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>Hazer/sentry-java<file_sep>/sentry/src/main/java/io/sentry/marshaller/json/SentryJsonGenerator.java
package io.sentry.marshaller.json;
import io.sentry.marshaller.json.connector.JsonGenerator;
import io.sentry.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Map;
/**
* JsonGenerator that makes an attempt at serializing any Java POJO to the "best"
* JSON representation. For example, iterables should become JSON arrays, Maps should
* become JSON objects, etc. As a fallback we use {@link Object#toString()}.
*
* Every method except {@link JsonGenerator#writeObject(Object)} is proxied to an
* underlying {@link JsonGenerator}.
*/
public class SentryJsonGenerator implements JsonGenerator {
private static final Logger logger = LoggerFactory.getLogger(Util.class);
private static final String RECURSION_LIMIT_HIT = "<recursion limit hit>";
private static final int MAX_LENGTH_LIST = 10;
private static final int MAX_SIZE_MAP = 50;
private static final int MAX_LENGTH_STRING = 400;
private static final int MAX_NESTING = 3;
private static final String ELIDED = "...";
private int maxLengthList;
private int maxLengthString;
private int maxSizeMap;
private int maxNesting;
private JsonGenerator generator;
/**
* Construct a JsonObjectMarshaller with the default configuration.
*
* @param generator Underlying JsonGenerator used for actual writing
*/
public SentryJsonGenerator(JsonGenerator generator) {
this.generator = generator;
this.maxLengthList = MAX_LENGTH_LIST;
this.maxLengthString = MAX_LENGTH_STRING;
this.maxSizeMap = MAX_SIZE_MAP;
this.maxNesting = MAX_NESTING;
}
/**
* Serialize any object to JSON. Large collections are elided.
*
* @param value Value to write out.
* @throws IOException On Jackson error (unserializable object).
*/
public void writeObject(Object value) throws IOException {
writeObject(value, 0);
}
private void writeObject(Object value, int recursionLevel) throws IOException {
if (recursionLevel >= maxNesting) {
generator.writeString(RECURSION_LIMIT_HIT);
return;
}
if (value == null) {
generator.writeNull();
} else if (value.getClass().isArray()) {
generator.writeStartArray();
writeArray(value, recursionLevel);
generator.writeEndArray();
} else if (value instanceof Map) {
generator.writeStartObject();
int i = 0;
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
if (i >= maxSizeMap) {
break;
}
if (entry.getKey() == null) {
generator.writeFieldName("null");
} else {
generator.writeFieldName(Util.trimString(entry.getKey().toString(), maxLengthString));
}
writeObject(entry.getValue(), recursionLevel + 1);
i++;
}
generator.writeEndObject();
} else if (value instanceof Collection) {
generator.writeStartArray();
int i = 0;
for (Object subValue : (Collection<?>) value) {
if (i >= maxLengthList) {
writeElided();
break;
}
writeObject(subValue, recursionLevel + 1);
i++;
}
generator.writeEndArray();
} else if (value instanceof String) {
generator.writeString(Util.trimString((String) value, maxLengthString));
} else {
try {
/** @see com.fasterxml.jackson.core.JsonGenerator#_writeSimpleObject(Object) */
generator.writeObject(value);
} catch (IllegalStateException e) {
logger.debug("Couldn't marshal '{}' of type '{}', had to be converted into a String",
value, value.getClass());
generator.writeString(Util.trimString(value.toString(), maxLengthString));
}
}
}
private void writeArray(Object value,
int recursionLevel) throws IOException {
if (value instanceof byte[]) {
byte[] byteArray = (byte[]) value;
for (int i = 0; i < byteArray.length && i < maxLengthList; i++) {
generator.writeNumber((int) byteArray[i]);
}
if (byteArray.length > maxLengthList) {
writeElided();
}
} else if (value instanceof short[]) {
short[] shortArray = (short[]) value;
for (int i = 0; i < shortArray.length && i < maxLengthList; i++) {
generator.writeNumber((int) shortArray[i]);
}
if (shortArray.length > maxLengthList) {
writeElided();
}
} else if (value instanceof int[]) {
int[] intArray = (int[]) value;
for (int i = 0; i < intArray.length && i < maxLengthList; i++) {
generator.writeNumber(intArray[i]);
}
if (intArray.length > maxLengthList) {
writeElided();
}
} else if (value instanceof long[]) {
long[] longArray = (long[]) value;
for (int i = 0; i < longArray.length && i < maxLengthList; i++) {
generator.writeNumber(longArray[i]);
}
if (longArray.length > maxLengthList) {
writeElided();
}
} else if (value instanceof float[]) {
float[] floatArray = (float[]) value;
for (int i = 0; i < floatArray.length && i < maxLengthList; i++) {
generator.writeNumber(floatArray[i]);
}
if (floatArray.length > maxLengthList) {
writeElided();
}
} else if (value instanceof double[]) {
double[] doubleArray = (double[]) value;
for (int i = 0; i < doubleArray.length && i < maxLengthList; i++) {
generator.writeNumber(doubleArray[i]);
}
if (doubleArray.length > maxLengthList) {
writeElided();
}
} else if (value instanceof char[]) {
char[] charArray = (char[]) value;
for (int i = 0; i < charArray.length && i < maxLengthList; i++) {
generator.writeString(String.valueOf(charArray[i]));
}
if (charArray.length > maxLengthList) {
writeElided();
}
} else if (value instanceof boolean[]) {
boolean[] boolArray = (boolean[]) value;
for (int i = 0; i < boolArray.length && i < maxLengthList; i++) {
generator.writeBoolean(boolArray[i]);
}
if (boolArray.length > maxLengthList) {
writeElided();
}
} else {
Object[] objArray = (Object[]) value;
for (int i = 0; i < objArray.length && i < maxLengthList; i++) {
writeObject(objArray[i], recursionLevel + 1);
}
if (objArray.length > maxLengthList) {
writeElided();
}
}
}
private void writeElided() throws IOException {
generator.writeString(ELIDED);
}
public void setMaxLengthList(int maxLengthList) {
this.maxLengthList = maxLengthList;
}
public void setMaxLengthString(int maxLengthString) {
this.maxLengthString = maxLengthString;
}
public void setMaxSizeMap(int maxSizeMap) {
this.maxSizeMap = maxSizeMap;
}
public void setMaxNesting(int maxNesting) {
this.maxNesting = maxNesting;
}
@Override
public void writeStartArray() throws IOException {
generator.writeStartArray();
}
@Override
public void writeStringField(String fieldName, String value) throws IOException {
generator.writeStringField(fieldName, value);
}
@Override
public void writeArrayFieldStart(String fieldName) throws IOException {
generator.writeArrayFieldStart(fieldName);
}
@Override
public void writeBooleanField(String fieldName, boolean value) throws IOException {
generator.writeBooleanField(fieldName, value);
}
@Override
public void writeObjectFieldStart(String fieldName) throws IOException {
generator.writeObjectFieldStart(fieldName);
}
@Override
public void writeObjectField(String fieldName, Object value) throws IOException {
generator.writeObjectField(fieldName, value);
}
@Override
public void writeNullField(String fieldName) throws IOException {
generator.writeNullField(fieldName);
}
@Override
public void writeEndArray() throws IOException {
generator.writeEndArray();
}
@Override
public void writeStartObject() throws IOException {
generator.writeStartObject();
}
@Override
public void writeEndObject() throws IOException {
generator.writeEndObject();
}
@Override
public void writeFieldName(String name) throws IOException {
generator.writeFieldName(name);
}
@Override
public void writeString(String text) throws IOException {
generator.writeString(text);
}
@Override
public void writeNumber(int v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(long v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(BigInteger v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(double v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(float v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(BigDecimal v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(String encodedValue) throws IOException {
generator.writeNumber(encodedValue);
}
@Override
public void writeBoolean(boolean state) throws IOException {
generator.writeBoolean(state);
}
@Override
public void writeNull() throws IOException {
generator.writeNull();
}
@Override
public void writeNumberField(String fieldName, BigDecimal value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, float value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, double value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, long value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, int value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void close() throws IOException {
generator.close();
}
}
<file_sep>/sentry-gson-factory/README.md
# sentry-gson-factory
See the [Sentry documentation](https://docs.sentry.io/clients/java/) for more information.
<file_sep>/sentry-json-connector/src/main/java/io/sentry/marshaller/json/connector/classloading/UnknownClassException.java
package io.sentry.marshaller.json.connector.classloading;
/**
* Exception when class not found in runtime classpath.
*/
class UnknownClassException extends RuntimeException {
/**
* Class not found in runtime exception.
*
* @param msg Reason message.
*/
UnknownClassException(String msg) {
super(msg);
}
}
<file_sep>/sentry-jackson-factory/src/main/java/io/sentry/marshaller/json/generator/JacksonGenerator.java
package io.sentry.marshaller.json.generator;
import io.sentry.marshaller.json.connector.JsonGenerator;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Jackson Json Generator Facade, it just delegates directly to <code>com.fasterxml.jackson.core.JsonGenerator</code>.
*/
public class JacksonGenerator implements JsonGenerator {
private final com.fasterxml.jackson.core.JsonGenerator generator;
/**
* Creates a new facade delegating to parameter generator.
*
* @param generator Jackson Core JsonGenerator instance.
*/
public JacksonGenerator(com.fasterxml.jackson.core.JsonGenerator generator) {
this.generator = generator;
}
@Override
public void writeObject(Object value) throws IOException {
generator.writeObject(value);
}
@Override
public void writeStartArray() throws IOException {
generator.writeStartArray();
}
@Override
public void writeStringField(String fieldName, String value) throws IOException {
generator.writeStringField(fieldName, value);
}
@Override
public void writeArrayFieldStart(String fieldName) throws IOException {
generator.writeArrayFieldStart(fieldName);
}
@Override
public void writeBooleanField(String fieldName, boolean value) throws IOException {
generator.writeBooleanField(fieldName, value);
}
@Override
public void writeObjectFieldStart(String fieldName) throws IOException {
generator.writeObjectFieldStart(fieldName);
}
@Override
public void writeObjectField(String fieldName, Object value) throws IOException {
generator.writeObjectField(fieldName, value);
}
@Override
public void writeNullField(String fieldName) throws IOException {
generator.writeNullField(fieldName);
}
@Override
public void writeEndArray() throws IOException {
generator.writeEndArray();
}
@Override
public void writeStartObject() throws IOException {
generator.writeStartObject();
}
@Override
public void writeEndObject() throws IOException {
generator.writeEndObject();
}
@Override
public void writeFieldName(String name) throws IOException {
generator.writeFieldName(name);
}
@Override
public void writeString(String text) throws IOException {
generator.writeString(text);
}
@Override
public void writeNumber(int v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(long v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(BigInteger v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(double v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(float v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(BigDecimal v) throws IOException {
generator.writeNumber(v);
}
@Override
public void writeNumber(String encodedValue) throws IOException {
generator.writeNumber(encodedValue);
}
@Override
public void writeBoolean(boolean state) throws IOException {
generator.writeBoolean(state);
}
@Override
public void writeNull() throws IOException {
generator.writeNull();
}
@Override
public void writeNumberField(String fieldName, BigDecimal value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, float value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, double value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, long value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void writeNumberField(String fieldName, int value) throws IOException {
generator.writeNumberField(fieldName, value);
}
@Override
public void close() throws IOException {
generator.close();
}
}
<file_sep>/sentry-jackson-factory/src/main/java/io/sentry/marshaller/json/factory/JsonFactoryImpl.java
package io.sentry.marshaller.json.factory;
import io.sentry.marshaller.json.connector.JsonFactory;
import io.sentry.marshaller.json.connector.JsonGenerator;
import io.sentry.marshaller.json.generator.JacksonGenerator;
import java.io.IOException;
import java.io.OutputStream;
/**
* JsonFactory implementation for runtime Jackson Injection.
*/
public class JsonFactoryImpl implements JsonFactory {
private final com.fasterxml.jackson.core.JsonFactory jsonFactory = new com.fasterxml.jackson.core.JsonFactory();
@Override
public JsonGenerator createGenerator(OutputStream destination) throws IOException {
return wrap(jsonFactory.createGenerator(destination));
}
private JsonGenerator wrap(com.fasterxml.jackson.core.JsonGenerator generator) {
return new JacksonGenerator(generator);
}
}
<file_sep>/sentry-gson-factory/src/main/java/io/sentry/marshaller/json/generator/GsonGenerator.java
package io.sentry.marshaller.json.generator;
import com.google.gson.stream.JsonWriter;
import io.sentry.marshaller.json.connector.JsonGenerator;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Gson Json Generator Facade, it just delegates directly to <code>com.fasterxml.jackson.core.JsonGenerator</code>.
*/
public class GsonGenerator implements JsonGenerator {
private final JsonWriter writer;
/**
* Creates a new facade delegating to @{@code com.google.gson.stream.JsonWriter}.
*
* @param destination Destination OutputStream whose Json will be written.
*/
public GsonGenerator(OutputStream destination) {
this.writer = new JsonWriter(new OutputStreamWriter(destination));
}
@Override
public void writeStartObject() throws IOException {
writer.beginObject();
}
@Override
public void writeStringField(String fieldName, String value) throws IOException {
writer.name(fieldName).value(value);
}
@Override
public void writeArrayFieldStart(String fieldName) throws IOException {
writer.name(fieldName).beginArray();
}
@Override
public void writeString(String value) throws IOException {
writer.value(value);
}
@Override
public void writeEndArray() throws IOException {
writer.endArray();
}
@Override
public void writeEndObject() throws IOException {
writer.endObject();
}
@Override
public void writeNull() throws IOException {
writer.nullValue();
}
@Override
public void writeStartArray() throws IOException {
writer.beginArray();
}
@Override
public void writeFieldName(String fieldName) throws IOException {
writer.name(fieldName);
}
@Override
public void writeObject(Object value) throws IOException {
writeSimpleObject(value);
}
@Override
public void writeObjectField(String fieldName, Object value) throws IOException {
writer.name(fieldName);
writeSimpleObject(value);
}
/**
* Tries to write object value to simple types or error out.
*
* @param value any object value.
* @throws IOException when there's and issue with output stream.
*/
private void writeSimpleObject(Object value) throws IOException {
if (value == null) {
this.writeNull();
} else if (value instanceof String) {
this.writeString((String) value);
} else {
if (value instanceof Number) {
Number n = (Number) value;
this.writeNumber(n);
return;
} else {
if (value instanceof byte[]) {
this.writeBinary((byte[]) value);
return;
}
if (value instanceof Boolean) {
this.writeBoolean((Boolean) value);
return;
}
if (value instanceof AtomicBoolean) {
this.writeBoolean(((AtomicBoolean) value).get());
return;
}
}
throw new IllegalStateException(GsonGenerator.class.getSimpleName()
+ " can only serialize simple wrapper types (type passed "
+ value.getClass().getName()
+ ")");
}
}
/**
* NOT SUPPORTED YET.
* Writes byte array to json output as field value.
*
* @param bytes byte array object.
*/
private void writeBinary(byte[] bytes) {
throw new IllegalStateException(GsonGenerator.class.getSimpleName()
+ " don't support serializing byte[] yet.");
}
private void writeNumber(Number number) throws IOException {
writer.value(number);
}
@Override
public void writeBoolean(boolean state) throws IOException {
writer.value(state);
}
@Override
public void writeBooleanField(String fieldName, boolean value) throws IOException {
writer.name(fieldName).value(value);
}
@Override
public void writeObjectFieldStart(String fieldName) throws IOException {
writer.name(fieldName).beginObject();
}
@Override
public void writeNullField(String fieldName) throws IOException {
writer.name(fieldName).nullValue();
}
@Override
public void writeNumber(String encodedValue) throws IOException {
try {
writer.value(new BigInteger(encodedValue));
} catch (Exception iError) {
try {
writer.value(new BigDecimal(encodedValue));
} catch (Exception dError) {
writer.value(encodedValue);
}
}
}
@Override
public void writeNumber(BigDecimal value) throws IOException {
writer.value(value);
}
@Override
public void writeNumber(float value) throws IOException {
writer.value(value);
}
@Override
public void writeNumber(double value) throws IOException {
writer.value(value);
}
@Override
public void writeNumber(long value) throws IOException {
writer.value(value);
}
@Override
public void writeNumber(int value) throws IOException {
writer.value(value);
}
@Override
public void writeNumberField(String fieldName, BigDecimal value) throws IOException {
writer.name(fieldName).value(value);
}
@Override
public void writeNumberField(String fieldName, float value) throws IOException {
writer.name(fieldName).value(value);
}
@Override
public void writeNumberField(String fieldName, double value) throws IOException {
writer.name(fieldName).value(value);
}
@Override
public void writeNumberField(String fieldName, long value) throws IOException {
writer.name(fieldName).value(value);
}
@Override
public void writeNumberField(String fieldName, int value) throws IOException {
writer.name(fieldName).value(value);
}
@Override
public void writeNumber(BigInteger value) throws IOException {
writer.value(value);
}
@Override
public void close() throws IOException {
writer.close();
}
}
<file_sep>/sentry-json-connector/src/main/java/io/sentry/marshaller/json/connector/classloading/Classes.java
package io.sentry.marshaller.json.connector.classloading;
/**
* A simple Classloader helper.
* <p>
* Based on:
* [https://github.com/jwtk/jjwt/
* blob/8afca0d0df6248a017f6004dfc6f692f0463545c/src/main/java/io/jsonwebtoken/lang/Classes.java]
*/
public final class Classes {
private static final Classes.ClassLoaderAccessor THREAD_CL_ACCESSOR = new Classes.ExceptionIgnoringAccessor() {
@Override
protected ClassLoader doGetClassLoader() throws Throwable {
return Thread.currentThread().getContextClassLoader();
}
};
private static final Classes.ClassLoaderAccessor CLASS_CL_ACCESSOR = new Classes.ExceptionIgnoringAccessor() {
@Override
protected ClassLoader doGetClassLoader() throws Throwable {
return Classes.class.getClassLoader();
}
};
private static final Classes.ClassLoaderAccessor SYSTEM_CL_ACCESSOR = new Classes.ExceptionIgnoringAccessor() {
@Override
protected ClassLoader doGetClassLoader() throws Throwable {
return ClassLoader.getSystemClassLoader();
}
};
private Classes() {
}
/**
* Attempts to load the specified class name from the current thread's
* {@link Thread#getContextClassLoader() context class loader}, then the
* current ClassLoader (<code>Classes.class.getClassLoader()</code>), then the system/application
* ClassLoader (<code>ClassLoader.getSystemClassLoader()</code>, in that order. If any of them cannot locate
* the specified class, an <code>UnknownClassException</code> is thrown (our RuntimeException equivalent of
* the JRE's <code>ClassNotFoundException</code>.
*
* @param fullyQualifiedClassName the fully qualified class name to load
* @param <T> Class type found.
* @return the located class
* @throws UnknownClassException if the class cannot be found.
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> forName(String fullyQualifiedClassName) throws UnknownClassException {
Class clazz = THREAD_CL_ACCESSOR.loadClass(fullyQualifiedClassName);
if (clazz == null) {
clazz = CLASS_CL_ACCESSOR.loadClass(fullyQualifiedClassName);
}
if (clazz == null) {
clazz = SYSTEM_CL_ACCESSOR.loadClass(fullyQualifiedClassName);
}
if (clazz == null) {
String msg = "Unable to load class named [" + fullyQualifiedClassName + "] from the thread context, "
+ "current, or system/application ClassLoaders. "
+ "All heuristics have been exhausted. Class could not be found.";
throw new UnknownClassException(msg);
}
return clazz;
}
/**
* Checks if classname is available in classpath.
*
* @param fullyQualifiedClassName classname to search for.
* @return if class is available in runtime.
*/
public static boolean isAvailable(String fullyQualifiedClassName) {
try {
forName(fullyQualifiedClassName);
return true;
} catch (UnknownClassException e) {
return false;
}
}
/**
* Instantiate class from given name using no-arguments constructor.
* @param fullyQualifiedClassName Classname to instantiate.
* @param <T> Class type.
* @return New T class instance.
*/
@SuppressWarnings("unchecked")
public static <T> T newInstance(String fullyQualifiedClassName) {
return (T) newInstance(forName(fullyQualifiedClassName));
}
/**
* Instantiate given Class using no-arguments constructor.
* @param clazz Class to instantiate.
* @param <T> Class type.
* @return New T class instance.
*/
public static <T> T newInstance(Class<T> clazz) {
if (clazz == null) {
String msg = "Class method parameter cannot be null.";
throw new IllegalArgumentException(msg);
}
try {
return clazz.newInstance();
} catch (Exception e) {
throw new InstantiationException("Unable to instantiate class [" + clazz.getName() + "]", e);
}
}
private interface ClassLoaderAccessor {
Class loadClass(String fullyQualifiedClassName);
}
private abstract static class ExceptionIgnoringAccessor implements Classes.ClassLoaderAccessor {
public Class loadClass(String fqcn) {
Class clazz = null;
ClassLoader cl = getClassLoader();
if (cl != null) {
try {
clazz = cl.loadClass(fqcn);
} catch (ClassNotFoundException e) {
//Class couldn't be found by loader
}
}
return clazz;
}
protected final ClassLoader getClassLoader() {
try {
return doGetClassLoader();
} catch (Throwable t) {
//Unable to get ClassLoader
}
return null;
}
protected abstract ClassLoader doGetClassLoader() throws Throwable;
}
}
<file_sep>/docs/index.rst
.. sentry:edition:: self
Sentry Java
===========
.. sentry:edition:: on-premise, hosted
.. class:: platform-java
Java
====
Sentry for Java is the official Java SDK for Sentry. At its core it provides
a raw client for sending events to Sentry, but it is highly recommended that you
use one of the included library or framework integrations listed below if at all possible.
**Note:** The old ``raven`` library is no longer maintained. It is highly recommended that
you `migrate <https://docs.sentry.io/clients/java/migration/>`_ to ``sentry`` (which this
documentation covers). `Check out the migration guide <https://docs.sentry.io/clients/java/migration/>`_
for more information. If you are still using ``raven`` you can
`find the old documentation here <https://github.com/getsentry/sentry-java/blob/raven-java-8.x/docs/modules/raven.rst>`_.
.. toctree::
:maxdepth: 2
:titlesonly:
config
context
usage
agent
migration
modules/index
Resources:
* `Documentation <https://docs.sentry.io/clients/java/>`_
* `Examples <https://github.com/getsentry/examples>`_
* `Bug Tracker <http://github.com/getsentry/sentry-java/issues>`_
* `Code <http://github.com/getsentry/sentry-java>`_
* `Mailing List <https://groups.google.com/group/getsentry>`_
* `IRC <irc://irc.freenode.net/sentry>`_ (irc.freenode.net, #sentry)
* `Travis CI <http://travis-ci.org/getsentry/sentry-java>`_
<file_sep>/docs/modules/index.rst
.. _integrations:
Integrations
============
The Sentry Java SDK comes with support for some frameworks and libraries so that
you don't have to capture and send errors manually.
.. toctree::
:maxdepth: 1
android
appengine
jul
log4j
log4j2
logback
spring
<file_sep>/docs/context.rst
Context & Breadcrumbs
=====================
The Java SDK implements the idea of a "context" to support attaching additional
information to events, such as breadcrumbs. A context may refer to a single
request to a web framework, to the entire lifetime of an Android application,
or something else that better suits your application's needs.
There is no single definition of context that applies to every application,
for this reason a specific implementation must be chosen depending on what your
application does and how it is structured. By default Sentry uses a
``ThreadLocalContextManager`` that maintains a single ``Context`` instance per thread.
This is useful for frameworks that use one thread per user request such as those based
on synchronous servlet APIs. Sentry also installs a ``ServletRequestListener`` that will
clear the thread's context after each servlet request finishes.
Sentry defaults to the ``SingletonContextManager`` on Android, which maintains a single
context instance for all threads for the lifetime of the application.
To override the ``ContextManager`` you will need to override the ``getContextManager``
method in the ``DefaultSentryClientFactory``. A simpler API will likely be provided in
the future.
Usage
-----
Breadcrumbs can be used to describe actions that occurred in your application leading
up to an event being sent. For example, whether external API requests were made,
or whether a user clicked on something in an Android application. By default the last
100 breadcrumbs per context will be stored and sent with future events.
The user can be set per context so that you know who was affected by each event.
Once a ``SentryClient`` instance has been initialized you can begin setting state in
the current context.
.. sourcecode:: java
import io.sentry.Sentry;
import io.sentry.context.Context;
import io.sentry.event.BreadcrumbBuilder;
import io.sentry.event.UserBuilder;
public class MyClass {
/**
* Examples using the (recommended) static API.
*/
public void staticAPIExample() {
// Manually initialize the static client, you may also pass in a DSN and/or
// SentryClientFactory to use. Note that the client will attempt to automatically
// initialize on the first use of the static API, so this isn't strictly necessary.
Sentry.init();
// Note that all fields set on the context are optional. Context data is copied onto
// all future events in the current context (until the context is cleared).
// Set the current user in the context.
Sentry.getContext().setUser(
new UserBuilder().setUsername("user1").build()
);
// Record a breadcrumb in the context.
Sentry.getContext().recordBreadcrumb(
new BreadcrumbBuilder().setMessage("User did something specific again!").build()
);
// Add extra data to future events in this context.
Sentry.getContext().addExtra("extra", "thing");
// Add an additional tag to future events in this context.
Sentry.getContext().addTag("tagName", "tagValue");
// Send an event with the context data attached.
Sentry.capture("New event message");
// Clear the context, useful if you need to add hooks in a framework
// to empty context between requests.
Sentry.clearContext();
}
/**
* Examples that use the SentryClient instance directly.
*/
public void instanceAPIExample() {
// Create a SentryClient instance that you manage manually.
SentryClient sentryClient = SentryClientFactory.sentryClient();
// Get the current context instance.
Context context = sentryClient.getContext();
// Note that all fields set on the context are optional. Context data is copied onto
// all future events in the current context (until the context is cleared).
// Set the current user in the context.
context.setUser(
new UserBuilder().setUsername("user1").build()
);
// Record a breadcrumb in the context.
context.recordBreadcrumb(
new BreadcrumbBuilder().setMessage("User did something specific!").build()
);
// Add extra data to future events in this context.
context.addExtra("extra", "thing");
// Add an additional tag to future events in this context.
context.addTag("tagName", "tagValue");
// Send an event with the context data attached.
sentryClient.sendMessage("New event message");
// Clear the context, useful if you need to add hooks in a framework
// to empty context between requests.
context.clear();
}
}
<file_sep>/sentry-jackson-factory/README.md
# sentry-jackson-factory
See the [Sentry documentation](https://docs.sentry.io/clients/java/) for more information.
| c3af24a3a298154cce83c26d64292c01987e7c8c | [
"Markdown",
"Java",
"reStructuredText"
] | 11 | Java | Hazer/sentry-java | 0a7c8feaed05cc425b13ee158ae72a52fd0c09f2 | 23a64ed9374dcc8ecc9853afd06e34c37fb36a27 |
refs/heads/master | <repo_name>kevkim11/Marshawns_Skittle_Crusher<file_sep>/lcdnumber.h
/** @file LCDNumber.h
@author <NAME>
@date
@brief This is a header file for the LCDNumber class. The class is defined within this header file.
This file contains the list of functions and variable used in LCDNumber.
The LCDNumber class contains the timer for the game.
It keeps track of the game time.
*/
#ifndef LCDNUMBER_H
#define LCDNUMBER_H
#include <QLCDNumber>
#include <QTimer>
#include <QTime>
#include <QLabel>
#include "gameboard.h"
class LCDNumber: public QLabel
{
Q_OBJECT
public:
QTimer* timer;
QTime* timeValue;
int sec;
int set_min;
int set_sec;
public:
/** LCDNumber Constructor
* @brief builds the clock object used as a timer in the game
*/
LCDNumber(QWidget * parentWidget,int minutes,int seconds)
{
set_min = minutes;
set_sec = seconds;
timer = new QTimer();
timeValue = new QTime(0,minutes,seconds);
sec = minutes*60 + seconds;
this->setParent(parentWidget);
this->setText(timeValue->toString());
QObject::connect(timer,SIGNAL(timeout()),this,SLOT(setDisplay()));
};
~ LCDNumber(){};
int getSeconds() { return sec;}
void start() { timer->start();}
void stop() { timer->stop();}
void restart(){
timeValue->setHMS(0, set_min, set_sec, 0);
sec = set_min*60+set_sec;
}
public slots:
void setDisplay()
{
this->timeValue->setHMS(0,this->timeValue->addSecs(-1).minute(),this->timeValue->addSecs(-1).second());
sec--;
this->setText(this->timeValue->toString());
};
};
#endif
<file_sep>/instructions.h
/** @file instructions.h
@author <NAME>
@date May 28, 2015
@brief This is a header file for the instructions class.
Creates a Window that shows the Instructions on how to play the game.
*/
#ifndef INSTRUCTIONS_H
#define INSTRUCTIONS_H
#include <QMainWindow>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QWidget>
#include <QPixmap>
class MainWindow;
class instructions : public QWidget
{
Q_OBJECT
public:
explicit instructions(QWidget *parent = 0);
~instructions();
private:
MainWindow* mw;
};
#endif // INSTRUCTIONS_H
<file_sep>/gameboard.cpp
/** @file gameboard.cpp
@author <NAME>
@brief This is the main source file for the gameboard class.
Has the constructor to build a gameboard object. The parent widget is set to mainwindow when the game is started.
*/
#include "gameboard.h"
#include "ui_gameboard.h"
// Random number generator for C++11
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
//std::uniform_int_distribution<int> distribution(0,14); // generates a number from 0 - 14
std::uniform_int_distribution<int> skittles_colors(1,6);//generates a number from 1 - 6
/** Creates a gameboard object based on the paramenters which are set
@param parent is the Qwidget object - In this case the parent widget is set to as the MainWindow
@param timer is the timer object on the board
@param clock keeps track of time
*/
gameboard::gameboard(QWidget *parent, size_t board_sz, int min) :
QWidget(parent),board_size(board_sz), minute(min)
{
setStyleSheet("background-color: red;");
///Marshawn Lynch Image Loading
QString fileName(":/images/Marshawn Lynch BoardPiece.jpeg");
marshawns_image = new QPixmap(fileName);
/************** Skittle images **************/
QString filename_red_skittle(":/images/Red Skittle.gif");
red_skittle = new QPixmap(filename_red_skittle);
QString filename_orange_skittle(":/images/Orange Skittle.gif");
orange_skittle = new QPixmap(filename_orange_skittle);
QString filename_green_skittle(":/images/Green Skittle.gif");
green_skittle = new QPixmap(filename_green_skittle);
QString filename_yellow_skittle(":/images/Yellow Skittle.gif");
yellow_skittle = new QPixmap(filename_yellow_skittle);
QString filename_purple_skittle(":/images/Purple Skittle.gif");
purple_skittle = new QPixmap(filename_purple_skittle);
/************** Top Bar **************/
QFont Helvetica_italic( "Helvetica"); Helvetica_italic.setItalic(true);
Top = new QWidget;
Top->setStyleSheet("QLabel { background-color:white; "
"color:purple; "
"border-style: outset; "
"border-width:2px; "
"border-color: black }");
QLabel* life_label = new QLabel("Lives Remaining:");
life_label->setFont(Helvetica_italic);
// This code sets up the Top bar
// This layout will space out the elements above
QHBoxLayout *top_bar = new QHBoxLayout(Top);
lives_remaining = 3;
lives = new QLabel*[lives_remaining];
top_bar->addWidget(life_label);
// This line above is important, it is an array of QLabel POINTERS.
// You have to input heap memory pointers for the memory management system to work properly.
for(size_t i=0;i<lives_remaining;i++) {
lives[i] = new QLabel;
lives[i]->setPixmap(*marshawns_image);
lives[i]->setMinimumSize(30,30);
lives[i]->setMaximumSize(30,30);
lives[i]->setScaledContents(true);
top_bar->addWidget(lives[i]);
}
/************** Game Board Build **************/
///create board object for all the widgets to be laid out on
board = new QWidget;
labels = new QLabel*[board_size*board_size];
values = new int[board_size*board_size];
QGridLayout *SquareGrid = new QGridLayout(board);
SquareGrid->setGeometry(QRect());
SquareGrid->setSpacing(0);
/************** Board Layout **************/
/// Assigning all the values on the board to be 0
for(size_t i=0;i<board_size;i++) {
for(size_t j=0;j<board_size;j++) {
/// Assigning all the values to 0
values[i*board_size+j] = 0;
/// Create label and set properties.
labels[i*board_size+j] = new QLabel;
labels[i*board_size+j]->setMinimumSize(30,30);
labels[i*board_size+j]->setMaximumSize(30,30);
labels[i*board_size+j]->setStyleSheet("QLabel { background-color : white; color : black; }");
labels[i*board_size+j]->setFrameStyle(2);
labels[i*board_size+j]->setAlignment(Qt::AlignCenter);
///Each skittle color is assigned to a random number from 1-5. If the number is 6 then no skittle is added onto the gameboard
int number_color_conversion = skittles_colors(generator);
if (number_color_conversion<6){
if (number_color_conversion==1){
random_skittle=red_skittle;
values[i*board_size+j]=1;
}
if (number_color_conversion==2){
random_skittle=orange_skittle;
values[i*board_size+j]=2;
}
if (number_color_conversion==3){
random_skittle=yellow_skittle;
values[i*board_size+j]=3;
}
if (number_color_conversion==4){
random_skittle=green_skittle;
values[i*board_size+j]=4;
}
if (number_color_conversion==5){
random_skittle=purple_skittle;
values[i*board_size+j]=5;
}
labels[i*board_size+j]->setPixmap(*random_skittle);
labels[i*board_size+j]->setScaledContents(true);
}
/// Add label to the layout
SquareGrid->addWidget(labels[i*board_size+j] ,i,j);
}
std::cout << std::endl;
}
/// Initialize the marshawn at the top left corner, coordinate (0,0).
marshawns_position = new QPoint(0,0);
/************** Timer **************/
QLabel* time_remaining = new QLabel("Time Remaining:");
time_remaining->setFont(Helvetica_italic);
QFont clock_font( "Helvetica", 60, QFont::Bold);
timer = new QLabel;
clock = new LCDNumber(timer,minute,00);
clock->setFixedSize(280, 80);
clock->setFont(clock_font);
clock->setAlignment(Qt::AlignCenter);
clock->start();
clock->timer->start(1000); // starts the clock.
/************** Score Board **************/
QLabel* score_label = new QLabel("Score:");
score_label->setFont(Helvetica_italic);
score_lcd = new QLabel;
score_lcd->setNum(points);
score_lcd->setFixedSize(280,50);
score_lcd->setAlignment(Qt::AlignCenter);
QHBoxLayout* score_layout = new QHBoxLayout;
score_layout->addWidget(score_label);
score_layout->addWidget(score_lcd);
/************** crush_output/multiplier **************/
QLabel* crush_output_label = new QLabel("Type of Crush:");
crush_output_label->setFont(Helvetica_italic);
crush_output = new QLabel;
crush_output->setText(type_of_crush);
crush_output->setFixedSize(280,50);
crush_output->setAlignment(Qt::AlignCenter);
QHBoxLayout* crush_output_layout = new QHBoxLayout;
crush_output_layout->addWidget(crush_output_label);
crush_output_layout->addWidget(crush_output);
/************** score and crush output **************/
QVBoxLayout* score_and_multiplier = new QVBoxLayout;
score_and_multiplier->addLayout(score_layout);
score_and_multiplier->addLayout(crush_output_layout);
/************** Bottom **************/
Bottom = new QWidget;
Bottom->setStyleSheet("QLabel { background: red; color : white; }");
QHBoxLayout* bottom_bar = new QHBoxLayout(Bottom);
bottom_bar->addWidget(time_remaining);
bottom_bar->addWidget(clock);
bottom_bar->addLayout(score_and_multiplier);
/// Create a vertical box layout for the two pieces
QVBoxLayout* piece_together = new QVBoxLayout;
piece_together->addWidget(Top,0,Qt::AlignCenter);
piece_together->addWidget(board,0,Qt::AlignCenter);
piece_together->addWidget(Bottom,0,Qt::AlignCenter);
this->setLayout(piece_together);
}
/**
gameboard destructor
@brief deallocate the gameboard object and deletes the gameboard object variables
*/
gameboard::~gameboard()
{
delete [] values;
delete [] marshawns_position;
}
/**
keypressevent
@param
@return void
@brief assigns the keyboard keys to Marshawn moving on the board and the space bar is connected to crushSkittles function
*/
void gameboard::keyPressEvent(QKeyEvent *event){
size_t x = marshawns_position->rx();
size_t y = marshawns_position->ry();
switch (event->key()) {
case Qt::Key_Left:
if(marshawns_position->rx() != 0)
updateMarshawn(x,y,x-1,y);
break;
case Qt::Key_Right:
if(marshawns_position->rx() != board_size-1)
updateMarshawn(x,y,x+1,y);
break;
case Qt::Key_Up:
if(marshawns_position->ry() != 0)
updateMarshawn(x,y,x,y-1);
break;
case Qt::Key_Down:
if(marshawns_position->ry() != board_size-1)
updateMarshawn(x,y,x,y+1);
break;
case Qt::Key_Space:
crushSkittles(x,y);
break;
default:
QWidget::keyPressEvent(event);
}
game_is_over = false;
// Need both lines to force a repaint.
// This line forces processor to process all previously promised events.
QCoreApplication::processEvents();
// This one QUEUES up a repaint
repaint();
return;
}
/**
Update Marshawn Function
@param int previous_x, previous_y
int next_x, next_y
@return void
@brief used to update marshawn after he's been moved/crushed skittles on the board.
*/
void gameboard::updateMarshawn(int previous_x, int previous_y, int next_x, int next_y) {
///Clear the label that Marshawn was on first
labels[previous_y*board_size+previous_x]->clear();
///Then whatever values/skittles were placed in the label before, replace it back when Marshawn moves out of the board space
if(values[previous_y*board_size+previous_x]==1){
labels[previous_y*board_size+previous_x]->setPixmap(*red_skittle);
labels[previous_y*board_size+previous_x]->setScaledContents(true);
}
if(values[previous_y*board_size+previous_x]==2){
labels[previous_y*board_size+previous_x]->setPixmap(*orange_skittle);
labels[previous_y*board_size+previous_x]->setScaledContents(true);
}
if(values[previous_y*board_size+previous_x]==3){
labels[previous_y*board_size+previous_x]->setPixmap(*yellow_skittle);
labels[previous_y*board_size+previous_x]->setScaledContents(true);
}
if(values[previous_y*board_size+previous_x]==4){
labels[previous_y*board_size+previous_x]->setPixmap(*green_skittle);
labels[previous_y*board_size+previous_x]->setScaledContents(true);
}
if(values[previous_y*board_size+previous_x]==5){
labels[previous_y*board_size+previous_x]->setPixmap(*purple_skittle);
labels[previous_y*board_size+previous_x]->setScaledContents(true);
}
///Set's Marshawn's new positions
marshawns_position->setX(next_x);
marshawns_position->setY(next_y);
}
/**
Crush Skittles Function
* @param Marshawn's position (x,y)
* @return bool
* @brief function when the space bar is pressed
*/
bool gameboard::crushSkittles(int x, int y){
///Initialize the each of marshawn's vertical (up and down) and horizontal (left and right) axis
int a=1;
int left=values[(y*board_size)+(x-a)];
QLabel* left_label=labels[(y*board_size)+(x-a)];
int b=1;
int right = values[(y*board_size)+(x+b)];
QLabel* right_label = labels[(y*board_size)+(x+b)];
int c=1;
int up = values[((y-c)*board_size)+x];
QLabel* up_label = labels[((y-c)*board_size)+x];
int d=1;
int down = values[((y+d)*board_size)+x];
QLabel* down_label = labels[((y+d)*board_size)+x];
///If Marshawn is on the edges
//If marshawn's on the LEFT most side of the board
if(x==0)
{
left=0;
values[(y*board_size)+(x-a)]=0;
//std::cout<<"if(y<15&&x==0) worked for LEFT"<<std::endl;
}
//If Marshawn's right next to the LEFT edge BECAUSE it's already been initialized
//If LEFT is at the left_edge and has no skittle
else if((x-a)==0 && left==0)
{
left=0;
values[(y*board_size)+(x-a)]=0;
//std::cout<<"marshawn's right next to the LEFT edge = 0"<<std::endl;
}
///else While Marshawn's not at the LEFT edge
else
{
while(left==0){
a++;
left=values[y*board_size+(x-a)];
left_label=labels[y*board_size+(x-a)];
///when it reaches the edge with no skittle to the left most side
if((x-a)==0 && left==0){
left=0;
//std::cout<<"left edge = 0"<<std::endl;
break;
}
///when it reaches a skittle to the left, left=that skittle
else if(left!=0){
//if((x-a)==0){
//std::cout<<"left!=0 worked for L"<<std::endl;
break;
}
//a++;
}
}
///If marshawn's on the RIGHT most side of the board OR next to the right edge BECAUSE it's already been initialized
if(x==14)
{
right=0;
values[(y*board_size)+(x+b)]=0;
//std::cout<<"if(y<15&&x==14) worked for Right"<<std::endl;
}
//If Marshawn's right next to the RIGHT edge BECAUSE it's already been initialized
//If RIGHT is at the RIGHT_edge and has no skittle
else if((x+b)==14 && right==0)
{
right=0;
values[(y*board_size)+(x+b)]=0;
//std::cout<<"marshawn's right next to the RIGHT edge = 0"<<std::endl;
}
///else While Marshawn's not at the RIGHT edge
else
{
while(right==0){
b++;
right=values[y*board_size+(x+b)];
right_label=labels[y*board_size+(x+b)];
if((x+b)==14 && right==0){
right=0;
//std::cout<<"right edge = 0"<<std::endl;
break;
}
//when it reaches a skittle to the right, left=that skittle
else if(right!=0){
//if((x+b)==0){
//std::cout<<"right!=0 worked for R"<<std::endl;
break;
}
}
}
//If marshawn's on the UP most side of the board
if(y==0)
{
up=0;
values[((y-c)*board_size)+x]=0;
//std::cout<<"if(y==14) worked for Up"<<std::endl;
}
//If Marshawn's right next to the UP edge BECAUSE it's already been initialized
//If UP is at the UP_edge and has no skittle
else if((y-c)==0 && up==0)
{
up=0;
values[((y-c)*board_size)+x]=0;
//std::cout<<"marshawn's right next to the UP edge = 0"<<std::endl;
}
///else While Marshawn's not at the UP edge
else
{
while(up==0){
c++;
up=values[(y-c)*board_size+x];
up_label=labels[(y-c)*board_size+x];
//when UP reaches the top edge
if((y-c)==0 && up==0){
up=0;
//std::cout<<"up edge = 0"<<std::endl;
break;
}
//when UP reaches a skittle, up=that skittle
else if(up!=0){
//if((y-c)==0){
//std::cout<<"up!==0 for U"<<std::endl;
break;
}
}
}
//If marshawn's on the DOWN most side of the board
if(y==14)
{
down=0;
values[((y+d)*board_size)+x]=0;
//std::cout<<"marshawn's on the DOWN most side of the board"<<std::endl;
}
//If Marshawn's right next to the DOW edge BECAUSE it's already been initialized
//If DOWN is at the DOWN_edge and has no skittle
else if((y+d)==14 && down==0)
{
down=0;
values[((y+d)*board_size)+x]=0;
//std::cout<<"marshawn's right next to the DOWN edge = 0"<<std::endl;
}
///else While Marshawn's not at the DOWN edge
else
{
while(down==0){
d++;
down=values[(y+d)*board_size+x];
down_label=labels[(y+d)*board_size+x];
if((y+d)==14 && down==0){
down=0;
//std::cout<<"at down edge = 0"<<std::endl;
break;
}
else if(down!=0){
//if((y-c)==0){
//std::cout<<"not at down edge "<<down<<std::endl;
break;
}
}
}
//std::cout<<"L R U D"<< std::endl;
//std::cout<<left<< " " << right<< " " <<up<< " " <<down<< std::endl;
if(isValidCrush(x,y, left, right, up, down)) {
updateAfterCrush(true, values[y*board_size+(x-a)], values[y*board_size+(x+b)], values[(y-c)*board_size+x], values[(y+d)*board_size+x], left_label, right_label, up_label, down_label);
return true;
}
else {
updateAfterCrush(false, values[y*board_size+(x-a)], values[y*board_size+(x+b)], values[(y-c)*board_size+x], values[(y+d)*board_size+x], left_label, right_label, up_label, down_label);
return false;
}
}
/**
updateAfterCrush Function
* @brief updates the gameboard after skittles have been crushed. So if it's invalid crush then you lose a life or the game
* @param flag
* @return bool
*/
void gameboard::updateAfterCrush(bool flag, int& left, int& right, int& up, int& down, QLabel* left_label, QLabel* right_label, QLabel* up_label, QLabel* down_label){
if(flag){//True
///4 SAME SKITTLES LOGIC +12_Points
if(left==right && left==up && left==down){
left_label->clear();left=0;
right_label->clear();right=0;
up_label->clear();up=0;
down_label->clear();down=0;
//std::cout<<"left, right, up, and down have been crushed"<<std::endl;
//+ 12 POINTS
points+=12;
type_of_crush = "4 Skittle Crush, +12 Points";
return;
}
///2 2 SAME SKITTLES LOGIC +12_Points
///Have to be none-zeroes
if(left!=0 && right!=0 && up!=0 && down!=0){
if(left==right && up==down){
left_label->clear();left=0;
right_label->clear();right=0;
up_label->clear();up=0;
down_label->clear();down=0;
//std::cout<<"left, right, up, and down have been crushed"<<std::endl;
//+ 12 POINTS
points+=12;
type_of_crush = "4 Skittle Crush, +12 Points";
return;
}
if(left==up && right==down){
left_label->clear();left=0;
right_label->clear();right=0;
up_label->clear();up=0;
down_label->clear();down=0;
//std::cout<<"left, right, up, and down have been crushed"<<std::endl;
//+ 12 POINTS
points+=12;
type_of_crush = "4 Skittle Crush, +12 Points";
return;
}
if(left==down && right==up){
left_label->clear();left=0;
right_label->clear();right=0;
up_label->clear();up=0;
down_label->clear();down=0;
//std::cout<<"left, right, up, and down have been crushed"<<std::endl;
//+ 12 POINTS
points+=12;
type_of_crush = "4 Skittle Crush, +12 Points";
return;
}
}
///3 SAME SKITTLES LOGIC +6_Points
if(left==up && left==down){
up_label->clear();up=0;
down_label->clear();down=0;
left_label->clear();left=0;
//std::cout<<"up, down, left have been crushed"<<std::endl;
//+6 POINTS
points+=6;
type_of_crush = "3 Skittle Crush, +6 Points";
return;
}
if(left==right && left==up){
left_label->clear();left=0;
right_label->clear();right=0;
up_label->clear();up=0;
//std::cout<<"left, right, up have been crushed"<<std::endl;
//+6 POINTS
points+=6;
type_of_crush = "3 Skittle Crush, +6 Points";
return;
}
if(right==up && right==down){
up_label->clear();up=0;
down_label->clear();down=0;
right_label->clear();right=0;
//std::cout<<"up, down, right have been crushed"<<std::endl;
//+6 POINTS
points+=6;
type_of_crush = "3 Skittle Crush, +6 Points";
return;
}
if(left==right && left==down){
left_label->clear();left=0;
right_label->clear();right=0;
down_label->clear();down=0;
//std::cout<<"left, right, down have been crushed"<<std::endl;
//+6 POINTS
points+=6;
type_of_crush = "3 Skittle Crush, +6 Points";
return;
}
///TWO SAME SKITTLES LOGIC +2_Points
if(left==right && left!=0){
left_label->clear();left=0;
right_label->clear();right=0;
//std::cout<<"left and right have been crushed"<<std::endl;
///+2
points+=2;
type_of_crush = "2 Skittle Crush, +2 Points";
return;
}
if(up==down && up!=0){
up_label->clear();up=0;
down_label->clear();down=0;
//std::cout<<"up and down have been crushed"<<std::endl;
points+=2;
type_of_crush = "2 Skittle Crush, +2 Points";
return;
}
if(left==up && left!=0){
left_label->clear();left=0;
up_label->clear();up=0;
//std::cout<<"left and up have been crushed"<<std::endl;
//+2
points+=2;
type_of_crush = "2 Skittle Crush, +2 Points";
return;
}
if(left==down && left!=0){
left_label->clear();left=0;
down_label->clear();down=0;
//std::cout<<"left and down have been crushed"<<std::endl;
//+2
points+=2;
type_of_crush = "2 Skittle Crush, +2 Points";
return;
}
if(right==up && up!=0){
right_label->clear();right=0;
up_label->clear();up=0;
//std::cout<<"right and up have been crushed"<<std::endl;
//+2
points+=2;
type_of_crush = "2 Skittle Crush, +2 Points";
return;
}
if(right==down && right!=0){
right_label->clear();right=0;
down_label->clear();down=0;
//std::cout<<"right and down have been crushed"<<std::endl;
//+2
points+=2;
type_of_crush = "2 Skittle Crush, +2 Points";
return;
}
}
else {//false
///if it's an invalid CRUSH then lose a life or the game if life runs out.
if(lives_remaining > 0) {
lives_remaining--;
lives[lives_remaining]->clear();
type_of_crush = "INVALID CRUSH! You lost a life";
return;
}
else {
gamedone();
return;
}
}
game_is_over = false;
}
/**
* @brief Game logic to crush skittles based on Marshawn's position (@param)
* @param Marshawn's position (x,y)
* @return bool
*/
bool gameboard::isValidCrush(int x, int y, int left, int right, int up, int down) {
if(values[y*board_size+x]==0){
///if the skittles match but they CANNOT be 0 aka no skittles.
if((left==right && left!=0)||(up==down && up!=0) ||
(left==up&&left!=0)||(left==down && left!=0) ||
(right==up&&right!=0)||(right==down&&right!=0)){
return true;
}
else
return false;
}
return false;
}
/**
paintevent
@param
@return void
@brief Paints the gameboard, gameboard variable objects, and Marshawn
*/
void gameboard::paintEvent(QPaintEvent *e) {
if(game_is_over){
if(clock->getSeconds()==0) gamedone();
size_t x = marshawns_position->rx();
size_t y = marshawns_position->ry();
labels[y*board_size+x]->setPixmap(*marshawns_image);
labels[y*board_size+x]->setScaledContents(true);
/** Painting Score */
score_lcd->setNum(points);
/** Painting Skittles Crush*/
crush_output->setText(type_of_crush);
if(lives_remaining==0) gamedone();
}
game_is_over = true;
}
/**
ShowEvent
@param
@return
@brief
*/
void gameboard::showEvent(QShowEvent *e) {
this->activateWindow();
this->setFocus();
QWidget::showEvent(e);
}
/**
SLOT - Set GameOver Window
@param gameover* go
@brief When game is over, a GameOver Window pops up asking the user if he wants to "quit" or "play again"
*/
void gameboard::setGameOverWindow(gameover* go){
gameOver_object = go;
}
/**
Start Game Function
@param
@brief set's the MainWindow to the gameboard object
* Color of the board is set to red here
*/
void gameboard::startGame(){
this->setStyleSheet("background-color: red;");
show();
}
/**
Start Done/Game Over Function
@param
@brief set's the MainWindow to the gameboard object
* Color of the board is set to red here
*/
void gameboard::gamedone(){
clock->stop();
game_is_over=true;
gameOver_object->show();
}
<file_sep>/mainwindow.h
/** @file mainwindow.h
@author <NAME>
@date May 28, 2015
@brief This is a header file for the MainWindow class.
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QButtonGroup>
#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include "lcdnumber.h"
#include "gameboard.h"
#include "instructions.h"
#include "gameover.h"
#include <QPixmap>
class gameboard;
class instructions;
class gameover;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public slots:
void easy_game_begin();
void hard_game_begin();
void restart();
void setInstructionsWindow(instructions* i);
void setGameOver(gameover* go);
public:
explicit MainWindow(QWidget *parent = 0);
QPushButton* start_button;
QPushButton* hard_button;
QPushButton* easy_button;
~MainWindow();
private:
Ui::MainWindow *ui;
gameboard* GameBoard;
QButtonGroup* buttonGroup;
QVBoxLayout* final_layout;
QHBoxLayout* Easy_Hard_layout;
QLabel* welcome;
QPixmap* welcome_picture;
instructions* instruction_object;
QPushButton* instruction_button;
gameover* gameOver_object;
QWidget* central;
};
#endif // MAINWINDOW_H
<file_sep>/gameboard.h
/** @file gameboard.h
@author <NAME>
@date
@brief This is a header file for the gameboard class.
This file contains the list of functions and variable used in gameboard.
This gameboard is where the game is played.
*/
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include <QMainWindow>
#include <QLabel>
#include <QGridLayout>
#include <QVBoxLayout>
#include <chrono>
#include <random>
#include <iostream>
#include <QTimer>
#include <QKeyEvent>
#include <QHBoxLayout>
#include "lcdnumber.h"
#include "mainwindow.h"
#include <QKeyEvent>
#include <QSpacerItem>
#include "instructions.h"
#include <QString>
#include <QPixmap>
#include "gameover.h"
#include <QPushButton>
class LCDNumber;
class gameover;
namespace Ui {
class gameboard;
}
class gameboard : public QWidget
{
Q_OBJECT
signals:
void game_over();
public slots:
void startGame();
void gamedone();
public:
explicit gameboard(QWidget *parent = 0, size_t board_sz = 15, int min = 2);
void setGameOverWindow(gameover* go);
///Window Objects
gameover* gameOver_object;
void paintEvent(QPaintEvent *e);
void keyPressEvent(QKeyEvent *event);
void showEvent(QShowEvent *e);
size_t getBoard_Size(){return board_size;};
~gameboard();
private:
bool game_is_over=false;
///Board Variables - board_size, minutes on timer
size_t board_size;
int minute;
/** Board features */
QWidget* board;
QLabel** labels;
int* values;
/// Top bar variables
QLabel* lives_left_value;
QWidget* Top;
int lives_remaining;
QLabel** lives;
/// Bottom bar variables
QWidget* Bottom;
///Timer
QLabel* timer;
LCDNumber *clock;
///Score
QLabel* score_lcd;
int points = 0;
///Crunch Output
QLabel* crush_output;
QString type_of_crush;
///Marshawn Lynch Piece
const QPixmap* marshawns_image;
QPoint *marshawns_position;
///Game Logic Functions
bool crushSkittles();
bool crushSkittles(int x, int y);
void updateAfterCrush(bool flag, int& left, int& right, int& up, int& down, QLabel* left_label, QLabel* right_label, QLabel* up_label, QLabel* down_label);
bool isValidCrush(int x, int y, int left, int right,int up, int down);
void updateMarshawn(int px, int py, int nx, int ny);
///Skittles
QPixmap* red_skittle;
QPixmap* orange_skittle;
QPixmap* yellow_skittle;
QPixmap* green_skittle;
QPixmap* purple_skittle;
///This is the dummy skittle that will be randomly assigned to one of the colored skittles
QPixmap* random_skittle;
///updateMarshawn function
QLabel* current_under;
QLabel* next_under;
//Ui::gameboard *ui;
};
#endif // GAMEBOARD_H
<file_sep>/README.md
# Marshawns_Skittle_Crusher
/*This is a link to a YouTube video showing the gameplay.
https://www.youtube.com/watch?v=I63TRsuNdkc
*/
<file_sep>/main.cpp
#include "mainwindow.h"
#include <QApplication>
#include "gameboard.h"
#include "lcdnumber.h"
#include "gameover.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow* mw = new MainWindow;
instructions* i = new instructions;
mw->setInstructionsWindow(i);
mw->show();
return a.exec();
}
<file_sep>/gameover.cpp
/** @file gameover.cpp
@author <NAME>
@date May 28, 2015
@brief This is a source file for the gameover class.
This file contains the list of functions and variable used in gameover.
The gameover class is evoked when the player loses all of his life or the time runs out.
This class allows players to play again or end game.
*/
#include "gameover.h"
gameover::gameover(QWidget *parent):
QWidget(parent)
{
QFont helvetica_italisized_font( "Helvetica", 44, QFont::Bold);
helvetica_italisized_font.setItalic(true);
this->setStyleSheet("background-image:url(:/images/GameOverPic.jpg)");
setFixedSize(500,300);
/************** Title that says "Game Over" **************/
QLabel* title = new QLabel ("Game Over!");
title->setFont(helvetica_italisized_font);
title->setStyleSheet("QLabel {color : white; }");
title->setAttribute(Qt::WA_TranslucentBackground);
QHBoxLayout* title_layout = new QHBoxLayout;
title_layout->addWidget(title);
title_layout->setAlignment(title, Qt::AlignHCenter);
///CONVERTING INTS->QSTRING TO PORTRAY POINTS
// std::string s = std::to_string(42);
// QLabel* score = new QLabel;
/************** Buttons **************/
QHBoxLayout* buttons = new QHBoxLayout();
retry_button = new QPushButton("Retry");
retry_button->setStyleSheet("QPushButton { background-color:red; color:white; border-style: outset; border-width: 2px; border-color: white}");
no_button = new QPushButton("Quit");
no_button->setStyleSheet("QPushButton { background-color:red; color:white; border-style: outset; border-width: 2px; border-color: white}");
buttons->addWidget(retry_button);
buttons->addWidget(no_button);
QVBoxLayout* overall = new QVBoxLayout;
overall->addLayout(title_layout);
overall->setAlignment(title_layout, Qt::AlignTop);
overall->addLayout(buttons);
setLayout(overall);
}
///@param gameboard
void gameover::setGameboard(gameboard* b){
board = b;
///Closes the GameOver Window when the retry button is clicked
QObject::connect(retry_button,SIGNAL(clicked()), this,SLOT(close()));
}
///@param MainWindow
void gameover::setMainWindow(MainWindow* mw){
mainwindow = mw;
///Closes the MainWindow aka the Gameboard when the no/quit button is clicked
QObject::connect(no_button,SIGNAL(clicked()), mainwindow,SLOT(close()));
///Closes the gameover window when no/quit button is clicked
QObject::connect(no_button,SIGNAL(clicked()), this,SLOT(close()));
///Retry
QObject::connect(retry_button,SIGNAL(clicked()), mainwindow,SLOT(restart()));
}
gameover::~gameover()
{
}
<file_sep>/lcdnumber.cpp
#include "lcdnumber.h"
#include "ui_lcdnumber.h"
lcdnumber::lcdnumber(QWidget *parent) :
QWidget(parent),
ui(new Ui::lcdnumber)
{
ui->setupUi(this);
}
lcdnumber::~lcdnumber()
{
delete ui;
}
<file_sep>/instructions.cpp
/** @file instructions.cpp
@author <NAME>
@date May 28, 2015
@brief This is the source file for the Instructions class.
This file contains the constructor for the instruction window object that portrays the rules on how to play this game.
Also the destructor.
*/
#include "instructions.h"
/**
Instruction Constructor
*/
instructions::instructions(QWidget *parent) :
QWidget(parent)
{
setStyleSheet("background-color:red; color : white; font-weight: bold");
/************** Setting up fonts **************/
QFont* skittle_font=new QFont("Helvetica");
skittle_font->setItalic(true);
skittle_font->setPixelSize(96);
QFont s("Helvetica");
QFont f( "Verdana", 12);
QFont t( "Verdana", 24, QFont::Bold);
/************** Title that says "Instructions" **************/
QLabel* title = new QLabel ("Instructions");
title->setFont(t);
/************** Welcome **************/
QLabel* welcome = new QLabel("Help Marshawn crush skittles! The goal of this game is to achieve the highest number of points by crushing skittles in a limited amount of time.");
welcome->setWordWrap(true);
welcome->setFont(f);
/************** Diagram showing game pieces **************/
QPixmap* marshawn_lynch = new QPixmap(":/images/Marshawn Lynch BoardPiece.jpeg");
QPixmap* red_skittle = new QPixmap(":/images/Red Skittle.gif");
QPixmap* orange_skittle = new QPixmap(":/images/Orange Skittle.gif");
QPixmap* yellow_skittle = new QPixmap(":/images/Yellow Skittle.gif");
QPixmap* green_skittle = new QPixmap(":/images/Green Skittle.gif");
QPixmap* purple_skittle = new QPixmap(":/images/Purple Skittle.gif");
QLabel* m=new QLabel;
m->setPixmap(*marshawn_lynch);
m->setScaledContents(true);
m->setFixedSize(50,50);
QLabel* r=new QLabel;
r->setPixmap(*red_skittle);
r->setScaledContents(true);
r->setFixedSize(30,30);
QLabel* o=new QLabel;
o->setPixmap(*orange_skittle);
o->setScaledContents(true);
o->setFixedSize(30,30);
QLabel* y=new QLabel;
y->setPixmap(*yellow_skittle);
y->setScaledContents(true);
y->setFixedSize(30,30);
QLabel* g=new QLabel;
g->setPixmap(*green_skittle);
g->setScaledContents(true);
g->setFixedSize(30,30);
QLabel* p=new QLabel;
p->setPixmap(*purple_skittle);
p->setScaledContents(true);
p->setFixedSize(30,30);
QHBoxLayout* game_piece_diagrams = new QHBoxLayout;
QSpacerItem* horizontal_space = new QSpacerItem(100,10);
game_piece_diagrams->addWidget(m);
game_piece_diagrams->addSpacerItem(horizontal_space);
game_piece_diagrams->addWidget(r);
game_piece_diagrams->addWidget(o);
game_piece_diagrams->addWidget(y);
game_piece_diagrams->addWidget(g);
game_piece_diagrams->addWidget(p);
/************** basic rules **************/
///
QLabel* basic_rules = new QLabel("Move Marshawn to an empty spot and press the spacebar\n"
"If two or more skittles\n"
"1) are the same color\n"
"2) and are along Marshawn's vertical and horizontal axis\n"
"Marshawn will crush the skittles! When you crush skittles, they diassappear and you get points!");
basic_rules->setWordWrap(true);
/************** EXAMPLE **************/
QLabel* example = new QLabel("Example:\n"
"Move Marshawn to the green star and press the spacebar to crush the top and bottom green skittles and left and right purple skittles (Crush 4 skittles)\n"
"Move Marshawn to the purple star and press spacebar to crush the left, right, and bottom purple skittles (Crush 3 skittles)");
QPixmap* example_diagram = new QPixmap(":/images/Marshawn's Skittle Crusher - EXAMPLE.png");
QLabel* example_pic=new QLabel;
example_pic->setPixmap(*example_diagram);
example_pic->setScaledContents(true);
example_pic->setFixedSize(215,200);
//example_pic->setAlignment(Qt::AlignCenter);
/************** Point System/Easy and Hard **************/
QLabel* point_system = new QLabel("POINT SYSTEM: LOSS OF LIFE:\n"
"2 Skittle Crush x 1 multiplier = 2 Points You lose a life when you crush skittles when:\n"
"3 Skittle Crush x 2 multiplier = 6 Points 1) Marshawn is on a space with skittles on it\n"
"4 Skittle Crush x 3 multiplier = 12 Points 2) or you do an invalid crush aka none of the skittles match along Marshawn's vertical and horizontal axis\n"
"\n"
"Easy Mode = 1:00 minutes and small gameboard\n"
"Hard Mode = 2:00 minutes and big gameboard");
/************** Conclusion **************/
QLabel* conclusion = new QLabel("You are now ready to crush some skittles. Let's go Beast Mode!");
/************** final instruction layout **************/
QVBoxLayout* instruction_layout = new QVBoxLayout;
instruction_layout->addWidget(title);
instruction_layout->addWidget(welcome);
instruction_layout->addLayout(game_piece_diagrams);
instruction_layout->addWidget(basic_rules);
instruction_layout->addWidget(example);
instruction_layout->addWidget(example_pic);
instruction_layout->setAlignment(example_pic,Qt::AlignCenter);
instruction_layout->addWidget(point_system);
instruction_layout->addWidget(conclusion);
setLayout(instruction_layout);
}
instructions::~instructions()
{
}
<file_sep>/mainwindow.cpp
/** @file mainwindow.cpp
@author <NAME>
@date May 28, 2015
@brief MainWindow window constructor defintion.
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "lcdnumber.h"
#include "instructions.h"
/** MainWindow window constructor
@param
*/
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
///Set's the backgroun image of the MainWindow option to Marshawn Skittle Conference
this->setStyleSheet("background-image:url(:/images/marshawn-lynch-skittles-press-conference.png)");
this->resize(400, this->height());
this->resize(600, this->width());
///Initialize specific Title Font
QFont title_font( "Helvetica", 44, QFont::Bold);
title_font.setItalic(true);
welcome = new QLabel("Marshawn's Skittle Crusher");
welcome->setFont(title_font);
welcome->setStyleSheet("QLabel {color : white; }");
welcome->setAttribute(Qt::WA_TranslucentBackground);
QHBoxLayout* welcome_layout = new QHBoxLayout;
welcome_layout->addWidget(welcome);
welcome_layout->setAlignment(welcome, Qt::AlignHCenter);
///Easy/Hard Buttons
easy_button = new QPushButton("Easy");
easy_button->setStyleSheet("QPushButton { background-color:red; color:white; border-style: outset; border-width: 2px; border-color: white}");
QObject::connect(easy_button, SIGNAL(clicked()), this, SLOT(easy_game_begin()));
hard_button = new QPushButton("Hard");
hard_button->setStyleSheet("QPushButton { background-color:red; color:white; border-style: outset; border-width: 2px; border-color: white}");
QObject::connect(hard_button, SIGNAL(clicked()), this, SLOT(hard_game_begin()));
Easy_Hard_layout = new QHBoxLayout;
Easy_Hard_layout->addWidget(easy_button);
Easy_Hard_layout->addWidget(hard_button);
///Instruction Button
instruction_button = new QPushButton("Instructions");
instruction_button->setStyleSheet("QPushButton { background-color:red; color:white; border-style: outset; border-width: 2px; border-color: white}");
///Final Vertical Layout to put
final_layout = new QVBoxLayout;
final_layout->addLayout(welcome_layout);
final_layout->setAlignment(welcome_layout, Qt::AlignTop);
final_layout->addLayout(Easy_Hard_layout);
final_layout->addWidget(instruction_button);
central = new QWidget;
central->setLayout(final_layout);
this->setCentralWidget(central);
}
/**
Easy Game Begin Function - slot
@param
@return
@brief connects to easy_button. Initializes a 10x10 gameboard with 1:00 on the timer and set's the GameOver to the GameBoard
*/
void MainWindow::easy_game_begin() {
GameBoard = new gameboard(this,10, 1);
gameover* go = new gameover;
GameBoard->setGameOverWindow(go);
go->setGameboard(GameBoard);
go->setMainWindow(this);
this->setCentralWidget(GameBoard);
this->setStyleSheet("background-color: red;");
}
/**
Hard Game Begin Function - slot
@param
@return
@brief connects to hard_button. Initializes a 15x15 gameboard with 2:00 on the timer and set's the GameOver to the GameBoard
*/
void MainWindow::hard_game_begin() {
GameBoard = new gameboard(this,15, 2);
gameover* go = new gameover;
GameBoard->setGameOverWindow(go);
go->setGameboard(GameBoard);
go->setMainWindow(this);
this->setCentralWidget(GameBoard);
this->setStyleSheet("background-color: red;");
}
/**
Restart Game Function
@param
@brief set's the MainWindow to the gameboard object
* Color of the board is set to red here
*/
void MainWindow::restart(){
///Deletes the gameboard that was just played with
if(GameBoard->getBoard_Size()==15){
delete GameBoard;
///Allocate a new gameboard on mainwindow
GameBoard = new gameboard(this,15, 2);
gameover* go = new gameover;
GameBoard->setGameOverWindow(go);
go->setGameboard(GameBoard);
go->setMainWindow(this);
this->setCentralWidget(GameBoard);
this->setStyleSheet("background-color: red;");
}
if(GameBoard->getBoard_Size()==10){
delete GameBoard;
///Allocate a new gameboard on mainwindow
GameBoard = new gameboard(this,10, 1);
gameover* go = new gameover;
GameBoard->setGameOverWindow(go);
go->setGameboard(GameBoard);
go->setMainWindow(this);
this->setCentralWidget(GameBoard);
this->setStyleSheet("background-color: red;");
}
}
/**
Set Instructions Window - Slot
@param instructions* i
@brief When instruction_button is clicked, instruction window pops up.
*/
void MainWindow::setInstructionsWindow(instructions* i){
instruction_object = i;
QObject::connect(instruction_button, SIGNAL(clicked()), instruction_object, SLOT(show()));
return;
}
void MainWindow::setGameOver(gameover* go){
gameOver_object = go;
return;
}
/**
MainWindow Destructor
*/
MainWindow::~MainWindow()
{
}
| 2d510fd425cecc3c9cce1aaa667f927222dbf7a7 | [
"Markdown",
"C++"
] | 11 | C++ | kevkim11/Marshawns_Skittle_Crusher | 9cdd135a6ed2f25391f35261d7ac8da7bbb1f64a | 11eb06a4cd685f8e91de8781a5454f95c11d91dc |
refs/heads/master | <repo_name>headquarters/eslint-config-payscale<file_sep>/strict-addons/vanilla-js/index.js
/* Rules for vanilla javascript */
module.exports = {
rules: {
// enforces getter/setter pairs in objects
'accessor-pairs': 'off',
// enforces return statements in callbacks of array's methods
// http://eslint.org/docs/rules/array-callback-return
'array-callback-return': 'error',
// treat var statements as if they were block scoped
'block-scoped-var': 'error',
// specify the maximum cyclomatic complexity allowed in a program
complexity: ['off', 11],
// enforce that class methods use "this"
// http://eslint.org/docs/rules/class-methods-use-this
'class-methods-use-this': ['error', {
exceptMethods: []
}],
// require return statements to either always or never specify values
'consistent-return': 'error',
// must use curly braces (no if (foo) bar();)
curly: ['error', 'all'],
// require default case in switch statements
'default-case': ['error', { commentPattern: '^no default$' }],
// encourages use of dot notation whenever possible
'dot-notation': ['error', { allowKeywords: true }],
// enforces consistent newlines before or after dots
// http://eslint.org/docs/rules/dot-location
'dot-location': ['error', 'property'],
// make sure for-in loops have an if statement
// this prevents unexpected behavior resulting from javascript's for-in
// being different from, say, C#
'guard-for-in': 'error',
// disallow the use of alert, confirm, and prompt
'no-alert': 'warn',
// Disallow await inside of loops
// http://eslint.org/docs/rules/no-await-in-loop
'no-await-in-loop': 'error',
// disallow use of arguments.caller or arguments.callee
'no-caller': 'error',
// disallow lexical declarations in case/default clauses
// http://eslint.org/docs/rules/no-case-declarations.html
'no-case-declarations': 'error',
// Disallow comparisons to negative zero
// http://eslint.org/docs/rules/no-compare-neg-zero
'no-compare-neg-zero': 'off',
// disallow assignment in conditional expressions
// this prevents difficult to spot bugs when you think you're doing a comparison,
// e.g. if (x = 0) { ... }
'no-cond-assign': ['error', 'always'],
// disallow use of constant expressions in conditions
// use of these rarely used characters in a regex is typically a mistake
// http://eslint.org/docs/rules/no-control-regex
'no-constant-condition': 'warn',
// disallow control characters in regular expressions
'no-control-regex': 'error',
// disallow division operators explicitly at beginning of regular expression
// http://eslint.org/docs/rules/no-div-regex
'no-div-regex': 'off',
// disallow duplicate arguments in functions
// never a reason to have duplicate args, as only one will pass through
// probably a typo
'no-dupe-args': 'error',
// disallow duplicate keys when creating object literals
// like dupe args, always a mistake, as only one key is used
'no-dupe-keys': 'error',
// disallow a duplicate case in a switch statement
// another common mistake - only one can be used
'no-duplicate-case': 'error',
// disallow else after a return in an if
'no-else-return': 'error',
// disallow empty blocks
// e.g., if (foo) {}
// You can put a comment in your empty block to prevent the error
// http://eslint.org/docs/rules/no-empty
'no-empty': 'error',
// disallow the use of empty character classes in regular expressions
// [] in a regex doesn't match anything
// http://eslint.org/docs/rules/no-empty-character-class
'no-empty-character-class': 'error',
// disallow empty functions, except for standalone funcs/arrows
// http://eslint.org/docs/rules/no-empty-function
'no-empty-function': ['error', {
allow: [
'arrowFunctions',
'functions',
'methods'
]
}],
// disallow empty destructuring patterns
// http://eslint.org/docs/rules/no-empty-pattern
'no-empty-pattern': 'error',
// disallow comparisons to null without a type-checking operator
'no-eq-null': 'off',
// disallow use of eval()
'no-eval': 'error',
// disallow assigning to the exception in a catch block
// this loses the information about the exception
// http://eslint.org/docs/rules/no-ex-assign
'no-ex-assign': 'error',
// disallow adding to native types
'no-extend-native': 'error',
// disallow unnecessary function binding
'no-extra-bind': 'error',
// disallow double-negation boolean casts in a boolean context
// for example, unnecessary in an if statement's check
// http://eslint.org/docs/rules/no-extra-boolean-cast
'no-extra-boolean-cast': 'error',
// disallow Unnecessary Labels
// http://eslint.org/docs/rules/no-extra-label
'no-extra-label': 'error',
// disallow fallthrough of case statements
'no-fallthrough': 'error',
// disallow the use of leading or trailing decimal points in numeric literals
'no-floating-decimal': 'error',
// disallow overwriting functions written as function declarations
'no-func-assign': 'error',
// disallow reassignments of native objects or read-only globals
// http://eslint.org/docs/rules/no-global-assign
'no-global-assign': ['error', { exceptions: [] }],
// disallow invalid regular expression strings in the RegExp constructor
'no-invalid-regexp': ['error', { 'allowConstructorFlags': ['u', 'y'] }],
// deprecated in favor of no-global-assign
'no-native-reassign': 'off',
// disallow implicit type conversions
// http://eslint.org/docs/rules/no-implicit-coercion
'no-implicit-coercion': ['off', {
boolean: false,
number: true,
string: true,
allow: []
}],
// disallow var and named functions in global scope
// http://eslint.org/docs/rules/no-implicit-globals
'no-implicit-globals': 'off',
// disallow use of eval()-like methods
'no-implied-eval': 'error',
// disallow this keywords outside of classes or class-like objects
'no-invalid-this': 'off',
// disallow usage of __iterator__ property
'no-iterator': 'error',
// disallow use of labels for anything other then loops and switches
'no-labels': ['error', { allowLoop: false, allowSwitch: false }],
// disallow unnecessary nested blocks
'no-lone-blocks': 'error',
// disallow creation of functions within loops
'no-loop-func': 'error',
// disallow use of multiple spaces
'no-multi-spaces': 'error',
// disallow use of multiline strings
'no-multi-str': 'error',
// disallow use of new operator when not part of the assignment or comparison
'no-new': 'error',
// disallow use of new operator for Function object
'no-new-func': 'error',
// disallows creating new instances of String, Number, and Boolean
'no-new-wrappers': 'error',
// disallow the use of object properties of the global object (Math and JSON) as functions
'no-obj-calls': 'error',
// disallow use of (old style) octal literals
'no-octal': 'error',
// disallow use of octal escape sequences in string literals, such as
// var foo = 'Copyright \251';
'no-octal-escape': 'error',
// disallow reassignment of function parameters
// rule: http://eslint.org/docs/rules/no-param-reassign.html
'no-param-reassign': 'error',
// disallow usage of __proto__ property
'no-proto': 'error',
// disallow use of Object.prototypes builtins directly
// http://eslint.org/docs/rules/no-prototype-builtins
'no-prototype-builtins': 'error',
// disallow declaring the same variable more then once
'no-redeclare': 'error',
// disallow multiple spaces in a regular expression literal
'no-regex-spaces': 'error',
// disallow certain object properties
// http://eslint.org/docs/rules/no-restricted-properties
'no-restricted-properties': ['error', {
object: 'arguments',
property: 'callee',
message: 'arguments.callee is deprecated'
}, {
property: '__defineGetter__',
message: 'Please use Object.defineProperty instead.'
}, {
property: '__defineSetter__',
message: 'Please use Object.defineProperty instead.'
}, {
object: 'Math',
property: 'pow',
message: 'Use the exponentiation operator (**) instead.'
}],
// disallow use of assignment in return statement
'no-return-assign': 'error',
// disallow redundant `return await`
'no-return-await': 'error',
// disallow use of `javascript:` urls.
'no-script-url': 'error',
// disallow self assignment
// http://eslint.org/docs/rules/no-self-assign
'no-self-assign': 'error',
// disallow comparisons where both sides are exactly the same
'no-self-compare': 'error',
// disallow use of comma operator
'no-sequences': 'error',
// disallow sparse arrays
// e.g. [,,] - typically caused by accidentally typing extra commas
'no-sparse-arrays': 'error',
// Disallow template literal placeholder syntax in regular strings
// Probably happens when you switch from template to a regular string, but forget
// to remove the placeholders
// http://eslint.org/docs/rules/no-template-curly-in-string
'no-template-curly-in-string': 'error',
// restrict what can be thrown as an exception
'no-throw-literal': 'error',
// Avoid code that looks like two expressions but is actually one
// http://eslint.org/docs/rules/no-unexpected-multiline
'no-unexpected-multiline': 'error',
// disallow unmodified conditions of loops
// http://eslint.org/docs/rules/no-unmodified-loop-condition
'no-unmodified-loop-condition': 'off',
// disallow unreachable statements after a return, throw, continue, or break statement
// you may have intended for the code to be reachable, or may have forgotten
// to delete it
// http://eslint.org/docs/rules/no-unreachable
'no-unreachable': 'error',
// disallow return/throw/break/continue inside finally blocks
// http://eslint.org/docs/rules/no-unsafe-finally
'no-unsafe-finally': 'error',
// disallow negating the left operand of relational operators
// prevents mistakes like !a && b when you mean !(a && b)
// http://eslint.org/docs/rules/no-unsafe-negation
'no-unsafe-negation': 'error',
// disallow usage of expressions in statement position
'no-unused-expressions': ['error', {
allowShortCircuit: false,
allowTernary: false,
allowTaggedTemplates: false
}],
// disallow unused labels
// http://eslint.org/docs/rules/no-unused-labels
'no-unused-labels': 'error',
// disallow unnecessary .call() and .apply()
'no-useless-call': 'off',
// disallow useless string concatenation
// http://eslint.org/docs/rules/no-useless-concat
'no-useless-concat': 'error',
// disallow unnecessary string escaping
// http://eslint.org/docs/rules/no-useless-escape
'no-useless-escape': 'error',
// disallow redundant return; keywords
// http://eslint.org/docs/rules/no-useless-return
'no-useless-return': 'error',
// disallow use of void operator
// http://eslint.org/docs/rules/no-void
'no-void': 'error',
// disallow usage of configurable warning terms in comments: e.g. todo
'no-warning-comments': ['off', { terms: ['todo', 'fixme', 'xxx'], location: 'start' }],
// disallow use of the with statement
'no-with': 'error',
// require using Error objects as Promise rejection reasons
// http://eslint.org/docs/rules/prefer-promise-reject-errors
// TODO: enable, semver-major
'prefer-promise-reject-errors': ['off', { allowEmptyReject: true }],
// require use of the second argument for parseInt()
radix: 'error',
// require `await` in `async function` (note: this is a horrible rule that should never be used)
// http://eslint.org/docs/rules/require-await
'require-await': 'off',
// disallow comparisons with the value NaN
// NaN behaves unexpectedly, whereas isNaN(foo) does not
// http://eslint.org/docs/rules/use-isnan
'use-isnan': 'error',
// ensure that the results of typeof are compared against a valid string
// http://eslint.org/docs/rules/valid-typeof
'valid-typeof': ['error', { requireStringLiterals: true }],
// requires to declare all vars on top of their containing scope
'vars-on-top': 'error',
// require immediate function invocation to be wrapped in parentheses
// http://eslint.org/docs/rules/wrap-iife.html
'wrap-iife': ['error', 'outside', { functionPrototypeMethods: false }],
// require or disallow Yoda conditions
yoda: 'error'
}
};
<file_sep>/strict-addons/es6/imports.js
/* rules for es6 imports */
module.exports = {
env: {
es6: true
},
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
plugins: [
'import'
],
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.json']
}
},
'import/extensions': [
'.js',
'.jsx'
],
'import/core-modules': [
],
'import/ignore': [
'node_modules',
'\\.(scss|css|less|svg|json)$'
]
},
rules: {
// ensure imports point to files/modules that can be resolved
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
'import/no-unresolved': ['error', { commonjs: true, caseSensitive: true }],
// ensure named imports coupled with named exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md
'import/named': 'error',
// ensure default import coupled with default export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md
'import/default': 'error',
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md
'import/namespace': 'error',
// disallow invalid exports, e.g. multiple defaults
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md
'import/export': 'error',
// do not allow a default import name to match a named export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md
'import/no-named-as-default': 'error',
// warn on accessing default export property names that are also named exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md
'import/no-named-as-default-member': 'error',
// Forbid the use of extraneous packages
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md
'import/no-extraneous-dependencies': ['error', {
devDependencies: [
'**/*.test.js', // ignore for tests
'**/webpack.config.js', // webpack config
'**/webpack.config.*.js', // webpack config
'**/gulpfile.js', // gulp config
'**/gulpfile.*.js' // gulp config
]
}],
// Forbid mutable exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md
'import/no-mutable-exports': 'error',
// disallow require()
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md
'import/no-commonjs': 'off',
// disallow AMD require/define
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md
'import/no-amd': 'error',
// No Node.js builtin modules
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md
'import/no-nodejs-modules': 'off',
// disallow non-import statements appearing before import statements
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md
'import/first': ['error', 'absolute-first'],
// disallow duplicate imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
'import/no-duplicates': 'error',
// Ensure consistent use of file extension within the import path
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
'import/extensions': ['error', 'always', {
js: 'never',
jsx: 'never'
}],
// Require a newline after the last import/require in a group
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md
'import/newline-after-import': 'error',
// Require modules with a single export to use a default export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md
'import/prefer-default-export': 'error',
// Forbid import of modules using absolute paths
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-absolute-path.md
'import/no-absolute-path': 'error',
// Forbid require() calls with expressions
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-dynamic-require.md
'import/no-dynamic-require': 'error',
// Forbid Webpack loader syntax in imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md
'import/no-webpack-loader-syntax': 'error',
// Prevent importing the default as if it were named
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-default.md
'import/no-named-default': 'error'
}
};
<file_sep>/strict-addons/vanilla-js/README.md
# eslint-config-payscale-vanilla
Additional lint rules for vanilla javascript.
## Usage
`npm install --save-dev eslint-config-payscale-vanilla`
Then, in your .eslintrc, add it to your list of extends, e.g.:
`extends: ['payscale-vanilla']` | e71d2334ae5973fabe89825e8a49dd84e8e74d19 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | headquarters/eslint-config-payscale | d8c44485dafab712a915e2ddb10ecc3820f8c4f0 | 50f3cd120aae49ae2b6b5010ad798355b83d5781 |
refs/heads/master | <repo_name>ashley4140/ConnectFour<file_sep>/src/GameBoard.java
import java.awt.*;
import javax.swing.*;
public abstract class GameBoard extends JLabel{
public static void main(String args[]) {
JFrame frame = new JFrame("Connect Four");
JPanel panel = new JPanel();
panel.setBackground(Color.green);
panel.setLayout(new FlowLayout());
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
JButton button5 = new JButton();
JButton button6 = new JButton();
JButton button7 = new JButton();
button1.setBackground(Color.white);
button2.setBackground(Color.white);
button3.setBackground(Color.white);
button4.setBackground(Color.white);
button5.setBackground(Color.white);
button6.setBackground(Color.white);
button7.setBackground(Color.white);
button1.setText("Column 1");
button2.setText("Column 2");
button3.setText("Column 3");
button4.setText("Column 4");
button5.setText("Column 5");
button6.setText("Column 6");
button7.setText("Column 7");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
panel.add(button7);
JLabel label1 = new JLabel();
label1.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label1);
JLabel label2 = new JLabel();
label2.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label2);
JLabel label3 = new JLabel();
label3.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label3);
JLabel label4 = new JLabel();
label4.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label4);
JLabel label5 = new JLabel();
label5.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label5);
JLabel label6 = new JLabel();
label6.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label6);
JLabel label7 = new JLabel();
label7.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label7);
JLabel label8 = new JLabel();
label8.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label8);
JLabel label9 = new JLabel();
label9.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label9);
JLabel label10 = new JLabel();
label10.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label10);
JLabel label11 = new JLabel();
label11.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label11);
JLabel label12 = new JLabel();
label12.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label12);
JLabel label13 = new JLabel();
label13.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label13);
JLabel label14 = new JLabel();
label14.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label14);
JLabel label15 = new JLabel();
label15.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label15);
JLabel label16 = new JLabel();
label16.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label16);
JLabel label17 = new JLabel();
label17.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label17);
JLabel label18 = new JLabel();
label18.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label18);
JLabel label19 = new JLabel();
label19.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label19);
JLabel label20 = new JLabel();
label20.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label20);
JLabel label21 = new JLabel();
label21.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label21);
JLabel label22 = new JLabel();
label22.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label22);
JLabel label23 = new JLabel();
label23.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label23);
JLabel label24 = new JLabel();
label24.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label24);
JLabel label25 = new JLabel();
label25.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label25);
JLabel label26 = new JLabel();
label26.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label26);
JLabel label27 = new JLabel();
label27.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label27);
JLabel label28 = new JLabel();
label28.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label28);
JLabel label29 = new JLabel();
label29.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label29);
JLabel label30 = new JLabel();
label30.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label30);
JLabel label31 = new JLabel();
label31.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label31);
JLabel label32 = new JLabel();
label32.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label32);
JLabel label33 = new JLabel();
label33.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label33);
JLabel label34 = new JLabel();
label34.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label34);
JLabel label35 = new JLabel();
label35.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label35);
JLabel label36 = new JLabel();
label36.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label36);
JLabel label37 = new JLabel();
label37.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label37);
JLabel label38 = new JLabel();
label38.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label38);
JLabel label39 = new JLabel();
label39.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label39);
JLabel label40 = new JLabel();
label40.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label40);
JLabel label41 = new JLabel();
label41.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label41);
JLabel label42 = new JLabel();
label42.setIcon(new ImageIcon("boardpiece1.jpg"));
panel.add(label42);
frame.add(panel);
frame.setSize(760, 700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
| c571cc3b52f7c892a27cc597651aed99ae15c2de | [
"Java"
] | 1 | Java | ashley4140/ConnectFour | 6da81f3123d3e1e29ea1464c508934a9d2a5f265 | ca81043724ba4c42dafe12a45652f0296444946a |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Employee;
use App\Models\Specialist;
use App\Models\Hardware;
use App\Models\Software;
use App\Models\OS;
use App\Models\Location;
use App\Models\Solution;
use App\Models\FAQ;
class MainController extends Controller
{
public function index() {
$users = User::all()->toJson();
return view('login', ['users' => $users]);
}
public function login(Request $request) {
$user = User::where('email', $request->email)
->where('password', $request->password)
->get();
if(isset($user[0])) {
$userID = $user[0]->userID;
$request->session()->put('userID', $userID);
switch($user[0]->userType){
case 'Specialist':
$specialist = Specialist::where('userID', $userID)
->get();
$request->session()->put('specID', $specialist[0]->specID);
return redirect('/specialist/dashboard');
break;
case 'Employee':
$employee = Employee::where('userID', $userID)
->get();
$request->session()->put('empID', $employee[0]->empID);
return redirect('/employee/dashboard');
break;
case 'Analyst':
$employee = Employee::where('userID', $userID)
->get();
$request->session()->put('empID', $employee[0]->empID);
return redirect('/analyst');
break;
}
} else {
return redirect('/login');
}
}
public function logout(Request $request) {
$request->session()->forget('empID');
$request->session()->forget('userID');
$request->session()->forget('specIDp');
return view('login', [ 'users' => [] ]);
}
public static function getLocations() {
return Location::all();
}
public static function getHardware() {
return Hardware::all();
}
public static function getOS() {
return OS::all();
}
public static function getSoftware() {
return Software::all();
}
public static function getSolutions() {
return Solution::all();
}
public static function getFAQ() {
return FAQ::all();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Hardware;
use App\Models\Software;
use App\Models\OS;
use App\Models\Location;
use App\Models\Solution;
use App\Models\User;
use App\Models\FAQ;
use App\Models\Specialist;
use App\Models\SoftwareSpecialist;
use App\Models\HardwareSpecialist;
use App\Models\Ticket;
use App\Http\Controllers\MainController;
class EmployeeController extends Controller
{
public function index() {
$locations = MainController::getLocations();
$os = MainController::getOS();
$hardware = MainController::getHardware();
$software = MainController::getSoftware();
$faq = MainController::getFAQ();
// obj needs name, id, hardware spec, software spec
$array = [];
$specialistsUsers = User::where('userType', 'Specialist')->get();
foreach($specialistsUsers as $specialistsUser) {
$specialist = Specialist::where('userID', $specialistsUser['userID'])->get()[0];
$softwareSpecialties = " ";
$specialistSoftware = SoftwareSpecialist::where('specID', $specialist->specID)->get();
foreach($specialistSoftware as $softwareSpecialty) {
$temp = Software::where('softID', $softwareSpecialty->softID)->get()[0]->softName;
$softwareSpecialties .= ($temp . " | ");
}
$hardwareSpecialties = " ";
$specialistHardware = HardwareSpecialist::where('specID', $specialist->specID)->get();
foreach($specialistHardware as $hardwareSpecialty) {
$temp = Hardware::where('serial_no', $hardwareSpecialty['serial_no'])->get()[0]->hardType;
$hardwareSpecialties .= ($temp . " | ");
}
$obj = [
'firstName' => $specialistsUser->firstName,
'userID' => $specialistsUser->userID,
'specID' => $specialist->specID,
'softwareSpecialties' => $softwareSpecialties,
'hardwareSpecialties' => $hardwareSpecialties
];
array_push($array, $obj);
}
return view('employee_dashboard', [
'software' => $software,
'os' => $os,
'hardware' => $hardware,
'locations' => $locations,
'faq' => $faq,
'specialists' => $array
]);
}
public function loadFAQPage() {
$faq = MainController::getFAQ();
return view('employee_FAQ', [
'faq' => $faq,
]);
}
public function loadTicketsPage(Request $request) {
$empID = $request->session()->get('empID');
$tickets = Ticket::where('empID', $empID)->get();
$unsolved = Ticket::where('empID', $empID)->where('status', 'Unsolved')->get();
$output = array();
foreach($tickets as $ticket ) {
$solutions = Solution::where('solutionID', $ticket->solutionID)->get();
if(count($solutions) > 0) {
$solution = $solutions[0];
$obj = [ $ticket->ticketID, $ticket->dateCreated, $ticket->description, $solution->solutionDescription, $ticket->status ];
array_push($output, $obj);
} else {
$obj = [ $ticket->ticketID, $ticket->dateCreated, $ticket->description, 'Not solved yet', $ticket->status ];
array_push($output, $obj);
}
}
return view('employee_my_tickets', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Date Created', 'Description', 'Solution', 'Status', 'Interactions'],
'title' => 'All Tickets',
'type' => 'all',
'unsolved' => $unsolved
]);
}
public function loadUnsolvedTickets(Request $request) {
$empID = $request->session()->get('empID');
$tickets = Ticket::where('empID', $empID)
->where('status', 'Unsolved')
->get();
$output = array();
foreach($tickets as $ticket ) {
$obj = [ $ticket->ticketID, $ticket->dateCreated, $ticket->description, $ticket->reason, $ticket->priority ];
array_push($output, $obj);
}
return view('employee_my_tickets', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Date Created', 'Description', 'Reason', 'Priority'],
'title' => 'Unsolved Tickets',
'type' => 'unsolved'
]);
}
public function loadSolvedTickets(Request $request) {
$empID = $request->session()->get('empID');
$tickets = Ticket::where('empID', $empID)
->where('status', 'Solved')
->get();
$output = array();
foreach($tickets as $ticket ) {
$solutions = Solution::where('solutionID', $ticket->solutionID)->get();
if(count($solutions) > 0) {
$solution = $solutions[0];
$obj = [ $ticket->ticketID, $solution->dateSolved, $ticket->description, $solution->solutionDescription ];
array_push($output, $obj);
}
}
// return var_dump($output[0]);
return view('employee_my_tickets', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Date Created', 'Description', 'Solution'],
'title' => 'Solved Tickets',
'type' => 'solved'
]);
}
public function loadPendingTickets(Request $request) {
// WAITING ON PENDING FIELD - Doesn't work fully yet
$empID = $request->session()->get('empID');
$tickets = Ticket::where('empID', $empID)
->where('status', 'Pending')
->get();
$output = array();
foreach($tickets as $ticket ) {
$solutions = Solution::where('solutionID', $ticket->solutionID)->get();
if(count($solutions) > 0) {
$solution = $solutions[0];
$obj = [ $ticket->ticketID, $solution->dateSolved, $ticket->description, $solution->solutionDescription ];
array_push($output, $obj);
}
}
return view('employee_my_tickets', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Date Created', 'Description', 'Solution', 'Interaction'],
'title' => 'Pending Tickets',
'type' => 'pending'
]);
}
public function addTicket(Request $request) {
$ticket = new Ticket();
$ticket['empID'] = session()->get('empID');
$ticket['dateCreated'] = date('Y-m-d');
$ticket['timeCreated'] = date('H:i:s');
$ticket['serial_no'] = $request->serial_no;
$ticket['softID'] = $request->softID;
$ticket['OSID'] = $request->OSID;
$ticket['description'] = $request->description;
$ticket['reason'] = $request->reason;
$ticket['priority'] = $request->priority;
$ticket['locationID'] = $request->locationID;
$ticket['solutionID'] = null;
$ticket['sepcID'] = $request->specID;
$ticket['status'] = 'Unsolved';
$ticket->save();
return redirect('/employee/tickets/unsolved');
}
public function denyTicket(Request $request) {
$ticket = Ticket::find($request->ticketID);
$ticket['status'] = 'Unsolved';
$ticket->save();
return redirect('/employee/tickets/pending');
}
public function acceptTicket(Request $request) {
$ticket = Ticket::find($request->ticketID);
$ticket['status'] = 'Solved';
$ticket->save();
return redirect('/employee/tickets/pending');
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
use App\Http\Controllers\MainController;
use App\Http\Controllers\AnalystController;
use App\Http\Controllers\SpecialistController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [MainController::class, 'index']);
Route::get('/login', [MainController::class, 'index']);
Route::post('/login/user', [MainController::class, 'login']);
Route::get('/logout', [MainController::class, 'logout']);
Route::get('/employee/dashboard', [EmployeeController::class, 'index']);
Route::post('/employee/dashboard/add-ticket', [EmployeeController::class, 'addTicket']);
Route::get('/employee/FAQ', [EmployeeController::class, 'loadFAQPage']);
Route::get('/employee/tickets', [EmployeeController::class, 'loadTicketsPage']);
Route::get('/employee/tickets/unsolved', [EmployeeController::class, 'loadUnsolvedTickets']);
Route::get('/employee/tickets/solved', [EmployeeController::class, 'loadSolvedTickets']);
Route::get('/employee/tickets/pending', [EmployeeController::class, 'loadPendingTickets']);
Route::post('/employee/tickets/pending/deny', [EmployeeController::class, 'denyTicket']);
Route::post('/employee/tickets/pending/accept', [EmployeeController::class, 'acceptTicket']);
Route::get('/analyst', [AnalystController::class, 'index']);
Route::get('/analyst/dashboard', [AnalystController::class, 'index']);
Route::get('/specialist/dashboard', [SpecialistController::class, 'index']);
Route::get('/specialist/dashboard/unsolved', [SpecialistController::class, 'loadUnsolvedTickets']);
Route::get('/specialist/dashboard/solved', [SpecialistController::class, 'loadSolvedTickets']);
Route::get('/specialist/dashboard/pending', [SpecialistController::class, 'loadPendingTickets']);
Route::get('/specialist/FAQ', [SpecialistController::class, 'loadFAQPage']);
Route::get('/specialist/edit', [SpecialistController::class, 'loadEditPage']);
Route::post('/specialist/solve', [SpecialistController::class, 'loadSolvePage']);
Route::post('/specialist/solve/submit', [SpecialistController::class, 'submitSolution']);
Route::post('/specialist/reassign', [SpecialistController::class, 'loadReassignPage']);
Route::post('/specialist/reassign/submit', [SpecialistController::class, 'submitReassignment']);
Route::post('/specialist/edit/add-hardware', [SpecialistController::class, 'addHardware']);
Route::post('/specialist/edit/remove-hardware', [SpecialistController::class, 'removeHardware']);
Route::post('/specialist/edit/add-faq', [SpecialistController::class, 'addFAQ']);
Route::post('/specialist/edit/remove-faq', [SpecialistController::class, 'removeFAQ']);
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class OS extends Model
{
use HasFactory;
public $timestamps = false;
protected $table = 'OperatingSystems';
protected $primaryKey = 'OSID';
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Ticket;
use App\Http\Controllers\MainController;
use DB;
// Remove later
use App\Models\Hardware;
use App\Models\Software;
use App\Models\OS;
use App\Models\Location;
use App\Models\Solution;
use App\Models\User;
use App\Models\FAQ;
use App\Models\Specialist;
use App\Models\SoftwareSpecialist;
use App\Models\HardwareSpecialist;
class SpecialistController extends Controller
{
public function index(Request $request) {
$specID = $request->session()->get('specID');
$tickets = Ticket::where('sepcID', $specID)->get();
$unsolved = Ticket::where('sepcID', $specID)->where('status', "!=", "solved")->get();
$output = array();
foreach($tickets as $ticket ) {
$solutions = Solution::where('solutionID', $ticket->solutionID)->get();
if(count($solutions) > 0) {
$solution = $solutions[0];
$obj = [ $ticket->ticketID, $ticket->description, $solution->solutionDescription, $solution->dateSolved,$ticket->status ];
array_push($output, $obj);
} else {
$obj = [ $ticket->ticketID, $ticket->description, 'Not solved yet', 'N/A', $ticket->status ];
array_push($output, $obj);
}
}
return view('specialist_dashboard', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Description', 'Solution','Date Solved', 'Status'],
'title' => 'All tickets',
'unsolved' => $unsolved,
'type' => 'all'
]);
}
public function loadUnsolvedTickets(Request $request) {
$specID = $request->session()->get('specID');
$tickets = Ticket::where('sepcID', $specID)->where('status', "unsolved")->get();
$output = array();
foreach($tickets as $ticket ) {
$solutions = Solution::where('solutionID', $ticket->solutionID)->get();
if(count($solutions) > 0) {
$solution = $solutions[0];
$obj = [ $ticket->ticketID, $ticket->description, $solution->solutionDescription, $solution->dateSolved, $ticket->priority, $ticket->status ];
array_push($output, $obj);
} else {
$obj = [ $ticket->ticketID, $ticket->description, 'Not solved yet', 'N/A', $ticket->priority, $ticket->status];
array_push($output, $obj);
}
}
return view('specialist_dashboard', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Description', 'Solution','Date Solved', 'Priority', 'Status'],
'title' => 'Unsolved Tickets',
'type' => 'unsolved'
]);
}
public function loadPendingTickets(Request $request) {
$specID = $request->session()->get('specID');
$tickets = Ticket::where('sepcID', $specID)->where('status', "Pending")->get();
$output = array();
foreach($tickets as $ticket ) {
$solutions = Solution::where('solutionID', $ticket->solutionID)->get();
if(count($solutions) > 0) {
$solution = $solutions[0];
$obj = [ $ticket->ticketID, $ticket->description, $solution->solutionDescription, $solution->dateSolved];
array_push($output, $obj);
} else {
$obj = [ $ticket->ticketID, $ticket->description, 'Not solved yet', 'N/A'];
array_push($output, $obj);
}
}
return view('specialist_dashboard', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Description', 'Solution','Date Solved'],
'title' => 'Pending Tickets',
'type' => 'pending'
]);
}
public function loadSolvedTickets(Request $request) {
$specID = $request->session()->get('specID');
$tickets = Ticket::where('sepcID', $specID)->where('status', "solved")->get();
$output = array();
foreach($tickets as $ticket ) {
$solutions = Solution::where('solutionID', $ticket->solutionID)->get();
if(count($solutions) > 0) {
$solution = $solutions[0];
$obj = [ $ticket->ticketID, $ticket->description, $solution->solutionDescription, $solution->dateSolved];
array_push($output, $obj);
} else {
$obj = [ $ticket->ticketID, $ticket->description, 'Not solved yet', 'N/A'];
array_push($output, $obj);
}
}
return view('specialist_dashboard', [
'tickets' => $output,
'fields' => ['Ticket ID', 'Description', 'Solution','Date Solved'],
'title' => 'Solved Tickets',
'type' => 'solved'
]);
}
public function loadFAQPage() {
$faq = MainController::getFAQ();
return view('specialist_FAQ', [
'faq' => $faq,
]);
}
public function loadSolvePage(Request $request) {
$chosenticket = new Ticket();
$chosenticket->ticketID = $request->ticketID;
$ticket = Ticket::where('ticketID', $chosenticket->ticketID)->get()[0];
//os, hard, software
$osVersion = '';
if(isset($ticket->OSID)) {
$osVersion = OS::where('OSID', $ticket->OSID)->get()[0]->version;
}
$hardType = '';
if(isset($ticket->serial_no)) {
$hardType = Hardware::where('serial_no', $ticket->serial_no)->get()[0]->hardType;
}
$softName = '';
if(isset($ticket->softID)) {
$softName = Software::where('softID', $ticket->softID)->get()[0]->softName;
}
$solution = "";
if(isset($ticket->solutionID)) {
$solution = Solution::where('solutionID', $ticket->solutionID)->get()[0]->solutionDescription;
}
return view('specialist_solve', [
'ticketID' => $chosenticket->ticketID,
'desc' => $ticket->description,
'ticket' => $ticket,
'osVersion' => $osVersion,
'hardType' => $hardType,
'softName' => $softName,
'priority' => $ticket->priority,
'solution' => $solution
]);
}
public function submitSolution(Request $request) {
// Add solutions to table
$solution = new Solution();
$solution['dateSolved'] = date('Y-m-d');
$solution['timeSolved'] = date('H:i:s');
$solution['solutionDescription'] = $request->solution;
$user = User::where('userID', session()->get('userID'))->get()[0];
$solution['solutionSolver'] = $user->firstName;
$solutionID = rand(0, 100000000);
$solution['solutionID'] = $solutionID;
$solution->save();
// $solution->id;
// Add ticket sepcID
$ticket = Ticket::where('ticketID', $request->ticketID)->get()[0];
$ticket['solutionID'] = $solutionID;
$ticket['status'] = 'Pending';
$ticket->save();
if($request['add-to-faq'] == 'on') {
$faq = new FAQ();
$faq['problem'] = $request->description;
$faq['solution'] = $request->solution;
$faq['SolutionID'] = $solutionID;
$faq->save();
}
return redirect('/specialist/dashboard/pending');
// Add to FAQ
}
public function loadReassignPage(Request $request) {
$chosenticket = new Ticket();
$chosenticket->ticketID = $request->ticketID;
$ticket = Ticket::where('ticketID', $chosenticket->ticketID)->get()[0];
// obj needs name, id, hardware spec, software spec
$array = [];
$specialistsUsers = User::where('userType', 'Specialist')->get();
foreach($specialistsUsers as $specialistsUser) {
$specialist = Specialist::where('userID', $specialistsUser['userID'])->get()[0];
$softwareSpecialties = " ";
$specialistSoftware = SoftwareSpecialist::where('specID', $specialist->specID)->get();
foreach($specialistSoftware as $softwareSpecialty) {
$temp = Software::where('softID', $softwareSpecialty->softID)->get()[0]->softName;
$softwareSpecialties .= ($temp . " | ");
}
$hardwareSpecialties = " ";
$specialistHardware = HardwareSpecialist::where('specID', $specialist->specID)->get();
foreach($specialistHardware as $hardwareSpecialty) {
$temp = Hardware::where('serial_no', $hardwareSpecialty['serial_no'])->get()[0]->hardType;
$hardwareSpecialties .= ($temp . " | ");
}
$obj = [
'firstName' => $specialistsUser->firstName,
'userID' => $specialistsUser->userID,
'specID' => $specialist->specID,
'softwareSpecialties' => $softwareSpecialties,
'hardwareSpecialties' => $hardwareSpecialties
];
array_push($array, $obj);
}
// return response()->json(array('success' => true, 'last_insert_id' => $array), 200);
return view('specialist_reassign', [
'ticketID' => $chosenticket->ticketID,
'desc' => $ticket->description,
'specialists' => $array
]);
}
public function submitReassignment(Request $request) {
$ticket = Ticket::find($request->ticketID);
$ticket['sepcID'] = $request->specID;
$ticket->save();
return redirect('/specialist/dashboard');
}
public function loadEditPage() {
$hardware = MainController::getHardware();
$software = MainController::getSoftware();
$os = MainController::getOS();
$solutions = MainController::getSolutions();
$faqs = MainController::getFAQ();
return view('specialist_edit', [
'hardware' => $hardware,
'software' => $software,
'os' => $os,
'faqs' => $faqs
] );
}
public function addHardware(Request $request) {
$hardware = new Hardware();
$hardware->serial_no = $request->serial_no;
$hardware->hardType = $request->hardType;
$hardware->make = $request->make;
$hardware->save();
return redirect('/specialist/edit');
}
public function removeHardware(Request $request) {
Hardware::destroy($request->serial_no);
return redirect('/specialist/edit');
}
public function addFAQ(Request $request) {
// ADd solution, add FAQ
$solution = new Solution();
$solution['dateSolved'] = $request['dateSolved'];
$solution['timeSolved'] = $request['timeSolved'];
$solution['solutionDescription'] = $request['solution'];
$user = User::where('userID', session()->get('userID'))->get()[0];
$solution['solutionSolver'] = $user->firstName;
$solutionID = rand(0, 100000000);
$solution['solutionID'] = $solutionID;
$solution->save();
$faq = new FAQ();
$faq['problem'] = $request['problem'];
$faq['solution'] = $request['solution'];
$faq['SolutionID'] = $solutionID;
$faq->save();
return redirect('/specialist/edit');
}
public function removeFAQ(Request $request) {
FAQ::destroy($request['faqID']);
return redirect('/specialist/edit');
}
}
| 71d0381ad2356d54a76edecf75cfc7159cf0447f | [
"PHP"
] | 5 | PHP | JamesThanni/Laravel-Helpdesk-System | 909816c8325b29ed4de8422d3da7d59c70f1b92b | e66e960e83009fab158933102abde72bf22a35ee |
refs/heads/main | <file_sep>INSERT INTO Categories (CategoryName, CategoryClass)
VALUES ('Snowboard&Ski', 'boards'),
('Bindings', 'bindings'),
('Boots', 'boots'),
('Snowwear', 'clothing'),
('Accessories', 'tools'),
('Other', 'other');
INSERT INTO Users (UserID, UserEmail, UserPassword, UserName, UserComments, UserImgPath )
VALUES ('1', '<EMAIL>', <PASSWORD>', 'Dylan', '','img/avatar.jpg'),
('2', '<EMAIL>', '$2y$10$bWtSjUhwgggtxrnJ7rxmIe63ABubHQs0AS0hgnOo41IEdMHkYoSVa', 'Catherine', '','img/avatar.jpg'),
('3', '<EMAIL>', '$2y$10$2OxpEH7narYpkOT1H5cApezuzh10tZEEQ2axgFOaKW.55LxIJBgWW', 'Warrior', '','img/avatar.jpg'),
('4', '<EMAIL>', '$2y$10$bWtSjUhwgggtxrnJ7rxmIe63ABubHQs0AS0hgnOo41IEdMHkYoSVa', 'Skye', '','img/avatar.jpg');
INSERT INTO Lots (LotName, LotPrice, LotStepBid, LotImgUrl, LotDescription, CategoryID, LotDateTime)
VALUES ('2014 Rossignol District Snowboard','350','5','img/lot-1.jpg','something about Snowboard','1', '2021-08-22 00:00:00'),
('DC Ply Mens 2016/2017 Snowboard','299','5','img/lot-2.jpg','something about Snowboard','1', '2021-08-20 00:00:00'),
('Bindings Union Contact Pro 2015 size L/XL','109','5','img/lot-3.jpg','something about Bindings','2', '2021-08-10 05:00:00'),
('Boots for Snowboard DC Mutiny Charocal','340','5','img/lot-4.jpg','something about boots','3', '2021-08-02 07:07:11'),
('Jacket for Snowboard DC Mutiny Charocal','169','5','img/lot-5.jpg','something about jacket','4', '2021-08-01 14:17:00'),
('Face Mask DRAGON DX Goggle 2021','270','5','img/lot-6.jpg',"The DX Goggle is a timeless Dragon shape that's been upgraded to meet the demands of today's consumers. The DX checks all the boxes: 100-percent UV protection, Super Anti Fog lens treatment, and a design that guarantees seamless goggle-to-helmet fit. Those looking for a no-fuss goggle should look no further than the DX.",'6', '2021-08-01 04:19:00');
INSERT INTO Bids (BidID, BidPrice, BidDateTime, LotID, UserID)
VALUES ('1','250', '2021-08-13 00:15:00', '1', '2'),
('2','280', '2021-08-12 08:09:08', '1', '1'),
('3','300', '2021-08-11 12:17:40', '1', '3'),
('4','280', '2021-08-11 06:30:10', '1', '4');
<file_sep><?php
require 'functions.php';
require 'config.php';
require 'init.php';
require 'nav.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$form = $_POST;
$user_photo = $_FILES['user-photo'];
$errors=validate_form_sign_up($form);
if ($_FILES['user-photo']['name']) {
if (isset($_FILES['user-photo']['name'])) {
$tmp_name = $user_photo['tmp_name'];
$path = $user_photo['name'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file_type = finfo_file($finfo, $tmp_name);
if ($file_type !== "image/jpeg") {
$errors['file'] = 'Upload photo in jpeg format';
}
else {
move_uploaded_file($tmp_name, 'img/' . $path);
$form['path'] = $path;
}
}
}
else {
$errors['file'] = 'You have not uploaded photo';
}
if (empty($errors)) {
$password_hash = password_hash($form['password'], PASSWORD_DEFAULT);
$email = mysqli_real_escape_string($link, $form['email']);
$name = mysqli_real_escape_string($link, $form['name']);
$password = mysqli_real_escape_string($link, $password_hash);
$path = mysqli_real_escape_string($link, 'img/'.$form['path']);
$message = mysqli_real_escape_string($link, $form['message']);
$sql = "INSERT INTO Users (`UserEmail`, `UserName`, `UserPassword`,`UserImgPath`,`UserComments`) VALUES ('$email', '$name', '$password','$path','$message')";
$result = mysqli_query($link, $sql);
if ($result) {
header('Location: ./index.php');
exit();
}
}
else {
$page_content = include_template('sign-up.php', [
'categories' => $categories,
'form' => $form,
'errors' => $errors,
]);
}
} else {
$page_content = include_template('sign-up.php', [
'categories' => $categories,
]);
}
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'categories' => $categories,
'user_name' => $user_name,
'user_avatar'=>$user_avatar,
'title' => "Sign up"
]);
print($layout_content);
?>
<file_sep><?php
$categories = [
['category' =>'Snowboard&Ski','class'=>'boards'],
['category' =>'Bindings','class'=>'bindings'],
['category' =>'Boots','class'=>'boots'],
['category' =>'Snowwear','class'=>'clothing'],
['category' =>'Accessories','class'=>'tools'],
['category' =>'Other','class'=>'other']
];
$lots = [
[
'id' => 1,
'name' => '2014 Rossignol District Snowboard',
'category' => 'Snowboard&Ski',
'price' => '350',
'url' => 'img/lot-1.jpg',
'about' => ''
],
[
'id' => 2,
'name' => 'DC Ply Mens 2016/2017 Snowboard',
'category' => 'Snowboard&Ski',
'price' => '299',
'url' => 'img/lot-2.jpg',
],
[
'id' => 3,
'name' => 'Bindings Union Contact Pro 2015 size L/XL',
'category' => 'Bindings',
'price' => '109',
'url' => 'img/lot-3.jpg',
],
[
'id' => 4,
'name' => 'Boots for Snowboard DC Mutiny Charocal',
'category' => 'Boots',
'price' => '340',
'url' => 'img/lot-4.jpg',
],
[
'id' => 5,
'name' => 'Jacket for Snowboard DC Mutiny Charocal',
'category' => 'Clothes',
'price' => '169',
'url' => 'img/lot-5.jpg',
],
[
'id' => 6,
'name' => 'Face Mask DRAGON DX Goggle 2021',
'category' => 'Other',
'price' => '270',
'url' => 'img/lot-6.jpg',
'about' => "The DX goggle is a timeless Dragon shape that's been upgraded to meet the demands of today's consumers. The DX checks all the boxes: 100-percent UV protection, Super Anti Fog lens treatment, and a design that guarantees seamless goggle-to-helmet fit. Those looking for a no-fuss goggle should look no further than the DX."
]
];
$Bids = [
['name' => 'Alex', 'price' => 250, 'ts' => strtotime('-' . rand(1, 50) .' minute')],
['name' => 'Paul', 'price' => 280, 'ts' => strtotime('-' . rand(1, 18) .' hour')],
['name' => 'Catherine', 'price' => 300, 'ts' => strtotime('-' . rand(25, 50) .' hour')],
['name' => 'Skye', 'price' => 250, 'ts' => strtotime('last week')]
];
$users = [
[
'email'=>'<EMAIL>',
'name' => 'John',
'password' => <PASSWORD>' // <PASSWORD>
],
[
'email'=>'<EMAIL>',
'name' => 'Helen',
'password' => <PASSWORD>' // <PASSWORD>
],
[
'email'=>'<EMAIL>',
'name' => 'Warrior',
'password' => <PASSWORD>' // <PASSWORD>
],
];
<file_sep><?php
require 'config.php';
require 'data.php';
require 'functions.php';
unset($_SESSION['user']);
header("Location: index.php")
?>
<file_sep>Репозиторий создан для обучения на интенсивном онлайн‑курсе «[Профессиональный PHP, уровень 1](https://htmlacademy.ru/intensive/php)» от [HTML Academy](https://htmlacademy.ru).
<file_sep><?php
$email = $form['email'] ?? '';
$password = $form['password'] ?? '';
$name = $form['name'] ?? '';
$message = $form['message'] ?? '';
?>
<main>
<nav class="nav">
<ul class="nav__list container">
<?php foreach($categories as $key => $value): ?>
<li class="nav__item">
<a href="all-lots.html"><?=$value['CategoryName']?></a>
</li>
<?php endforeach?>
</ul>
</nav>
<form class="form container <?= isset($errors) ? 'form--invalid' : '' ?>" enctype="multipart/form-data"
action="sign-up.php" method="post">
<!-- form--invalid -->
<h2>Register new accaunt</h2>
<div class="form__item <?= isset($errors['email']) ? 'form__item--invalid' : '' ?>">
<!-- form__item--invalid -->
<label for="email">E-mail*</label>
<input id="email" type="text" name="email" value="<?= $email;?>" placeholder="Insert e-mail">
<span class="form__error"><?= $errors['email'] ?? '' ?></span>
</div>
<div class="form__item <?= isset($errors['password']) ? 'form__item--invalid' : '' ?> ">
<label for="password">Password*</label>
<input id="password" type="text" name="password" value="<?= $password;?>" placeholder="Insert password">
<span class="form__error"><?= $errors['password'] ?? '' ?></span>
</div>
<div class="form__item <?= isset($errors['name']) ? 'form__item--invalid' : '' ?>">
<label for="name">Name*</label>
<input id="name" type="text" name="name" value="<?= $name;?>" placeholder="Insert your name">
<span class="form__error"><?= $errors['name'] ?? '' ?></span>
</div>
<div class="form__item <?= isset($errors['message']) ? 'form__item--invalid' : '' ?>">
<label for="message">Contact details*</label>
<textarea id="message" name="message" placeholder="Your contact details"><?= $message;?></textarea>
<span class="form__error"><?= $errors['message'] ?? '' ?></span>
</div>
<div
class="form__item form__item--file form__item--last <?= isset($errors['file']) ? 'form__item--invalid' : '' ?>">
<label>Your photo</label>
<div class="preview">
<button class="preview__remove" type="button">x</button>
<div class="preview__img">
<img src="img/avatar.jpg" width="113" height="113" alt="Your photo">
</div>
</div>
<div class="form__input-file">
<input class="visually-hidden" type="file" id="photo" name="user-photo">
<label for="photo">
<span>+ Add</span>
</label>
<span class="form__error"><?= $errors['file'] ?? '' ?></span>
</div>
</div>
<span class="form__error form__error--bottom">Please, correct mistakes in your form</span>
<button type="submit" class="button">Register</button>
<a class="text-link" href="#">Already have this accaunt</a>
</form>
</main><file_sep><main>
<section class="lot-item container">
<h2>Error</h2>
<p><?= $error ?></p>
</section>
</main><file_sep><?php
require 'config.php';
require 'functions.php';
require 'init.php';
require 'nav.php';
$lot = null;
if (!$link) {
$error = mysqli_connect_error();
$page_content = include_template('error.php', ['error' => $error]);
}
else {
// request on showing 9 recent lots
$sql = 'SELECT * FROM Lots as l
JOIN Categories AS c ON l.CategoryID=c.CategoryID
ORDER BY `LotDateTime` DESC LIMIT 9';
if ($res = mysqli_query($link, $sql)) {
$lots = mysqli_fetch_all($res, MYSQLI_ASSOC);
}
else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
$page_content = include_template('index.php', [
'categories' => $categories,
'lots' => $lots,
]);
}
if (isset($_SESSION['user'])) {
$user_name = $_SESSION['user']['UserName'];
}
if (isset($_GET['lot_id'])) {
$lot_id = $_GET['lot_id'];
foreach ($lot_list as $item) {
if ($item['id'] == $lot_id) {
$lot = $item;
break;
}
}
}
if (!$lot) {
http_response_code(404);
}
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'categories' => $categories,
'user_name' => $user_name,
'user_avatar'=>$user_avatar,
'title' => "Home page"
]);
print($layout_content);
?>
<file_sep>CREATE DATABASE yeticave;
USE yeticave;
CREATE TABLE Categories (
CategoryID INT AUTO_INCREMENT PRIMARY KEY,
CategoryName VARCHAR(255),
CategoryClass VARCHAR(255)
);
CREATE TABLE Users (
UserID INT AUTO_INCREMENT PRIMARY KEY,
UserEmail VARCHAR(128),
UserPassword VARCHAR(64),
UserName VARCHAR(128),
UserImgPath VARCHAR(128),
UserComments VARCHAR(255)
);
CREATE TABLE Lots (
LotID INT AUTO_INCREMENT,
LotName VARCHAR(255),
LotStepBid INT,
LotPrice INT,
LotImgUrl VARCHAR(128),
LotDescription VARCHAR(255),
LotDateTime DATETIME,
CategoryID INT,
PRIMARY KEY (LotID),
FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID)
);
CREATE TABLE Bids (
BidID INT AUTO_INCREMENT,
BidPrice INT,
BidDateTime DATETIME,
UserID INT,
LotID INT,
PRIMARY KEY (BidID),
FOREIGN KEY (UserID) REFERENCES Users(UserID),
FOREIGN KEY (LotID) REFERENCES Lots(LotID)
);
<file_sep><?php
/**
* Преобразует специмволы в HTML-сущности.
*
* @param array $post Данный из формы.
*
* @return array Ассоциативный массив с преобразуемыми спецсимволами.
*/
function esc_array($post) {
$array = [];
foreach ($post as $field => $value) {
$array[$field] = htmlspecialchars($value);
}
return $array;
}
function searchUserByEmail($link, $email) {
$result = null;
$email = mysqli_real_escape_string($link, $email);
$sql = "SELECT * FROM `users` WHERE `UserEmail` = '$email'";
$sql_query = mysqli_query($link, $sql);
if(!$sql_query) {
$errorMsg = 'Error: ' . mysqli_error($link_connection);
die($errorMsg);
}
$comparation_result = mysqli_fetch_assoc ($sql_query);
if ($comparation_result !== NULL) {
$result = $comparation_result;
}
return $result;
};
function include_template($name, $data) {
$name = 'templates/' . $name;
if(file_exists($name)) {
ob_start();
extract($data);
require_once $name;
$result = ob_get_clean();
} else {
$result = '';
}
return $result;
};
function calculatePrice($price) {
$price_round = ceil($price);
if ($price_round<1000) {
return $price_round;
} else if($price_round>1000) {
$price_format = number_format($price_round);
return $price_format. '<b class="rub">р</b>';
}
}
function calculateTimer() {
date_default_timezone_set('Australia/Sydney');
$curtime = date('H:i:s');
$future = strtotime('tomorrow');
$diff = $future - strtotime($curtime);
$hours = floor($diff / 3600);
$min = date('i', $diff);
print($hours.':'.$min);
}
function calculate_TimeBids($date) {
$ts=strtotime($date);
$time_diff = $_SERVER['REQUEST_TIME'] - $ts;
if ($time_diff > 86400) { // difference is more than 24h
$time_return = date('d.m.Y H:i', $ts);
}
else if ($time_diff > 3600) { // difference between 1h-24h
$time_return = date('G', $ts) . ' hours ago';
}
else { // less than 1h
$time_return = intval(date('i', $ts)) . ' minuts ago';
}
return $time_return;
}
function search_id_by_category($link, $category) {
$sqlCategory = "SELECT CategoryID FROM categories WHERE `CategoryName` = '$category'";
$category_id = mysqli_query($link, $sqlCategory);
if(!$category_id) {
$errorMsg = 'Error: ' . mysqli_error($link);
die($errorMsg);
}
$id = mysqli_fetch_assoc($category_id)['CategoryID'];
return $id;
}
function search_id_by_user($link, $user_name) {
$sqlUser = "SELECT UserID FROM users WHERE `UserName` = '$user_name'";
$user_id = mysqli_query($link, $sqlUser);
if(!$user_id) {
$errorMsg = 'Error: ' . mysqli_error($link);
die($errorMsg);
}
$id = mysqli_fetch_assoc($user_id)['UserID'];
return $id;
}
function search_id_by_lot($link, $lot) {
$sqlLot = "SELECT LotID FROM lots WHERE `LotName` = '$lot'";
$lot_id = mysqli_query($link, $sqlLot);
if(!$lot_id) {
$errorMsg = 'Error: ' . mysqli_error($link);
die($errorMsg);
}
$id = mysqli_fetch_assoc($lot_id)['LotID'];
return $id;
}
function validate_form_sign_up($form) {
require 'init.php';
$errors = [];
foreach ($form as $field => $value) {
if ($field == 'email') {
$email = mysqli_real_escape_string($link, $value);
$sql = "SELECT `UserEmail` FROM `Users` WHERE `UserEmail` = '$email'";
$sql_query = mysqli_query($link, $sql);
$result = mysqli_fetch_array ($sql_query);
if ($result !== NULL) {
$errors[$field] = 'This email is already been used';
}
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[$field] = 'Email has to be correct';
}
}
if ($field=== 'password') {
if (!preg_match('/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{5,}/', $value)) {
$errors['password'] = 'Must contain at least one number and one uppercase and lowercase letter, and at least 5 or more characters';
}
}
if ($field === 'name') {
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $value)) {
$errors['name'] = 'Should contain only alphanumeric!';
}
}
if ($field === 'message') {
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $value)) {
$errors['message'] = 'Should contain only alphanumeric!';
}
}
if (empty($value)) {
$errors[$field] = 'Fill up this field';
}
}
return $errors;
}
function validate_form_add($form) {
$errors = [];
foreach ($form as $field => $value) {
if ($field=== 'category') {
if($value==='Select category') {
$errors['category'] = 'Choose category';
}
}
if ($field=== 'lot-price') {
if(!filter_var($value, FILTER_VALIDATE_INT)) {
$errors['lot-price'] = 'Insert integer';
}
}
if ($field === 'lot-step') {
if(!filter_var($value, FILTER_VALIDATE_INT)) {
$errors['lot-step'] = 'Insert integer';
}
}
if ($field === 'lot-name') {
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $value)) {
$errors['lot-name'] = 'should contain only alphanumeric!';
}
}
if ($field === 'message') {
if (!preg_match('/^[a-zA-Z0-9-_]+$/', $value)) {
$errors['message'] = 'should contain only alphanumeric!';
}
}
if (empty($value)) {
$errors[$field] = 'Fill up this field';
}
}
return $errors;
}
?><file_sep><?php
require 'functions.php';
require 'config.php';
require 'init.php';
require 'nav.php';
$lot = null;
$cookie_name = 'lot_history';
$cookie_value = [];
$cookie_expire = strtotime("+30 days");
$cookie_path = "/";
$lot_id = $_GET['lot_id'];
if (!$link) {
$error = mysqli_connect_error();
$page_content = include_template('error.php', ['error' => $error]);
} else {
//set up all lots
$sqlLots = 'SELECT * FROM Lots as l
JOIN Categories AS c ON l.CategoryID=c.CategoryID
ORDER BY `LotDateTime` DESC LIMIT 9';
if ($res = mysqli_query($link, $sqlLots)) {
$lots = mysqli_fetch_all($res, MYSQLI_ASSOC);
}
else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
$sqlBidsQuantity= "SELECT * FROM bids
WHERE LotID = '$lot_id'";
if ($res = mysqli_query($link, $sqlBidsQuantity)) {
$bidsQuantity = mysqli_num_rows($res);
}
else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
$sqlBids= "SELECT * FROM Bids as b
JOIN Users AS u ON b.UserID=u.UserID
WHERE b.LotID = '$lot_id'
ORDER BY BidPrice DESC";
if ($res = mysqli_query($link, $sqlBids )) {
$bids = mysqli_fetch_all($res, MYSQLI_ASSOC);
}
else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
if (isset($_GET['lot_id'])) {
foreach ($lots as $key => $value) {
if ($key == $lot_id) {
$lot = $value;
break;
}
}
if (isset($_COOKIE['lot_history'])) {
$cookie_value = json_decode($_COOKIE['lot_history'], true);
}
if (!in_array($lot_id, $cookie_value)) {
$cookie_value[] = $lot_id;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$form = $_POST;
$errors=[];
if ($form['cost']) {
if(!filter_var($form['cost'], FILTER_VALIDATE_INT)) {
$errors['cost'] = 'Insert integer';
} else if(empty($form['cost'])) {
$errors['cost'] = 'Fill up this field';
}
}
if (count($errors)) {
$page_content = include_template('lot.php', [
'categories' => $categories,
'form' => $form,
'errors' => $errors,
]);
} else {
$cost = mysqli_real_escape_string($link, $form['cost']);
$user_id = search_id_by_user($link, $user_name);
$sqlNewLot = "INSERT INTO bids (`BidPrice`, `BidDate`, `UserID`)
VALUES ('$cost', NOW(), '$user_id')";
$resultNewLot = mysqli_query($link, $sqlNewLot);
if ($resultNewLot) {
}
else {
$error = mysqli_error($link);
$page_content = include_template('error.php', ['error' => $error]);
}
}
}
$page_content = include_template('lot.php', [
'categories' => $categories,
'lot' => $lot,
'is_auth' => $is_auth,
'bids' => $bids,
'bidsQuantity' => $bidsQuantity
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'categories' => $categories,
'user_name' => $user_name,
'user_avatar'=>$user_avatar,
'title' => 'Lot'
]);
print($layout_content);
?><file_sep><?php
require 'data.php';
require 'functions.php';
require 'config.php';
require 'init.php';
require 'nav.php';
$datetime = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$form = $_POST;
$lot_photo = $_FILES['lot-photo'];
$datetime = date("h:i:sa");
$errors=validate_form_add($form);
if ($_FILES['lot-photo']['name']) {
if (isset($_FILES['lot-photo']['name'])) {
$tmp_name = $lot_photo['tmp_name'];
$path = $lot_photo['name'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file_type = finfo_file($finfo, $tmp_name);
if ($file_type !== "image/jpeg") {
$errors['file'] = 'Upload photo in jpeg format';
}
else {
move_uploaded_file($tmp_name, 'img/' . $path);
$form['path'] = $path;
}
}
}
else {
$errors['file'] = 'You have not uploaded';
}
if (count($errors)) {
$page_content = include_template('add.php', [
'categories' => $categories,
'form' => $form,
'errors' => $errors,
]);
} else {
$lot_name = mysqli_real_escape_string($link, $form['lot-name']);
$category_id = search_id_by_category($link, $form['category']);
$description = mysqli_real_escape_string($link, $form['message']);
$lot_price= mysqli_real_escape_string($link, $form['lot-price']);
$lot_step = mysqli_real_escape_string($link, $form['lot-step']);
$path = mysqli_real_escape_string($link, $form['path']);
$sqlNewLot = "INSERT INTO lots (`LotName`, `LotStepBid`, `LotPrice`,`LotImgUrl`, `LotDescription`,`CategoryID`, `LotDateTime`)
VALUES ('$lot_name', '$lot_step', '$lot_price','./img/$path', '$description','$category_id', NOW())";
$resultNewLot = mysqli_query($link, $sqlNewLot);
if ($resultNewLot) {
// request on showing 9 recent lots
$sqlLots = 'SELECT * FROM Lots as l
JOIN Categories AS c ON l.CategoryID=c.CategoryID
ORDER BY `LotDateTime` DESC LIMIT 9';
if ($res = mysqli_query($link, $sqlLots)) {
$lots = mysqli_fetch_all($res, MYSQLI_ASSOC);
}
else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
$page_content = include_template('index.php', [
'categories' => $categories,
'lots' => $lots,
]);
}
else {
$error = mysqli_error($link);
$page_content = include_template('error.php', ['error' => $error]);
}
}
}
else {
$page_content = include_template('add.php', [
'categories' => $categories,
]);
}
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'categories' => $categories,
'user_name' => $user_name,
'user_avatar'=>$user_avatar,
'title' => 'Add lot'
]);
print($layout_content);
?><file_sep><?php
require_once 'functions.php';
$db = [
'host' => 'localhost',
'user' => 'root',
'password' => '',
'database' => 'yeticave'
];
$link = mysqli_connect($db['host'], $db['user'],$db['password'], $db['database']);
mysqli_set_charset($link, 'utf8');
$categories = [];
$page_content='';
?><file_sep><?php
require 'init.php';
require 'config.php';
$lots = [];
if (isset($_COOKIE['lot_history'])) {
$cookies = json_decode($_COOKIE['lot_history']);
$lots = implode(', ', $cookies);
$cur_page = $_GET['page'] ?? 1;
$page_items = 6;
$sql_count = "SELECT COUNT(*) AS `count`
FROM `lots`
WHERE `LotID` IN ($lots)";
$sql_query_count = mysqli_query($link, $sql_count);
if ($sql_query_count) {
$items_count = mysqli_fetch_assoc($sql_query_count)['count'];
$pages_count = ceil($items_count / $page_items);
$offset = ($cur_page - 1) * $page_items;
$pages = range(1, $pages_count);
$sql = "SELECT * FROM Lots as l
JOIN Categories AS c ON l.CategoryID=c.CategoryID
WHERE l.LotID IN ($lots)
LIMIT $page_items
OFFSET $offset";
if ($sql_query = mysqli_query($link, $sql)) {
$url = $_SERVER['REQUEST_URI'];
$url = explode('?page', $url)[0];
$lots = mysqli_fetch_all($sql_query, MYSQLI_ASSOC);
$page_content = include_template('history.php', [
'url' => $url,
'lots' => $lots,
'nav_menu' => $nav_menu,
'pages' => $pages,
'pages_count' => $pages_count,
'cur_page' => $cur_page
]);
}
else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
}
else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
}
else {
$page_content = include_template('error.php', ['error_title' => 'Ваша история просмотров пуста']);
}
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'categories' => $categories,
'user_name' => $user_name,
'user_avatar'=>$user_avatar,
'title' => 'History'
]);
print($layout_content);
?>
<file_sep><section class="promo">
<h2 class="promo__title">Looking for a snowsport equipment?</h2>
<p class="promo__text">On our auction you will find exclusive equipment for snowboarding and skiing!</p>
<ul class="promo__list">
<?php foreach($categories as $value): ?>
<li class="promo__item promo__item--<?=$value['CategoryClass']?>">
<a class="promo__link" href="all-lots.html"><?=$value['CategoryName']?></a>
</li>
<?php endforeach; ?>
</ul>
</section>
<section class="lots">
<div class="lots__header">
<h2>Open lots</h2>
</div>
<ul class="lots__list">
<?php foreach($lots as $item => $value): ?>
<li class="lots__item lot">
<div class="lot__image">
<img src="<?=$value['LotImgUrl']?>" width="350" height="260" alt="<?=$value['LotCategory']?>">
</div>
<div class="lot__info">
<span class="lot__category"><?=$value['CategoryName']?></span>
<h3 class="lot__title"><a class="text-link"
href="<?= "lot.php?lot_id=$item" ?>"><?=$value['LotName']?></a>
</h3>
<div class="lot__state">
<div class="lot__rate">
<span class="lot__amount">Start price</span>
<span class="lot__cost"><?=calculatePrice($value['LotPrice']).' €'?></span>
</div>
<div class="lot__timer timer"><?=calculateTimer();?></div>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
</section>
<file_sep> <?php
$sql = 'SELECT `CategoryName`, `CategoryClass` FROM categories';
$result = mysqli_query($link, $sql);
if ($result) {
$categories = mysqli_fetch_all($result, MYSQLI_ASSOC);
} else {
$page_content = include_template('error.php', ['error' => mysqli_error($link)]);
}
<file_sep><main>
<nav class="nav">
<ul class="nav__list container">
<?php foreach($categories as $key => $value): ?>
<li class="nav__item">
<a href="all-lots.html"><?=$value['CategoryName']?></a>
</li>
<?php endforeach?>
</ul>
</nav>
<section class="lot-item container">
<h2><?= $lot['LotName'] ?></h2>
<div class="lot-item__content">
<div class="lot-item__left">
<div class="lot-item__image">
<img src="<?='./'.$lot['LotImgUrl'] ?>" width="730" height="548" alt="<?= $lot['LotName'] ?>">
</div>
<p class="lot-item__category">Category: <span><?= $lot['CategoryName'] ?></span></p>
<p class="lot-item__description"><?= $lot['LotDescription'] ?></p>
</div>
<div class="lot-item__right">
<div class="lot-item__state">
<div class="lot-item__timer timer">
10:54:12
</div>
<div class="lot-item__cost-state">
<div class="lot-item__rate">
<span class="lot-item__amount">Current price</span>
<span class="lot-item__cost"><?= $lot['LotPrice'] .' €'?></span>
</div>
<div class="lot-item__min-cost">
Min bid <span><?= $lot['LotPrice'] + $lot['LotStepBid']?> €</span>
</div>
</div>
<?php if ($is_auth): ?>
<form class="lot-item__form" action="lot.php" method="post">
<p class="lot-item__form-item">
<label for="cost">Your bid</label>
<input id="cost" type="number" name="cost"
min="<?= $lot['LotPrice'] + $lots['LotStepBid']?>"
placeholder="<?= $lot['LotPrice'] + $lot['LotStepBid']?>">
</p>
<button type="submit" class="button">Make bid</button>
</form>
<?php endif; ?>
</div>
<div class="history">
<h3>Bid history <?= $bidsQuantity ?></h3>
<?php if ($bidsQuantity>0): ?>
<table class="history__list">
<?php foreach($bids as $key => $value): ?>
<tr class="history__item">
<td class="history__name"><?=$value['UserName']?></td>
<td class="history__price"><?=$value['BidPrice']?> €</td>
<td class="history__time"><?=calculate_TimeBids($value['BidDateTime'])?></td>
</tr>
<?php endforeach?>
</table>
<?php endif?>
</div>
</div>
</div>
</section ection>
</main>
<file_sep><?php
$lot_name = $form['lot-name'] ?? '';
$category = $form['category'] ?? 'Select category';
$message = $form['message'] ?? '';
$lot_price = $form['lot-price'] ?? '';
$lot_step = $form['lot-step'] ?? '';
$lot_date = $form['lot-date'] ?? '';
?>
<main>
<nav class="nav">
<ul class="nav__list container">
<?php foreach($categories as $key => $value): ?>
<li class="nav__item">
<a href="all-lots.html"><?=$value['CategoryName']?></a>
</li>
<?php endforeach?>
</ul>
</nav>
<form class="form form--add-lot container <?= isset($errors) ? 'form--invalid' : '' ?>"
enctype="multipart/form-data" action="add.php" method="post">
<h2>Adding lot</h2>
<div class="form__container-two">
<div class="form__item <?= isset($errors['lot-name']) ? 'form__item--invalid' : '' ?>">
<label for="lot-name">Name</label>
<input id="lot-name" type="text" name="lot-name" placeholder="Enter lot name"
value="<?= $lot_name ?>" />
<span class="form__error"><?= $errors['lot-name'] ?? '' ?></span>
</div>
<div class="form__item <?= isset($errors['category']) ? 'form__item--invalid' : '' ?>">
<label for="category">Category</label>
<select id="category" name="category" required>
<option selected>Select category</option>
<?php foreach($categories as $key => $value): ?>
<option><?=$value['CategoryName']?></option>
<?php endforeach?>
</select>
<span class="form__error"><?= $errors['category'] ?? '' ?></span>
</div>
</div>
<div class="form__item form__item--wide <?= isset($errors['message']) ? 'form__item--invalid' : '' ?>">
<label for="message">Description</label>
<textarea id="message" name="message" placeholder="Enter lot description"><?= $message ?></textarea>
<!-- required -->
<span class="form__error"><?= $errors['message'] ?? '' ?></span>
</div>
<div class="form__item form__item--file <?= isset($errors['file']) ? 'form__item--invalid' : '' ?>">
<!-- form__item--uploaded -->
<label>Photo</label>
<div class="preview">
<button class="preview__remove" type="button">x</button>
<div class="preview__img">
<img src="img/avatar.jpg" width="113" height="113" alt="Photo of lot" />
</div>
</div>
<div class="form__input-file">
<input class="visually-hidden" type="file" id="photo2" name="lot-photo" />
<label for="photo2">
<span>+ Add</span>
</label>
<span class="form__error"><?= $errors['file'] ?? '' ?></span>
</div>
</div>
<div class="form__container-three">
<div class="form__item form__item--small <?= isset($errors['lot-price']) ? 'form__item--invalid' : '' ?>">
<label for="lot-price">Start price</label>
<input id="lot-price" type="number" name="lot-price" placeholder="0" value="<?= $lot-price ?>" />
<span class="form__error"><?= $errors['lot-price'] ?? '' ?></span>
</div>
<div class="form__item form__item--small <?= isset($errors['lot-step']) ? 'form__item--invalid' : '' ?>">
<label for="lot-step">Bid step</label>
<input id="lot-step" type="number" name="lot-step" placeholder="0" value="<?= $lot_step ?>" />
<span class="form__error"><?= $errors['lot-step'] ?? '' ?></span>
</div>
<div class="form__item <?= isset($errors['lot-date']) ? 'form__item--invalid' : '' ?>">
<label for="lot-date">Auction final date</label>
<input class="form__input-date" id="lot-date" type="date" name="lot-date" value="<?= $lot_date ?>" />
<span class="form__error"><?= $errors['lot-date'] ?? '' ?></span>
</div>
</div>
<span class="form__error form__error--bottom">Please, correct mistakes in your form</span>
<button type="submit" class="button">Upload lot</button>
</form>
</main>
<file_sep><?php
require 'config.php';
require 'functions.php';
require 'init.php';
require 'nav.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$form = $_POST;
$required = ['email', 'password'];
$errors = [];
$user = searchUserByEmail($link, $form['email']);
foreach ($form as $field => $value) {
if ($field == 'email') {
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$errors[$field] = 'Email has to be correct';
}
}
if (empty($value) ) {
$errors[$field] = 'Fill up this field';
}
};
if (!count($errors) && $user) {
if (password_verify($form['password'], $user['UserPassword'])) {
$_SESSION['user'] = $user;
}
else {
$errors['password'] = '<PASSWORD>';
}
}
else {
$errors['email'] = 'This email have not been found';
}
if (count($errors)) {
$page_content = include_template('login.php', [
'categories' => $categories,
'form' => $form,
'errors' => $errors
]);
}
else {
header('Location: ./index.php');
exit();
}
}
else {
if (isset($_SESSION['user'])) {
$page_content = include_template('index.php', [
'lots' => $lots,
'categories' => $categories,
]);
}
else {
$page_content = include_template('login.php', [
'categories' => $categories,
]);
}
}
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'categories' => $categories,
'user_name' => $user_name,
'user_avatar'=>$user_avatar,
'title' => 'Login'
]);
print($layout_content);
?><file_sep><?php
session_start();
$is_auth = false;
$user_name = null;
$user_avatar = null;
if (isset($_SESSION['user'])) {
$user_name = $_SESSION['user']['UserName'];
$is_auth = true;
$user_avatar = $_SESSION['user']['UserImgPath'];
}
| 31232cd904f207426f4f42af4cda1379b70885d4 | [
"Markdown",
"SQL",
"PHP"
] | 20 | SQL | tati267/php_1 | a6492c8e93ef0ae2d33ed687d53f6439d31d05cc | 59feb2dbcf227c9e47ccde05ac8090330ecc3030 |
refs/heads/master | <file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
puts 'iniciando seed'
puts 'limpando registros'
Cocktail.destroy_all
Dose.destroy_all
Ingredient.destroy_all
puts 'criando um registro'
10.times do
cocktails = Cocktail.create(
name: Faker::Beer.malts
)
ingredients = Ingredient.create(
name: Faker::Food.ingredient
)
Dose.create(
description: Faker::Food.measurement,
cocktail: cocktails,
ingredient: ingredients
)
end
puts 'seed feito com sucesso'
| 144897dda23201760ca7c93b34d7120e5d585dc7 | [
"Ruby"
] | 1 | Ruby | Appiopini/rails-mister-cocktail | 610414b4c67e60f2fd8660ff9cd47f59c65bab32 | 4b291e3478f75e4c28311c446bcf8b3f0e963519 |
refs/heads/master | <file_sep>class Init {
constructor(sensor, motor) {
this.sensor = sensor;
this.motor = motor;
console.log('App initialized');
/*
* Setting interval to test out sensor every second.
*/
// setInterval(this.interval.bind(this.sensor), 1000);
this.motor.forward();
// Check if distance is lesser than the allowed distance
this.lowestAllowedDistance = 18; // in cm
this.sensor.on('distancechanged', () => {
// console.log(`Motor ${(this.sensor.distance < this.lowestAllowedDistance) ? 'stopped' : 'running'}. Distance: ${this.sensor.distance}`);
// Stop motor if distance of object exceeds the specified max distance
if(this.sensor.distance < this.lowestAllowedDistance) {
// this.motor.stop();
// console.log('STOP!');
} else {
// this.motor.forward();
}
});
}
}
export default Init;
<file_sep>import Dotenv from 'dotenv';
import Init from './app/init';
import Motor from './app/module/motor';
import Sensor from './app/module/sensor';
Dotenv.config();
const init = new Init(
new Sensor(
process.env.HCSRO4_TRIGGER,
process.env.HCSRO4_ECHO,
),
new Motor(
process.env.LP293D_VCC,
process.env.LP293D_INPUT1,
process.env.LP293D_INPUT2,
),
);
| 0ee575c79c5f96f8dfbaddd33446e7850e021cd3 | [
"JavaScript"
] | 2 | JavaScript | georgeneokq/PiTest | a27646bd7aff3a6aefa4983c28276de0ca416777 | 901d03f56b7444c4ac81e6b68c250f57d8cce152 |
refs/heads/master | <repo_name>firstandthird/hapi-micro-mail<file_sep>/README.md
# hapi-micro-mail
[Hapi](https://hapi.dev/) plugin for posting emails to your [micro mail](https://github.com/firstandthird/micro-mail) email server. You will need to either set up or have access to a micro-mail instance to use this plugin.
## Installation
```
npm install hapi-micro-mail
```
## Register the Plugin
Assuming you have a micro-mail server set up at `https://my-mail.com` and its API key is '12345', just register the hapi-micro-mail plugin with hapi:
```js
await server.register({
plugin: require('hapi-micro-mail'),
options: {
host: 'https://my-mail.com',
apiKey: '12345'
}
});
```
__You must include the host and apiKey fields to use this plugin__. This will decorate the server with the `sendEmail()` and `renderEmail` functions.
## sendEmail()
Your code should wrap calls to this function in a `try...catch` block as there are many errors that can occur when sending an email:
Sending an explicit text email:
```js
try {
const output = await server.sendEmail({
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'this is the subject of an email I am sending to you',
text: 'This is the text of the email I am sending to you!'
});
} catch (e) {
server.log(['email-error', 'error!'], e.toString());
// (maybe do something else with your error here)
}
```
Rendering and sending an email template hosted on micro-mail:
```js
try {
const output = await server.sendEmail({
from: '<EMAIL>',
// 'to' can also be an array for multiple recipients:
to: ['<EMAIL>', '<EMAIL>', '<EMAIL>'],
subject: 'Welcome!',
template: 'welcome-message',
data: {
'login': '<EMAIL>',
'public_handle': '<EMAIL>hill'
}
});
} catch (e) {
server.log(['email-error', 'error!'], e.toString());
// (maybe do something else with your error here)
}
```
If successful, `output` will look something like:
```js
{
status: 'ok',
message: 'Email delivered',
result: { response: '250 Message queued', accepted: [ '<EMAIL>' ] }
}
```
## Fields
Valid fields that you can specify in `sendEmail` are:
- _to_ (required): An email address or array of email addresses specifying the email destination
- _from_: The email address of the sender, this is ignored if the micro-mail server already has a configured sender.
- _fromName_: The common name of the sender, this is also ignored if the micro-mail server already has a configured sender.
- _subject_: The subject of the email
- _text_ (required if _template_ was not specified): The text of the email to send, if this is specified it will override anything you set in the _template_ field.
- _template_(required if _text_ was not specified): The slug of the template you wish to render and send as the text of the email.
- _data_: An object containing the context for the _template_ you wish to render. If you requested a _template_ email, then you will need to pass any values the template relies on for rendering in here.
- _headers_: Any additional headers that you want micro-mail to forward to the SMTP server.
- _trackingData_: An object containing tracking-specific information to include in your email
- _disableTracking_: Set to true to specify you want to include tracking data
## Errors
- HTTP errors
If there is an _HTTP error_ (some type of network-level error that prevents you from correctly communicating with your micro-mail server) then `sendEmail()` will throw a hapi [boom](https://github.com/hapijs/boom) error, an Error object which contains additional HTTP-specific error information useful for diagnosing network errors. You must catch this error in your own code.
- SMTP errors
If there is an _SMTP error_ (you communicated correctly with your micro-mail server, but it was unable to successfully send the email for some reason) then `sendEmail()` will throw a normal Javascript Error object, except that it will have an additional `result` field containing information about the type of SMTP error that occurred, including the [SMTP error code](https://en.wikipedia.org/wiki/List_of_SMTP_server_return_codes) and a list of which email destinations were successfully sent and which were rejected:
```js
result: {
accepted: [],
rejected: [ '<EMAIL>' ],
response: '502 Command not implemented'
}
```
The _message_ for this Error will be handed back to you by the micro-mail server, but the _stack trace_ for the error will still be for your local server. You must catch this error in your own code.
## Render Email
micro-mail also hosts an email template rendering service. Identical to view rendering with HTML pages, you pass it some data and the name of the template and it will fill out the template using the data you provided. You can use the `renderEmail()` function to preview what your email will look like with a given set of data. It will not actually send the email, just return back the email packet so you can verify what it will look like before you send it out.
So if your micro-mail server has a template named `welcome-email`:
```html
<h1>Welcome {{username}}!</h1>
Your login is: <b> {{login}} </b>
```
you can preview it without really sending it:
```js
const html = await server.renderEmail({
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'this is the subject of an email I am sending to you',
template: 'welcome-email',
data: {
username: 'jill_valentine',
login: 'zombie_hunter'
}
});
```
and `html` will be the string:
```HTML
<h1>Welcome jill_valentine!</h1>
Your login is: <b> zombie_hunter </b>
```
`renderEmail()` accepts all of the fields that the `sendEmail()` function accepts. The only difference is that it won't actually send the email and only returns the rendered email text.
## Plugin Options
The following are options you specify when you register the plugin:
- _host_ (required)
Complete URL of the micro-mail instance, should start with 'http://' or 'https://'
- _apiKey_ (required)
micro-mail uses a token-based API key to prevent unauthorized use, you must specify the server's API key when you register the plugin.
- _verbose_
Verbose mode, when set to true this will log information about every email you send out on the local hapi server.
<file_sep>/test/plugin.test.js
'use strict';
const code = require('code');
const Hapi = require('hapi');
const lab = exports.lab = require('lab').script();
const boom = require('boom');
let server;
let microMailServer;
lab.afterEach(async() => {
await microMailServer.stop();
});
lab.beforeEach(async() => {
server = new Hapi.Server({
debug: {
log: 'hapi-micro-mail'
},
port: 8000
});
await server.register({
plugin: require('../'),
options: {
host: 'http://localhost:8080',
apiKey: 'jksdf',
verbose: true
}
});
microMailServer = new Hapi.Server({ port: 8080 });
await microMailServer.start();
});
lab.describe('.sendEmail', { timeout: 5000 }, () => {
lab.it('can handle an HTTP error response from the micro-mail server', async() => {
microMailServer.route({
path: '/send',
method: 'POST',
handler: (request, h) => {
code.expect(request.payload.from).to.equal('<EMAIL>');
throw boom.badRequest({
message: 'Validation error',
result: '"to" is required'
});
}
});
const badParams = {
from: '<EMAIL>',
subject: 'This is a subject',
text: 'Hello there email text'
};
try {
await server.sendEmail(badParams);
} catch (err) {
code.expect(err).to.not.equal(null);
code.expect(err.isBoom).to.equal(true);
code.expect(err.output.payload.error).to.equal('Bad Request');
}
});
lab.it('can handle a micro-mail server SMTP error', async() => {
microMailServer.route({
path: '/send',
method: 'POST',
handler: (request, h) => {
return {
status: 'error',
message: 'Boo',
result: {
accepted: [],
rejected: ['nobody<EMAIL>'],
response: '502 Command not implemented'
}
};
}
});
const badParams = {
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'This is a subject',
text: 'Hello there email text'
};
try {
await server.sendEmail(badParams);
} catch (err) {
code.expect(err).to.not.equal(null);
code.expect(err.message).to.equal('Boo');
code.expect(err.result.response).to.equal('502 Command not implemented');
code.expect(err.result.rejected.length).to.equal(1);
}
});
lab.it('can send an email to a micro-mail server', async() => {
microMailServer.route({
path: '/send',
method: 'POST',
handler: (request, h) => {
code.expect(request.payload.from).to.equal('<EMAIL>');
code.expect(request.payload.to).to.equal('<EMAIL>');
code.expect(request.payload.subject).to.equal('this is the subject of an email I am sending to you');
code.expect(request.payload.text).to.equal('This is the text of the email I am sending to you!');
return {
status: 'ok',
message: 'Email delivered',
result: {
response: '250 Message queued',
accepted: [request.payload.to]
}
};
}
});
const res = await server.sendEmail({
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'this is the subject of an email I am sending to you',
text: 'This is the text of the email I am sending to you!'
});
code.expect(res.status).to.equal('ok');
code.expect(res.result.accepted.length).to.equal(1);
code.expect(res.result.accepted[0]).to.equal('<EMAIL>');
});
lab.it('can render an email from a micro-mail server', async() => {
microMailServer.route({
path: '/render',
method: 'POST',
handler: (request, h) => {
code.expect(request.payload.from).to.equal('<EMAIL>');
code.expect(request.payload.to).to.equal('<EMAIL>');
code.expect(request.payload.subject).to.equal('this is the subject of an email I am sending to you');
code.expect(request.payload.text).to.equal('This is the text of the email I am sending to you!');
return '<html><h1>HI!</h1></html>';
}
});
const data = await server.renderEmail({
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'this is the subject of an email I am sending to you',
text: 'This is the text of the email I am sending to you!'
});
code.expect(data).to.equal('<html><h1>HI!</h1></html>');
});
});
| c62bfe1ac542021bb3b3b483e4314a9e7689f7c3 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | firstandthird/hapi-micro-mail | 325efb78814aa55e4fbb9dc940731be6fad41d64 | 1b6b7672c5010ab4cab1746dbe3de5ad2b910f4e |
refs/heads/master | <file_sep>package me.jfenn.alarmio.adapters
import android.animation.Animator
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.view.HapticFeedbackConstants
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.appcompat.widget.SwitchCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.AutoTransition
import androidx.transition.TransitionManager
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import com.afollestad.aesthetic.Aesthetic
import me.jfenn.alarmio.Alarmio
import me.jfenn.alarmio.R
import me.jfenn.alarmio.data.AlarmData
import me.jfenn.alarmio.data.TimerData
import me.jfenn.alarmio.dialogs.AestheticTimeSheetPickerDialog
import me.jfenn.alarmio.dialogs.AlertDialog
import me.jfenn.alarmio.dialogs.SoundChooserDialog
import me.jfenn.alarmio.utils.FormatUtils
import me.jfenn.alarmio.views.DaySwitch
import me.jfenn.alarmio.views.ProgressLineView
import me.jfenn.androidutils.DimenUtils
import me.jfenn.timedatepickers.dialogs.PickerDialog
import me.jfenn.timedatepickers.views.LinearTimePickerView
import java.util.*
import java.util.concurrent.TimeUnit
/**
* View adapter for the "alarms" list; displays all timers and
* alarms currently stored in the application.
*/
class AlarmsAdapter(private val alarmio: Alarmio, private val recycler: RecyclerView, private val fragmentManager: FragmentManager) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val alarmManager: AlarmManager? = alarmio.getSystemService(Context.ALARM_SERVICE) as? AlarmManager?
private val timers: List<TimerData> = alarmio.timers
private val alarms: List<AlarmData> = alarmio.alarms
private var expandedPosition = -1
var colorAccent = Color.WHITE
set(colorAccent) {
field = colorAccent
recycler.post { notifyDataSetChanged() }
}
var colorForeground = Color.TRANSPARENT
set(colorForeground) {
field = colorForeground
if (expandedPosition > 0)
recycler.post { notifyItemChanged(expandedPosition) }
}
var textColorPrimary = Color.WHITE
set(textColorPrimary) {
field = textColorPrimary
recycler.post { notifyDataSetChanged() }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == 0)
TimerViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_timer, parent, false))
else
AlarmViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_alarm, parent, false), alarmio)
}
private fun onBindTimerViewHolder(holder: TimerViewHolder, position: Int) {
holder.runnable = object : Runnable {
override fun run() {
try {
getTimer(holder.adapterPosition)?.let { timer ->
val text = FormatUtils.formatMillis(timer.remainingMillis)
holder.time.text = text.substring(0, text.length - 3)
holder.progress.update(1 - timer.remainingMillis.toFloat() / timer.duration)
}
holder.handler.postDelayed(this, 1000)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
holder.stop.setColorFilter(textColorPrimary)
holder.stop.setOnClickListener {
getTimer(holder.adapterPosition)?.let { timer ->
alarmio.removeTimer(timer)
}
}
}
@SuppressLint("CheckResult")
private fun onBindAlarmViewHolderExpansion(holder: AlarmViewHolder, position: Int) {
val isExpanded = position == expandedPosition
val visibility = if (isExpanded) View.VISIBLE else View.GONE
if (false) { //visibility != holder.extra.visibility
// holder.extra.visibility = visibility
Aesthetic.get()
.colorPrimary()
.take(1)
.subscribe { integer ->
ValueAnimator.ofObject(
ArgbEvaluator(),
if (isExpanded) integer else colorForeground,
if (isExpanded) colorForeground else integer
).apply {
addUpdateListener { animation ->
(animation.animatedValue as? Int)?.let { color ->
holder.itemView.setBackgroundColor(color)
}
}
addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {}
override fun onAnimationEnd(animation: Animator) {
holder.itemView.setBackgroundColor(if (isExpanded) colorForeground else Color.TRANSPARENT)
}
override fun onAnimationCancel(animation: Animator) {}
override fun onAnimationRepeat(animation: Animator) {}
})
start()
}
}
ValueAnimator.ofFloat(
if (isExpanded) 0f else DimenUtils.dpToPx(2f).toFloat(),
if (isExpanded) DimenUtils.dpToPx(2f).toFloat() else 0f
).apply {
addUpdateListener { animation ->
(animation.animatedValue as? Float)?.let { elevation ->
ViewCompat.setElevation(holder.itemView, elevation)
}
}
start()
}
} else {
holder.itemView.setBackgroundColor(if (isExpanded) colorForeground else Color.TRANSPARENT)
ViewCompat.setElevation(holder.itemView, (if (isExpanded) DimenUtils.dpToPx(2f) else 0).toFloat())
}
holder.itemView.setOnClickListener {
expandedPosition = if (isExpanded) -1 else holder.adapterPosition
val transition = AutoTransition()
transition.duration = 250
TransitionManager.beginDelayedTransition(recycler, transition)
recycler.post { notifyDataSetChanged() }
}
}
private fun onBindAlarmViewHolder(holder: AlarmViewHolder, position: Int) {
val alarm = getAlarm(position) ?: return
holder.enable.setOnCheckedChangeListener(null)
holder.enable.isChecked = alarm.isEnabled
holder.enable.setOnCheckedChangeListener { _, b ->
alarm.setEnabled(alarmio, alarmManager, b)
val transition = AutoTransition()
transition.duration = 200
TransitionManager.beginDelayedTransition(recycler, transition)
recycler.post { notifyDataSetChanged() }
}
holder.time.text = FormatUtils.formatShort(alarmio, alarm.time.time)
holder.time.setOnClickListener { view ->
AestheticTimeSheetPickerDialog(view.context, alarm.time.get(Calendar.HOUR_OF_DAY), alarm.time.get(Calendar.MINUTE))
.setListener(object : PickerDialog.OnSelectedListener<LinearTimePickerView> {
override fun onSelect(dialog: PickerDialog<LinearTimePickerView>, view: LinearTimePickerView) {
alarm.time.set(Calendar.HOUR_OF_DAY, view.hourOfDay)
alarm.time.set(Calendar.MINUTE, view.minute)
alarm.setTime(alarmio, alarmManager, alarm.time.timeInMillis)
alarm.setEnabled(alarmio, alarmManager, true);
notifyItemChanged(holder.adapterPosition)
}
override fun onCancel(dialog: PickerDialog<LinearTimePickerView>) {
// ignore
}
})
.show()
}
holder.nextTime.visibility = if (alarm.isEnabled) View.VISIBLE else View.GONE
val nextAlarm = alarm.next
if (alarm.isEnabled && nextAlarm != null) {
// minutes in a week: 10080
// maximum value of an integer: 2147483647
// we do not need to check this int cast
val minutes = TimeUnit.MILLISECONDS.toMinutes(nextAlarm.timeInMillis - Calendar.getInstance().timeInMillis).toInt()
holder.nextTime.text = String.format(alarmio.getString(R.string.title_alarm_next), FormatUtils.formatUnit(alarmio, minutes))
}
onBindAlarmViewHolderExpansion(holder, position)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (getItemViewType(position) == 0 && holder is TimerViewHolder) {
onBindTimerViewHolder(holder, position)
} else if (holder is AlarmViewHolder) {
onBindAlarmViewHolder(holder, position)
}
}
override fun getItemViewType(position: Int): Int {
return if (position < timers.size) 0 else 1
}
override fun getItemCount(): Int {
return timers.size + alarms.size
}
/**
* Returns the timer that should be bound to the
* specified position in the list - null if there
* is no timer to be bound.
*/
private fun getTimer(position: Int): TimerData? {
return if (position in (0 until timers.size))
timers[position]
else null
}
/**
* Returns the alarm that should be bound to
* the specified position in the list - null if
* there is no alarm to be bound.
*/
private fun getAlarm(position: Int): AlarmData? {
val alarmPosition = position - timers.size
return if (alarmPosition in (0 until alarms.size))
alarms[alarmPosition]
else null
}
/**
* ViewHolder for timer items.
*/
class TimerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val handler = Handler()
var runnable: Runnable? = null
set(runnable) {
if (field != null)
handler.removeCallbacks(field)
field = runnable
handler.post(field)
}
val time: TextView = itemView.findViewById(R.id.time)
val stop: ImageView = itemView.findViewById(R.id.stop)
val progress: ProgressLineView = itemView.findViewById(R.id.progress)
}
/**
* ViewHolder for alarm items.
*/
class AlarmViewHolder(v: View, val alarmio: Alarmio) : RecyclerView.ViewHolder(v) {
val enable: SwitchCompat = v.findViewById(R.id.enable)
val time: TextView = v.findViewById(R.id.time)
val nextTime: TextView = v.findViewById(R.id.nextTime)
val alarms: List<AlarmData> = alarmio.alarms
}
}
| 23c984a6f1de06888c5ab54d4608e77567f7b00e | [
"Kotlin"
] | 1 | Kotlin | Hoffa25/androidalarmapp | 98606a2dda9f593c427bac15e2c4533124fbca6b | 7a31f08febac94a6c80b75dafc2e648a6ce38192 |
refs/heads/master | <repo_name>wozane/react-tests<file_sep>/src/App.test.js
import React from 'react'
import { shallow } from 'enzyme'
import App from './App'
describe('App', () => {
const wrapper = shallow(<App />)
it('should have `th` "Items"', () => {
expect(wrapper.contains(<th>Items</th>)).toBe(true)
})
it('should have button element', () => {
expect(wrapper.containsMatchingElement(<button>Add item</button>)).toBe(true)
})
it('`button` should be disabled', () => {
const button = wrapper.find('button').first()
expect(button.props().disabled).toBe(true)
})
})
| 9327afac1527761332f738c700f0b4902521ad7c | [
"JavaScript"
] | 1 | JavaScript | wozane/react-tests | a76dda88fbc8f7c732b8ab1bfe9d2f11c6177565 | 98fb20e8ca3bee008f9a39779b11cdb61373f579 |
refs/heads/main | <file_sep>g++ read_TH02.cpp ../TH02_dev.cpp ../../Grove_I2C_Com/I2C_Com.cpp -I.. -I../../Grove_I2C_Com/ -li2c
<file_sep>/*
I2C_Com.cpp
Driver for DIGITAL I2C Communication
Copyright (c) 2021 <NAME>
Website : https://github.com/zieglermax/Grove_RPi_Lib
Author : <NAME>
Create Time: January 2021
Change Log :
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/****************************************************************************/
/*** Include files ***/
/****************************************************************************/
#include <unistd.h>
#include <stdlib.h>
#include "I2C_Com.h"
#ifndef CROSS_COMPILE
extern "C" {
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>
}
#include <sys/ioctl.h>
#endif // CROSS_COMPILE
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <cstdint>
#include <iostream>
/****************************************************************************/
/*** Class member Functions ***/
/****************************************************************************/
I2C_Com::I2C_Com(const unsigned int dev, const uint8_t DevId) {
/* Init IIC Interface */
std::cout << "Initalizing I²C Interface" << std::endl;
I2C_DEV_ADR = DevId;
std::string dev_name = "/dev/i2c-" + std::to_string(dev);
//dev_name += std::to_string(dev);
if ( (I2C_Device = open( dev_name.c_str(), O_RDWR)) < 0)
{
perror("open() failed");
}
printf(" OK\n");
/* Specify Address of slave i2c_device */
if (ioctl( I2C_Device, I2C_SLAVE, I2C_DEV_ADR) < 0)
{
printf("Failed to acquire bus access and/or talk to slave\n");
}
}
I2C_Com::~I2C_Com() {
/* Init IIC Interface */
std::cout << "Deinitalizing I²C Interface" << std::endl;
if (0 < close(I2C_Device) )
{
perror("close() failed");
}
std::cout << "I²C i2c_device Deinitialized succesfully." << std::endl;
}
/****************************************************************************/
/*** Local Functions ***/
/****************************************************************************/
uint8_t I2C_Com::isAvailable() {
uint8_t status = I2C_ReadReg(I2C_REG_STATUS);
if (status & I2C_STATUS_RDY_MASK) {
return 0; //ready
} else {
return 1; //not ready yet
}
}
void I2C_Com::I2C_WriteCmd(const uint8_t Cmd) {
i2c_smbus_write_byte(I2C_Device, Cmd);
}
uint8_t I2C_Com::I2C_ReadReg(const uint8_t Reg) {
uint8_t TempReg = 0;
TempReg = (uint8_t) i2c_smbus_read_byte_data(I2C_Device, Reg);
return TempReg;
}
void I2C_Com::I2C_WriteReg(const uint8_t Reg, const uint8_t Data) {
i2c_smbus_write_byte_data( I2C_Device, Reg, Data);
}
uint8_t I2C_Com::I2C_ReadData(const uint8_t reg) {
uint8_t Temp = i2c_smbus_read_byte_data( I2C_Device, reg );
return Temp;
}
uint16_t I2C_Com::I2C_ReadData2byte(const uint8_t regL, const uint8_t regH ) {
uint16_t TempData = 0;
uint8_t datah=0, datal=0;
datah = i2c_smbus_read_byte_data( I2C_Device, regH );
datal = i2c_smbus_read_byte_data( I2C_Device, regL );
TempData = (datah << 8) | datal;
//std::cout << "RawTemp Value: " << TempData << std::endl;
return TempData;
}
uint16_t I2C_Com::I2C_ReadData2byte(const uint8_t reg) {
uint16_t TempData = 0;
TempData = i2c_smbus_read_word_data( I2C_Device, reg );
//std::cout << "RawTemp Value: " << TempData << std::endl;
return TempData;
}
<file_sep>SMBUS basic communication class used for SEEED Grove components
<file_sep>#include "TH02_dev.h"
#include <iostream>
#include <stdio.h>
int main (int argc, char *argv[])
{
TH02_dev th02;
std::cout << "Start to read TH02 Temperature and Humidity" << std::endl;
for( int i = 0; i< 1000; i++)
{
std::cout << " Temp: " << th02.ReadTemperature();
std::cout << " \t\t Humi: " << th02.ReadHumidity() << std::endl;
usleep(10000);
}
return 0;
}
| 52324c4885759e940c97d8e9d870d46857b01da0 | [
"Markdown",
"C++",
"Shell"
] | 4 | Shell | zieglermax/Grove_RPi_Lib | 2bb3fe81ed9c5e95a6fa45b06eb8e7af1c47b6f7 | b28249e1f29f048dedf85c7b953a0f7b42a47741 |
refs/heads/main | <file_sep>#Find targets
setwd('F:/<PASSWORD>')
source('InstantExam.R')
load('Combined2018PassingData.RData')
plays$targetReceiver = NA
for(i in 1:nrow(plays)){
plays[i,'targetReceiver'] = strsplit(strsplit(strsplit(toString(plays$playDescription[i]),' to ')[[1]][2],' ')[[1]][1],'[.]')[[1]][2]
}
#May also need to split by "intended for", for interceptions
#Seems to have failures also when there are penalties
head(plays)
findOffPlayers <- function(playNum,gameNum,data = allWeeksData){
firstFrameInfo = isolateFrame(1,playNum,gameNum)
skillOffPlayers = firstFrameInfo[firstFrameInfo$position %in% skillOffPos,'displayName']
return(as.character(skillOffPlayers))
}
plays$MatchedTargetReceiver = NA
for(i in 1:nrow(plays)){
# for(i in 1:10){
play = plays[i,]
thisGameId = play$gameId
ixGame = which(games$gameId == thisGameId)
weekNum = games$week[ixGame]
thisPlayId = play$playId
tarRec = play$targetReceiver
posTeam = play$possessionTeam
thisOffSet = findOffPlayers(thisPlayId,thisGameId)
ixMatch = which(grepl(tarRec,thisOffSet))
if(length(ixMatch) == 1) plays[i,'MatchedTargetReceiver'] = thisOffSet[ixMatch]
}
save(plays,file = 'UpdatedPlays.Rdata')
head(plays[is.na(plays$MatchedTargetReceiver),],50)
tail(plays[is.na(plays$MatchedTargetReceiver),],50)
<file_sep>#Random Plays ECA Plots at Throw
#Around 950 is where week 2 starts, so we stick to week 1 for ease of data plotting
playIx = sample(1:950,1)
for(j in playIx){
playNum = plays[j,'playId']
gameNum = plays[j,'gameId']
print(j)
playDesc = plays[j,'playDescription']
print(playDesc)
p = makeECAPlot_BallDest(playNum,gameNum)
show(p)
p = makeECAPlot_BallDest(playNum,gameNum,flipColors = T)
show(p)
}
<file_sep>#Attach play direction
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
load('Plays_Off_Def_Ball_Dist.Rdata')
trimmedPlays$PlayDirection = NA
oldWeek = 0
for(i in 1:nrow(trimmedPlays)){
play = trimmedPlays[i,'playId']; game = trimmedPlays[i,'gameId']
newWeek = findWeekNum(game)
if(newWeek != oldWeek) {
trackData = splitTrackingByWeek(newWeek)
routeOpts = levels(trackData$route)
playData = splitPlaysByWeek(newWeek)
}
if(i %% 200 == 1) print(paste(round(100*i/nrow(trimmedPlays),2),'% Complete',sep=''))
#Action
frame = isolateFrame(1,play,game,trackData)
trimmedPlays[i,'PlayDirection'] = levels(frame$playDirection)[frame$playDirection[1]]
oldWeek = newWeek
}
# save(trimmedPlays,file = 'Plays_Off_Def_Ball_Dist_Dir.Rdata')
<file_sep>#Find YAC
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
load('UpdatedPlays.Rdata')
w1Data = read.csv('week1.csv')
w1Plays = splitPlaysByWeek(1)
play = 75
game = 2018090600
findYAC <- function(playNum,gameNum,trackData = w1Data,playData = w1Plays){
thisPlay = findPlay(playNum,gameNum,playData)
if(thisPlay$passResult != 'C') {
print('incomplete or something')
return(NA)
}
else{
fa = findFrameAtArrival(playNum,gameNum,trackData)
if(any(is.na(fa$x))) return(NA)
los = thisPlay$absoluteYardlineNumber
totYards = thisPlay$playResult
ballCatcher = thisPlay$MatchedTargetReceiver
xCatch = fa[fa$displayName == ballCatcher,'x']
if(length(xCatch) == 0) return(NA)
if(fa$playDirection[1] == 'left'){
JasonWittenYards = los - xCatch
}
else{
JasonWittenYards = xCatch - los
}
return(totYards - JasonWittenYards)
}
}
findYAC(play,game,w1Data)
playsWithYAC = plays
playsWithYAC$YAC = NA
oldWeek = 0
for(i in 1:nrow(playsWithYAC)){
play = playsWithYAC[i,'playId']; game = playsWithYAC[i,'gameId']
newWeek = findWeekNum(game)
if(newWeek != oldWeek) {
trackData = splitTrackingByWeek(newWeek)
playData = splitPlaysByWeek(newWeek)
}
if(i %% 50 == 1) print(paste(round(100*i/nrow(playsWithYAC),2),'% Complete',sep=''))
if(!is.na(playsWithYAC[i,'MatchedTargetReceiver']) & (playsWithYAC[i,'passResult'] == 'C'))
playsWithYAC[i,'YAC'] = findYAC(play,game,trackData,playData)
oldWeek = newWeek
}
sum(!is.na(playsWithYAC$YAC) | (playsWithYAC$passResult != 'C'))
# sum(is.na(playsWithYAC[playsWithYAC$,'YAC']))
plays = playsWithYAC
# save(plays,file = 'Plays_Targets_YAC.Rdata')
plays$week = NA
for(i in 1:nrow(plays)){
plays[i,'week'] = findWeekNum(plays[i,'gameId'])
}
# save(plays,file = 'Plays_Week_Targets_YAC.Rdata')
#Weeks 4 and 14 seriously missing, but everything else seems fine, almost all missing are no play
for(i in 1:17) print(sum(is.na(plays[(plays$week == i) & (plays$passResult == 'C'),'YAC'])))
# print(plays[is.na(plays[(plays$week == 2) & (plays$passResult == 'C'),'YAC']),'playDescription'])
play4 = splitPlaysByWeek(4)
track4 = splitTrackingByWeek(4)
head(track4)
for(i in 1:nrow(play4)){
play = play4[i,'playId']; game = play4[i,'gameId']
if(i %% 50 == 1) print(paste(round(100*i/nrow(play4),2),'% Complete',sep=''))
if(!is.na(play4[i,'MatchedTargetReceiver']) & (play4[i,'passResult'] == 'C'))
play4[i,'YAC'] = findYAC(play,game,trackData,playData)
}
<file_sep>#Attach Target Loc, QB Name, and Throw Distance
setwd('F:/BigData<PASSWORD>21')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
load('Plays_Week_Targets_YAC_Route.Rdata')
plays$throwDistance = NA
plays$QB = NA
plays$Target_X = NA
plays$Target_Y = NA
plays$QB_X = NA
plays$QB_Y = NA
#Standard Loop through plays
oldWeek = 0
for(i in 1:nrow(plays)){
play = plays[i,'playId']; game = plays[i,'gameId']
newWeek = findWeekNum(game)
if(newWeek != oldWeek) {
trackData = splitTrackingByWeek(newWeek)
routeOpts = levels(trackData$route)
playData = splitPlaysByWeek(newWeek)
}
if(i %% 200 == 1) print(paste(round(100*i/nrow(plays),2),'% Complete',sep=''))
#Action
frame = findFrameAtPass(play,game,trackData)
qbName = frame[frame$position == 'QB','displayName']
targRec = plays[i,'MatchedTargetReceiver']
if(!is.na(targRec) & (any(frame$displayName == targRec))){
plays[i,'Target_X'] = frame[frame$displayName == targRec,'x']
plays[i,'Target_Y'] = frame[frame$displayName == targRec,'y']
}
if(length(qbName) == 1){
plays[i,'QB'] = as.character(qbName)
qb_x = frame[frame$position == 'QB','x']
qb_y = frame[frame$position == 'QB','y']
plays[i,'QB_X'] = qb_x
plays[i,'QB_Y'] = qb_y
if(is.na(plays[i,'QB'])) {
q = qbName
p = plays[i,]
f = frame
}
}
else{
qb_x = NA
qb_y = NA
}
dist = sqrt((plays[i,'Target_X'] - qb_x)^2 + (plays[i,'Target_Y'] - qb_y)^2)
if(!is.na(dist)) plays[i,'throwDistance'] = dist
oldWeek = newWeek
}
# save(plays,file = 'Plays_All_Offense.Rdata')
<file_sep>#Fix Trimmed Data
setwd('F:/BigDataBowl2021')
load('Plays_Off_Def_Ball_Dist_Dir.Rdata')
droppedFrames = subset(trimmedPlays,select = -c(defender1dir,defender2dir,defender3dir))
rightClass = droppedFrames
rightClass$defender1X = as.numeric(rightClass$defender1X)
rightClass$defender1Y = as.numeric(rightClass$defender1Y)
rightClass$defender1S = as.numeric(rightClass$defender1S)
rightClass$defender1Dir = as.numeric(rightClass$defender1Dir)
rightClass$defender1A = as.numeric(rightClass$defender1A)
rightClass$defender1O = as.numeric(rightClass$defender1O)
rightClass$defender1Dist = as.numeric(rightClass$defender1Dist)
rightClass$defender2X = as.numeric(rightClass$defender2X)
rightClass$defender2Y = as.numeric(rightClass$defender2Y)
rightClass$defender2S = as.numeric(rightClass$defender2S)
rightClass$defender2Dir = as.numeric(rightClass$defender2Dir)
rightClass$defender2A = as.numeric(rightClass$defender2A)
rightClass$defender2O = as.numeric(rightClass$defender2O)
rightClass$defender2Dist = as.numeric(rightClass$defender2Dist)
rightClass$defender3X = as.numeric(rightClass$defender3X)
rightClass$defender3Y = as.numeric(rightClass$defender3Y)
rightClass$defender3S = as.numeric(rightClass$defender3S)
rightClass$defender3Dir = as.numeric(rightClass$defender3Dir)
rightClass$defender3A = as.numeric(rightClass$defender3A)
rightClass$defender3O = as.numeric(rightClass$defender3O)
rightClass$defender3Dist = as.numeric(rightClass$defender3Dist)
# load('Plays_All_Offense.Rdata')
# p = plays[!is.na(plays$MatchedTargetReceiver) & !is.na(plays$throwDistance),]
# rightClass$QB_X = p$QB_X
# rightClass$QB_Y = p$QB_Y
#If the qb location is missing, its because it was dumped when attaching the defender and distances in the colstouse thing
#I added it in manually here. Hopefully were done with cleaning the data
playsToUse = rightClass
#Read above comment before using
# save(playsToUse,file='FinalPlays.Rdata')
<file_sep>#CombineData
setwd('F:/BigDataBowl2021')
w1Data = read.csv('week1.csv')
w2Data = read.csv('week2.csv')
w3Data = read.csv('week3.csv')
w4Data = read.csv('week4.csv')
w5Data = read.csv('week5.csv')
w6Data = read.csv('week6.csv')
w7Data = read.csv('week7.csv')
w8Data = read.csv('week8.csv')
w9Data = read.csv('week9.csv')
w10Data = read.csv('week10.csv')
w11Data = read.csv('week11.csv')
w12Data = read.csv('week12.csv')
w13Data = read.csv('week13.csv')
w14Data = read.csv('week14.csv')
w15Data = read.csv('week15.csv')
w16Data = read.csv('week16.csv')
w17Data = read.csv('week17.csv')
allWeeksData = rbind(w1Data,w2Data,w3Data,w4Data,
w5Data,w6Data,w7Data,w8Data,
w9Data,w10Data,w11Data,w12Data,
w13Data,w4Data,w15Data,w16Data,w17Data)
save(allWeeksData,file = 'Combined2018PassingData.RData')
rm(list = ls())
load('Combined2018PassingData.RData')
<file_sep>#Analyze Coverage
setwd('F:/BigDataBowl2021')
load('FinalPlays.Rdata')
load('CoverageData.Rdata')
source('InitialPlotting.R')
playerAnalysis = data.frame('DefenderName' = unique(coverageDf[!is.na(coverageDf$Def_Name),'Def_Name']))
playerAnalysis$NumberPlaysEnteredCoverage = NA
playerAnalysis$NumberComplete = NA
playerAnalysis$NumberIncomplete = NA
playerAnalysis$PercentComplete = NA
playerAnalysis$AverageYAC = NA
playerAnalysis$NumberINT = NA
playerAnalysis$NumberTD = NA
playerAnalysis$TotalYards = NA
playerAnalysis$Position = NA
for(i in 1:nrow(playerAnalysis)){
playsWithPlayer = coverageDf[coverageDf$Def_Name == playerAnalysis[i,'DefenderName'],]
playerAnalysis[i,'Position'] = playsWithPlayer[1,'Def_Pos']
playerAnalysis[i,'NumberPlaysEnteredCoverage'] = nrow(playsWithPlayer)
playerAnalysis[i,'NumberComplete'] = sum(playsWithPlayer$PassResult == 'C')
playerAnalysis[i,'NumberIncomplete'] = sum(playsWithPlayer$PassResult == 'I')
playerAnalysis[i,'NumberINT'] = sum(playsWithPlayer$PassResult == 'IN')
playerAnalysis[i,'NumberTD'] = sum(playsWithPlayer$TD)
playerAnalysis[i,'TotalYards'] = sum(playsWithPlayer$PlayResult)
playerAnalysis[i,'PercentComplete'] = playerAnalysis[i,'NumberComplete']/(playerAnalysis[i,'NumberIncomplete'] + playerAnalysis[i,'NumberComplete'])
playerAnalysis[i,'AverageYAC'] = mean(playsWithPlayer[!is.na(playsWithPlayer$YAC),'YAC'])
}
min10Df = playerAnalysis[playerAnalysis$NumberPlaysEnteredCoverage >= 10,]
min10Df[order(min10Df$PercentComplete,decreasing = F),]
min20Df = playerAnalysis[playerAnalysis$NumberPlaysEnteredCoverage >= 20,]
min20Df[order(min20Df$PercentComplete,decreasing = F),]
min20Df[order(min20Df$AverageYAC,decreasing = F),]
playerAnalysis[order(playerAnalysis$NumberPlaysEnteredCoverage,decreasing = T),]
plot(min20Df[,c('AverageYAC','PercentComplete')])
# text(min20Df$AverageYAC,min20Df$PercentComplete,min20Df$DefenderName)
text(min20Df$AverageYAC,min20Df$PercentComplete,min20Df$Position)
passRating <- function(NumAtts,NumComp,TotYards,TotTDs,TotINTs){
a = (NumComp/NumAtts - .3) * 5
b = (TotYards/NumAtts - 3) * .25
c = (TotTDs/NumAtts) * 20
d = 2.375 - (TotINTs/NumAtts) * 25
thresh = 2.375
a = ifelse(a>thresh,thresh,a)
b = ifelse(b>thresh,thresh,b)
c = ifelse(c>thresh,thresh,c)
d = ifelse(d>thresh,thresh,d)
return((a + b + c + d)/6 * 100)
}
min20Df$PasserRating = NA
for(i in 1:nrow(min20Df)){
min20Df[i,'PasserRating'] = passRating(NumAtts = min20Df[i,'NumberPlaysEnteredCoverage'],NumComp = min20Df[i,'NumberComplete'],TotYards = min20Df[i,'TotalYards'],
TotTDs = min20Df[i,'NumberTD'],TotINTs = min20Df[i,'NumberINT'])
}
min20Df[order(min20Df$PasserRating,decreasing = F),]
ECAT = min20Df[,c("DefenderName","NumberPlaysEnteredCoverage","PercentComplete","AverageYAC" , "Position" )]
colnames(ECAT) <- c('Defender Name','ECAT Plays','CMP%','YAC/p','Position')
save(ECAT,file = 'ECATData.Rdata')
<file_sep>#Attach ball destination
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
load('Plays_All_Offense_Defense_Ball.Rdata')
trimmedPlays$Dest_X = NA
trimmedPlays$Dest_Y = NA
oldWeek = 0
for(i in 1:nrow(trimmedPlays)){
play = trimmedPlays[i,'playId']; game = trimmedPlays[i,'gameId']
newWeek = findWeekNum(game)
if(newWeek != oldWeek) {
trackData = splitTrackingByWeek(newWeek)
routeOpts = levels(trackData$route)
playData = splitPlaysByWeek(newWeek)
}
if(i %% 200 == 1) print(paste(round(100*i/nrow(trimmedPlays),2),'% Complete',sep=''))
#Action
frame = findFrameAtArrival(play,game,trackData)
targRec = trimmedPlays[i,'MatchedTargetReceiver']
if(!is.na(targRec) & (any(frame$displayName == targRec))){
trimmedPlays[i,'Dest_X'] = frame[frame$displayName == targRec,'x']
trimmedPlays[i,'Dest_Y'] = frame[frame$displayName == targRec,'y']
}
oldWeek = newWeek
}
# save(trimmedPlays,file = 'Plays_Off_Def_Ball_Dist.Rdata')
<file_sep>#NFL Big Data Bowl
library(gganimate)
setwd('F:/BigDataBowl2021')
source('NFLFieldPlot.R')
games = read.csv('games.csv')
players = read.csv('players.csv')
plays = read.csv('plays.csv')
w1Data = read.csv('week1.csv')
# load('Combined2018PassingData.RData')
base = baseNFLField()
isolatePlay <- function(playNum,gameNum,data = allWeeksData){
playData = data[(data$playId == playNum) & (data$gameId == gameNum),]
return(playData)
}
isolateFrame <- function(frameNum,playNum,gameNum,data = allWeeksData){
playData = isolatePlay(playNum,gameNum,data)
frameData = playData[playData$frameId == frameNum,]
return(frameData)
}
findPlay <- function(playNum,gameNum,data = plays){
playInfo = data[(data$playId == playNum) & (data$gameId == gameNum),]
return(playInfo)
}
plotFrame <- function(frameNum,playNum,gameNum,data = allWeeksData,color = T){
#Plots a specific frame of a specific play
if(color){
base = baseNFLField()
}
else{
base = noColor_baseNFLField()
}
frameData = isolateFrame(frameNum,playNum,gameNum,data)
frameData[frameData$displayName == 'Football','jerseyNumber'] = 'FB'
playInfo = findPlay(playNum,gameNum)
if(frameData$playDirection[1] == 'right'){
LOS = playInfo$absoluteYardlineNumber
L2G = LOS + playInfo$yardsToGo
}
else{
LOS = playInfo$absoluteYardlineNumber
L2G = LOS - playInfo$yardsToGo
}
field.lines.df = data.frame(x = c(LOS,L2G),
ybot = rep(0.3,2),
ytop = rep(53,2))
framePlot <- base + geom_point(data = frameData,aes(x = x,y = y,col = team,size = 4)) +
geom_text(data = frameData,aes(x = x,y = y,size = 4,label = jerseyNumber)) +
geom_segment(data=field.lines.df,
aes(x=x,y=ybot,xend=x,yend=ytop,linetype='a'),
inherit.aes = F,
col=c('blue','yellow'))
return(framePlot)
}
# for(pl in unique(w1Data[w1Data$gameId == game,'playId'])){
# p = plotFrame(1,pl,game)
# plot(p)
# }
plotPlay <- function(playNum,gameNum,data = allWeeksData){
#Plots a specific play of a specific game
base = baseNFLField()
playData = isolatePlay(playNum,gameNum,data)
playInfo = findPlay(playNum,gameNum)
playData[playData$displayName == 'Football','jerseyNumber'] = 'FB'
if(playData$playDirection[1] == 'right'){
LOS = playInfo$absoluteYardlineNumber
L2G = LOS + playInfo$yardsToGo
}
else{
LOS = playInfo$absoluteYardlineNumber
L2G = LOS - playInfo$yardsToGo
}
field.lines.df = data.frame(x = c(LOS,L2G),
ybot = rep(0,2),
ytop = rep(53.3,2))
framePlot <- base + geom_point(data = playData,aes(x = x,y = y,col = team,size = 4)) +
geom_text(data = playData,aes(x = x,y = y,size = 4,label = jerseyNumber)) +
geom_segment(data=field.lines.df,
aes(x=x,y=ybot,xend=x,yend=ytop,linetype='a'),
inherit.aes = F,
col=c('blue','yellow')) +
transition_time(frameId) +
shadow_mark(alpha = .3,size = .5)
return(animate(framePlot,height = 700,width = 840))
}
#
# frame = 1
# play1 = 2845 #Okay
# play2 = 1425 #Pretty good
# play3 = 3784 #Pretty good
# play4 = 1737 #Good
# play5 = 877 # okay
# play6 = 2353 #Good
# play7 = 2312
# game = 2018090900
#
# plotFrame(20,play,game,w1Data)
#
# ap1 = findFrameAtPass(play1,game,w1Data,T)
# ap2 = findFrameAtPass(play2,game,w1Data,T)
# # ap2$plot
# ap3 = findFrameAtPass(play3,game,w1Data,T)
# # ap3$plot
# ap4 = findFrameAtPass(play4,game,w1Data,T)
# # ap4$plot
# ap5 = findFrameAtPass(play5,game,w1Data,T)
# # ap5$plot
# ap6 = findFrameAtPass(play6,game,w1Data,T)
# # ap6$plot
# ap7 = findFrameAtPass(play7,game,w1Data,T)
# # ap7$plot
#
# findPlay(play1,game)
# findPlay(play2,game)
# findPlay(play3,game)
# findPlay(play4,game)
# findPlay(play5,game)
# findPlay(play6,game)
# findPlay(play7,game)
#
# ap1$plot
# ap2$plot
# ap3$plot
# ap4$plot
# ap5$plot
# ap6$plot
# ap7$plot
#
#
#
# aa = findFrameAtArrival(play1,game,w1Data,T)
# aa$plot
#
# playRight = 320
# findPlay(play,game)
#
# frame1_146 = isolateFrame(1,146)
# plotFrame(frame,playRight,game)
#
#
# play146 = isolatePlay(146,game)
# unique(play146$frameId)
#
# plotPlay(play,game)
<file_sep>#Evaluation Time
setwd('F:/<PASSWORD>')
load('Plays_Week_Targets_YAC.Rdata')
YACPlays = plays[!is.na(plays$YAC),]
<file_sep>#Grid Field
# setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
source('FindAirDuration.R')
load('FinalPlays.Rdata')
xleft = 0; xright = 120; ybot = 0; ytop = 53.3
gridField <- function(QBLOC_X,playDir,givenMinX = NULL,givenMaxX = NULL){
if(is.null(givenMinX)){
if(playDir == 'left'){
xmin = ifelse(QBLOC_X-50<xleft,xleft,QBLOC_X-50); xmax = QBLOC_X
}
else{
xmax = ifelse(QBLOC_X+50>xright,xright,QBLOC_X+50); xmin = QBLOC_X
}
}
else{
xmin = givenMinX; xmax = givenMaxX
}
xSeq = seq(xmin,xmax,length.out = ceiling((xmax-xmin)/1.75))
ySeq = seq(ybot,ytop,length.out = 30)
gridDf = data.frame()
for(yi in ySeq){
gridDf <- rbind(gridDf,data.frame(xPts = xSeq,yPts = yi))
}
# plotBase = baseNFLField()
# plotBase <- plotBase + geom_point(data = gridDf,aes(x = xPts,y = yPts))
# print(plotBase)
return(gridDf)
}
# a = gridField(45,'right')
distToGrid <- function(QB_X,QB_Y,playDir,givenMinX = NULL,givenMaxX = NULL){
griddedField = gridField(QB_X,playDir,givenMinX,givenMaxX)
griddedField$DistToQB = round(sqrt((QB_X - griddedField$xPts)^2 + (QB_Y - griddedField$yPts)^2),1)
# plotBase = baseNFLField()
# plotBase <- plotBase + geom_label(data = griddedField,aes(x = xPts,y = yPts,label = DistToQB))
# print(plotBase)
return(griddedField)
}
airDurToGrid <- function(QB_X,QB_Y,playDir,medOnly = F,givenGrid = NA){
if(is.na(givenGrid)) gridDur = distToGrid(QB_X,QB_Y,playDir,givenMinX,givenMaxX)
else gridDur = givenGrid
if(medOnly){
gridDur[,'50%'] = NA
for(i in 1:nrow(gridDur)) {
gridDur[i,'50%'] = findAirDuration(gridDur[i,'DistToQB'],medOnly = T)
}
}
else{
gridDur[,c('5%','10%','25%','50%','75%','90%','95%')] = NA
for(i in 1:nrow(gridDur)) {
# print(gridDur[i,'DistToQB'])
gridDur[i,c('5%','10%','25%','50%','75%','90%','95%')] = findAirDuration(gridDur[i,'DistToQB'])
}
}
return(gridDur)
}
# a = distToGrid(45,26,'right')
# aGrid = airDurToGrid(5,26,'left')
# plot(aGrid$DistToQB,aGrid$`95%`,lty = 2)
# points(aGrid$DistToQB,aGrid$`5%`,lty = 2,col='red')
#Source https://www.reddit.com/r/GlobalOffensive/comments/90ztdc/player_reaction_times_relative_to_major_sports/
t_react = .309
maxSpeed = quantile(w1Data[w1Data$displayName != 'Football','s'],.99)
projectFuture <- function(player_x,player_y,vel_x,vel_y,dest_x,dest_y,timeToArrive){
#Returns true if the player could reasonable reach the destination location in the specified time given the
#current location and speed
#Assumes if you're within 1 foot of destination than you've gotten there
if(timeToArrive <= t_react){
#not enough time to react, better hope its on path
futureLoc_x = player_x + timeToArrive * vel_x
futureLoc_y = player_y + timeToArrive * vel_y
finalDist = sqrt((futureLoc_x - dest_x)^2 + (futureLoc_y - dest_y)^2)
if(finalDist < 1) return(TRUE)
else return(FALSE)
}
else{
reactLoc_x = player_x + t_react * vel_x
reactLoc_y = player_y + t_react * vel_y
timeRespond = timeToArrive - t_react
distRespond = sqrt((reactLoc_x - dest_x)^2 + (reactLoc_y - dest_y)^2)
speedNeedRespond = distRespond/timeRespond
if(speedNeedRespond < maxSpeed) return(TRUE)
else return(FALSE)
}
}
findCoverage <- function(player_x,player_y,vel_x,vel_y,qb_x,qb_y,playDir,givenGrid = NA){
player_x = player_x #+ 10
qb_x = qb_x #+ 10
gridVals = airDurToGrid(qb_x,qb_y,playDir,givenGrid = givenGrid)
gridCover = gridVals[,c('xPts','yPts','5%','10%','25%','50%','75%','90%','95%')]
# gridCover[,c('LowRange','MidRange','HighRange')] = NA
gridCover$CoveragePercentage = NA
# percentCheck = c('5%','10%','25%','50%','75%','90%','95%')
percentCheck = c('5%','25%','50%','75%','95%')
# percentCover = c(.95,.9,.75,.5,.25,.1,.05)
percentCover = c(.95,.75,.5,.25,.05)
for(i in 1:nrow(gridCover)){
j = 1
while(is.na(gridCover[i,'CoveragePercentage']) & j <= 5){
if(projectFuture(player_x,player_y,vel_x,vel_y,gridCover[i,'xPts'],gridCover[i,'yPts'],gridCover[i,percentCheck[j]]))
gridCover[i,'CoveragePercentage'] = percentCover[j]
else j = j + 1
}
if(is.na(gridCover[i,'CoveragePercentage'])) gridCover[i,'CoveragePercentage'] = 0
# gridCover[i,c('LowRange','MidRange','HighRange')] =
# c(projectFuture(player_x,player_y,vel_x,vel_y,gridCover[i,'xPts'],gridCover[i,'yPts'],gridCover[i,'5%']),
# projectFuture(player_x,player_y,vel_x,vel_y,gridCover[i,'xPts'],gridCover[i,'yPts'],gridCover[i,'50%']),
# projectFuture(player_x,player_y,vel_x,vel_y,gridCover[i,'xPts'],gridCover[i,'yPts'],gridCover[i,'95%']))
}
plotBase = baseNFLField()
plotBase <- plotBase + stat_contour(data = gridCover,aes(x = xPts,y = yPts,z = CoveragePercentage),binwidth = .2)
plotBase <- plotBase + geom_point(inherit.aes = F,data = data.frame(xp = c(qb_x,player_x),yp = c(qb_y,player_y)),aes(x=xp,y=yp,col=c('red','blue')))
# return(plotBase)
return(gridCover)
}
# projectFuture(0,0,1,1,2,2,.55)
# findCoverage(p$defender1X,p$defender1Y,p$defender1S * sin(p$defender1Dir * pi / 180),p$defender1S * cos(p$defender1Dir * pi / 180),p$QB_X,p$QB_Y,p$PlayDirection)
# findCoverage(p$defender2X,p$defender2Y,p$defender2S * sin(p$defender2Dir * pi / 180),p$defender2S * cos(p$defender2Dir * pi / 180),p$QB_X,p$QB_Y,p$PlayDirection)
# findCoverage(p$defender3X,p$defender3Y,p$defender3S * sin(p$defender3Dir * pi / 180),p$defender3S * cos(p$defender3Dir * pi / 180),p$QB_X,p$QB_Y,p$PlayDirection)
# findCoverage(r$defender1X,r$defender1Y,r$defender1S * sin(r$defender1Dir * pi / 180),r$defender1S * cos(r$defender1Dir * pi / 180),r$QB_X,r$QB_Y,r$PlayDirection)
# findCoverage(20,25,0,10,25,25,'left')
findMedianCoverageHull <- function(player_x,player_y,vel_x,vel_y,qb_x,qb_y,playDir,givenMinX = NULL,givenMaxX = NULL){
player_x = player_x + 10
qb_x = qb_x + 10
# print(paste(player_x,player_y,vel_x,vel_y,qb_x,qb_y,playDir))
gridVals = airDurToGrid(qb_x,qb_y,playDir,medOnly=T,givenMinX = givenMinX,givenMaxX = givenMaxX)
gridCover = gridVals[,c('xPts','yPts','50%')]
gridCover$CoveredBool = NA
# print(gridCover)
for(i in 1:nrow(gridCover)){
gridCover[i,c('CoveredBool')] =
projectFuture(player_x,player_y,vel_x,vel_y,gridCover[i,'xPts'],gridCover[i,'yPts'],gridCover[i,'50%'])
}
# print(gridCover$CoveredBool)
trueSpots = gridCover[gridCover$CoveredBool == T,c('xPts','yPts')]
hullIx = chull(trueSpots$xPts,trueSpots$yPts)
return(trueSpots[hullIx,])
# return(trueSpots)
}
# findMedianCoverageHull(p$defender1X,p$defender1Y,p$defender1S * sin(p$defender1Dir * pi / 180),p$defender1S * cos(p$defender1Dir * pi / 180),p$QB_X,p$QB_Y,p$PlayDirection)
# findMedianCoverageHull(p$defender2X,p$defender2Y,p$defender2S * sin(p$defender2Dir * pi / 180),p$defender2S * cos(p$defender2Dir * pi / 180),p$QB_X,p$QB_Y,p$PlayDirection)
# findMedianCoverageHull(p$defender3X,p$defender3Y,p$defender3S * sin(p$defender3Dir * pi / 180),p$defender3S * cos(p$defender3Dir * pi / 180),p$QB_X,p$QB_Y,p$PlayDirection)
# findMedianCoverageHull(r$defender1X,r$defender1Y,r$defender1S * sin(r$defender1Dir * pi / 180),r$defender1S * cos(r$defender1Dir * pi / 180),r$QB_X,r$QB_Y,r$PlayDirection)
# aAll = findMedianCoverageHull(20,25,0,10,25,25,'left')
# findMedianCoverageHull()
plotCoverageHulls <- function(defenderData,allData,givenMinX = NULL,givenMaxX = NULL){
qbx = allData[allData$position == 'QB','x']
qby = allData[allData$position == 'QB','y']
fieldGridDf = distToGrid(qbx,qby,defenderData[1,'playDirection'],givenMinX,givenMaxX)
for(i in 1:nrow(defenderData)){
p = defenderData[i,]
a = findCoverage(p$x,p$y,p$s * sin(p$dir * pi / 180),p$s * cos(p$dir * pi / 180),qbx,qby,p$playDirection,givenMinX,givenMaxX)
# print(a)
# print(p$displayName)
fieldGridDf[,as.character(p$displayName)] = a$CoveragePercentage
# print(a)
# print(fieldGridDf)
}
return(fieldGridDf)
}
# fullHullDf3 = plotCoverageHulls(ap3$defInfo,ap3$allInfo)
#
# fullHullDf3$SumCol = rowSums(fullHullDf3[,4:ncol(fullHullDf3)])
# fullHullDf3$SumCol = fullHullDf3$SumCol/(ncol(fullHullDf3) - 3)
#
# fullHullPlot3 <- ggplot(data = fullHullDf3) +
# geom_contour_filled(aes(x = xPts,y = yPts,z = SumCol),binwidth = .05) +
# geom_point(data = ap3$allInfo,aes(x = x,y = y, colour = team,size = 2)) +
# geom_segment(data = ap3$allInfo,
# aes(x = x,y = y, xend = x + s * sin(dir * pi / 180), yend = y + s * cos(dir * pi / 180),colour = team),
# arrow = arrow(length = unit(.4,"cm"))) +
# theme(legend.position = 'none') + labs(x = '',y = '') +
# geom_point(data = aa3$allInfo[aa3$allInfo$team == 'football',], aes(x=x, y = y),colour = 'burlywood4',size = 5)
# fullHullPlot3
#
# fullHullDf2 = plotCoverageHulls(ap2$defInfo,ap2$allInfo)
#
# fullHullDf2$SumCol = rowSums(fullHullDf2[,4:ncol(fullHullDf2)])
# fullHullDf2$SumCol = fullHullDf2$SumCol/(ncol(fullHullDf2) - 3)
#
# fullHullPlot2 <- ggplot(data = fullHullDf2) +
# geom_contour_filled(aes(x = xPts,y = yPts,z = SumCol),binwidth = .05) +
# geom_point(data = ap2$allInfo,aes(x = x,y = y, colour = team,size = 2)) +
# geom_segment(data = ap2$allInfo,
# aes(x = x,y = y, xend = x + s * sin(dir * pi / 180), yend = y + s * cos(dir * pi / 180),colour = team),
# arrow = arrow(length = unit(.4,"cm"))) +
# theme(legend.position = 'none') + labs(x = '',y = '') +
# geom_point(data = ap2$allInfo[ap2$allInfo$team == 'football',], aes(x=x, y = y),colour = 'burlywood4',size = 5)
# fullHullPlot2
#
# grid.arrange(fullHullPlot2,fullHullPlot3)
<file_sep>setwd('F:/BigDataBowl2021')
targetReceivers = read.csv('targetedReceiver.csv')
playsOrig = read.csv('plays.csv')
games = read.csv('games.csv')
players = read.csv('players.csv')
players$targetNflId = players$nflId
load('Plays_Week_Targets_YAC_Route.Rdata')
targetsWithName = merge(targetReceivers,players[,c('displayName','targetNflId')],by = 'targetNflId')
playsOrig
<file_sep>#Coverages Data
cov1 = read.csv('coverages_week1.csv')
cov1$YdsResult = NA
cov1$PassResult = NA
for(i in 1:nrow(cov1)){
play = cov1[i,'playId']
game = cov1[i,'gameId']
fp = findPlay(play,game)
if(nrow(fp)> 0){
cov1[i,'YdsResult'] = fp$playResult
cov1[i,'PassResult'] = levels(fp$passResult)[fp$passResult]
}
}
cov1[(cov1$coverage == 'Cover 2 Zone') & (cov1$PassResult == 'I'),]
#This one is pretty good, has two defenders covering the same guy, but not really covering him
#https://gamepass.nfl.com/game/buccaneers-at-saints-on-09092018?coach=true
#TB/NO Q4 4:22
play2 = 4173
game2 = 2018090906
p2 = findFrameAtPass(play2,game2,w1Data,T)
p2$plot
ap2 = findFrameAtPass(play2,game2,w1Data,T)
ap2$plot
aa2 = findFrameAtArrival(play2,game2,w1Data,T)
aa2$plot
#This might be the one
#https://gamepass.nfl.com/game/texans-at-patriots-on-09092018?coach=true
#HOU/NE Q2 7:23
play3 = 1533
game3 = 2018090905
p3 = findFrameAtPass(play3,game3,w1Data,T)
p3$plot
ap3 = findFrameAtPass(play3,game3,w1Data,T)
ap3$plot
aa3 = findFrameAtArrival(play3,game3,w1Data,T)
aa3$plot
grid.arrange(p2$plot,p3$plot)
grid.arrange(ap2$plot,ap3$plot)
grid.arrange(aa2$plot,aa3$plot)
# #Decent followup
# play3 = 1927
# game3 = 2018090906
# ap3 = findFrameAtPass(play3,game3,w1Data,T)
# ap3$plot
# aa3 = findFrameAtArrival(play3,game3,w1Data,T)
# aa3$plot
#Decent option, post play stopped
# play3 = 2715
# game3 = 2018091001
# ap3 = findFrameAtPass(play3,game3,w1Data,T)
# ap3$plot
# aa3 = findFrameAtArrival(play3,game3,w1Data,T)
# aa3$plot
# play3 = 1555
# game3 = 2018090912
# ap3 = findFrameAtPass(play3,game3,w1Data,T)
# ap3$plot
# aa3 = findFrameAtArrival(play3,game3,w1Data,T)
# aa3$plot<file_sep>#Simulate Motion
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
source('FindAirDuration.R')
load('FinalPlays.Rdata')
accelerationPopulation = w1Data[w1Data$a < 10,'a']
simulateMotion <- function(curX,curY,curS,curDir,timeToArrive,destX,destY){
numFrames = timeToArrive*10 + 1
playerx = rep(NA,numFrames)
playery = rep(NA,numFrames)
playerVx = rep(NA,numFrames)
playerVy = rep(NA,numFrames)
playerAx = rep(NA,numFrames)
playerAy = rep(NA,numFrames)
adir = rep(NA,numFrames)
times = seq(0,timeToArrive,by = .1)
playerx[1] = curX
playery[1] = curY
playerVx[1] = curS * sin(curDir * pi/180)
playerVy[1] = curS * cos(curDir * pi/180)
a_mag_1 = sample(accelerationPopulation,1)
a_dir_1 = atan((destX - curX)/(destY - curY))
playerAx[1] = a_mag_1 * cos(a_dir_1)
playerAy[1] = a_mag_1 * sin(a_dir_1)
adir[1] = a_dir_1 * 180 / pi
for(i in 2:numFrames){
playerx[i] = playerx[i-1] + playerVx[i-1] * .1
playery[i] = playery[i-1] + playerVy[i-1] * .1
playerVx[i] = playerVx[i-1] + playerAx[i-1] * .1
playerVy[i] = playerVy[i-1] + playerAy[i-1] * .1
a_mag = sample(accelerationPopulation,1)
# print(paste(playerx[i-1],playery[i-1]))
a_dir= atan((destX - playerx[i-1])/(destY - playery[i-1])) +
ifelse(((destX - playerx[i-1]) < 0) & ((destY - playery[i-1]) < 0),-pi,
ifelse(((destX - playerx[i-1]) < 0) & ((destY - playery[i-1]) > 0),pi,0))
# print(a_dir * 180 / pi)
adir[i] = a_dir * 180 / pi
playerAx[i] = a_mag * cos(a_dir)
playerAy[i] = a_mag * sin(a_dir)
}
moveDf = data.frame(x = playerx, y = playery,t = times,angle = adir)
destDf = data.frame(x = destX,y = destY,t = times)
actualLocPlot <- ggplot() + geom_label(data = moveDf,aes(x = x,y = y,label = angle)) +
geom_point(data = destDf,aes(x=x,y=y)) +
transition_time(t) +
shadow_mark(alpha = .3,size = .5)
return(animate(actualLocPlot,height = 700,width = 840))
}
a = simulateMotion(0,0,1,-120,10,10,10)
a
<file_sep>#Assign Defender
setwd('F:/BigDataBowl2021')
# setwd("~/Documents/BigDataBowl2020-main")
source('InitialPlotting.R')
defPos = c('CB','SS','FS','DB','S','MLB','LB','OLB','ILB','DL','NT','DE')
skillOffPos = c('WR','RB','TE','FB','HB')
# play = 75
# game = 2018090600
# playInfo = findPlay(play,game)
# playData = isolatePlay(play,game)
assignDefenders <- function(playNum,gameNum,data = allWeeksData){
playData = isolatePlay(playNum,gameNum,data)
playUpdate = playData
playUpdate$PlayerDefending = NA
playUpdate$DistToDefPlayer = NA
playUpdate$DefendingPlayer_x = NA
playUpdate$DefendingPlayer_y = NA
lastFrame = max(playData$frameId)
numRowsFirstFrame = nrow(isolateFrame(1,playNum,gameNum,data))
firstFrameInfo = isolateFrame(1,playNum,gameNum,data)
defPlayers = firstFrameInfo[firstFrameInfo$position %in% defPos,'displayName']
skillOffPlayers = firstFrameInfo[firstFrameInfo$position %in% skillOffPos,'displayName']
# print(defPlayers)
# print(skillOffPlayers)
for(frame in 1:lastFrame){
frameData = isolateFrame(frame,playNum,gameNum,data)
# print(frameData)
if(nrow(frameData) == numRowsFirstFrame){
offPlayerLocs = frameData[!is.na(match(frameData$displayName,skillOffPlayers)),c('x','y')]
for(playerName in defPlayers){
if(playerName %in% frameData$displayName){
curPlayerLoc = c(frameData[frameData$displayName == playerName,'x'],frameData[frameData$displayName == playerName,'y'])
playerDists = rep(NA,nrow(offPlayerLocs))
for(row in 1:nrow(offPlayerLocs)){
playerDists[row] = sqrt(sum((curPlayerLoc - offPlayerLocs[row,])^2))
}
closeIx = which(playerDists == min(playerDists))
if(sum((playUpdate$displayName == levels(skillOffPlayers)[skillOffPlayers[closeIx]]) & (playUpdate$frameId == frame)) == 1){
playUpdate[(playUpdate$displayName == playerName) & (playUpdate$frameId == frame),
c('PlayerDefending','DistToDefPlayer','DefendingPlayer_x','DefendingPlayer_y')] =
c(levels(skillOffPlayers)[skillOffPlayers[closeIx]],playerDists[closeIx],
playUpdate[(playUpdate$displayName == levels(skillOffPlayers)[skillOffPlayers[closeIx]]) & (playUpdate$frameId == frame),c('x','y')])
}
else{
playUpdate[(playUpdate$displayName == playerName) & (playUpdate$frameId == frame),
c('PlayerDefending','DistToDefPlayer')] =
c(levels(skillOffPlayers)[skillOffPlayers[closeIx]],playerDists[closeIx])
}
}
}
}
}
return(playUpdate[!is.na(playUpdate$PlayerDefending),])
}
# assignDefenders(play,game,trackData)
plotPlayWithDefenders <- function(playNum,gameNum,data = allWeeksData){
#Plots a specific play of a specific game
base = baseNFLField()
playData = isolatePlay(playNum,gameNum,data)
defData = assignDefenders(playNum,gameNum,data)
playInfo = findPlay(playNum,gameNum,data)
playData[playData$displayName == 'Football','jerseyNumber'] = 'FB'
if(playData$playDirection[1] == 'right'){
LOS = playInfo$absoluteYardlineNumber
L2G = LOS + playInfo$yardsToGo
}
else{
LOS = playInfo$absoluteYardlineNumber
L2G = LOS - playInfo$yardsToGo
}
field.lines.df = data.frame(x = c(LOS,L2G),
ybot = rep(0.3,2),
ytop = rep(53,2))
framePlot <- base + geom_point(data = playData,aes(x = x,y = y,col = team,size = 4)) +
geom_text(data = playData,aes(x = x,y = y,size = 4,label = jerseyNumber)) +
geom_segment(data=field.lines.df,
aes(x=x,y=ybot,xend=x,yend=ytop,linetype='a'),
inherit.aes = F,
col=c('blue','yellow')) +
transition_time(frameId) +
geom_segment(data = defData,aes(x = x,y = y,xend = DefendingPlayer_x,yend = DefendingPlayer_y))
return(animate(framePlot,height = 700,width = 840))
}
# plotPlayWithDefenders(play,game)
<file_sep>#Plot at Throw
library(gridExtra)
setwd('F:/BigDataBowl2021')
source('AssignDefender.R')
play = 75
game = 2018090600
findFrameAtPass <- function(playNum,gameNum,data = w1Data,plotOn = F,returnAllRes = F,assignDef = F){
playData = isolatePlay(playNum,gameNum,data)
if(plotOn) returnAllRes = T
if(returnAllRes) assignDef = T
if(assignDef) defData = assignDefenders(playNum,gameNum,data)
frameThrow = playData[(playData$event == 'pass_forward') | (playData$event == 'pass_shovel'),'frameId'][1]
if(plotOn){
p = plotFrame(frameThrow,playNum,gameNum,data)
p = p +
# geom_segment(data = defData[(defData$frameId == frameThrow),],
# aes(x = x,y = y,xend = DefendingPlayer_x,yend = DefendingPlayer_y)) +
geom_segment(data = isolateFrame(frameThrow,playNum,gameNum,data),
aes(x = x,y = y, xend = x + s * sin(dir * pi / 180), yend = y + s * cos(dir * pi / 180),colour = team),
arrow = arrow(length = unit(.4,"cm")))
}
else{
p = 'pineapple'
}
if(returnAllRes){
return(list(plot = p,
defInfo = defData[(defData$frameId == frameThrow),],
allInfo = playData[(playData$frameId == frameThrow),]))
}
else{
if(assignDef) return(defInfo = defData[(defData$frameId == frameThrow),])
else return(playData[(playData$frameId == frameThrow),])
}
}
# findFrameAtPass(play,game)
findFrameAtArrival <- function(playNum,gameNum,data = w1Data,plotOn = F,returnAllRes = F,assignDef = F){
playData = isolatePlay(playNum,gameNum,data)
if(plotOn) returnAllRes = T
if(returnAllRes) assignDef = T
if(assignDef) defData = assignDefenders(playNum,gameNum,data)
if(any((playData$event == 'pass_arrived') | (playData$event == 'pass_outcome_caught') |
(playData$event == 'pass_outcome_incomplete') |
(playData$event == 'pass_outcome_interception') |
(playData$event == 'pass_outcome_touchdown'))){
frameThrow = playData[(playData$event == 'pass_arrived') | (playData$event == 'pass_outcome_caught') |
(playData$event == 'pass_outcome_incomplete') |
(playData$event == 'pass_outcome_interception') |
(playData$event == 'pass_outcome_touchdown'),'frameId'][1]
}
else return(data.frame(info = F,displayName = F))
if(any(is.na(playData[playData$frameId == frameThrow,'x']))){
frameThrow = playData[(playData$event == 'first_contact'),'frameId'][1]
}
if(plotOn){
p = plotFrame(frameThrow,playNum,gameNum,data)
p = p +
# geom_segment(data = defData[(defData$frameId == frameThrow),],
# aes(x = x,y = y,xend = DefendingPlayer_x,yend = DefendingPlayer_y)) +
geom_segment(data = isolateFrame(frameThrow,playNum,gameNum,data),
aes(x = x,y = y, xend = x + s * sin(dir * pi / 180), yend = y + s * cos(dir * pi / 180),colour = team),
arrow = arrow(length = unit(.4,"cm")))
}
else{
p = 'pineapple'
}
if(returnAllRes){
return(list(plot = p,
defInfo = defData[(defData$frameId == frameThrow),],
allInfo = playData[(playData$frameId == frameThrow),]))
}
else{
return(playData[(playData$frameId == frameThrow),])
}
}
# findFrameAtArrival(play,game)
sideBySidePassPlot <- function(playNum,gameNum,data = w1Data){
list_throw = findFrameAtPass(playNum,gameNum,data,plotOn = T)
list_arrive = findFrameAtArrival(playNum,gameNum,data,plotOn = T)
grid.arrange(list_throw$plot,list_arrive$plot)
}
# sideBySidePassPlot(play,game)
<file_sep>#Make ECA Plots
library(metR)
library(transformr)
library(gganimate)
library(ggplot2)
setwd('F:/BigDataBowl2021')
source('AssignDefender.R')
source('GridField.R')
options(warn = -1)
addNFLField <- function(oldPlot){
ytop = 53.3
ybot = 0
field.lines <- data.frame(x1 = c(0,0,0,120,110,10),
x2 = c(120,120,0,120,110,10),
y1 = c(ybot,ytop,ytop,ytop,ytop,ytop),
y2 = c(ybot,ytop,ybot,ybot,ybot,ybot))
ids = factor(c('endDef','fieldPlay','endOff'))
values <- data.frame(
id = ids,
color = c('white','white','white')
)
field.shape <- data.frame(id = unlist(matrix(t(matrix(rep(ids,4),nrow=3)),nrow=1)[1,]),
xg = c(0,0,10,10,10,10,110,110,110,110,120,120),
yg = c(ybot,ytop,ytop,ybot,ybot,ytop,ytop,ybot,ybot,ytop,ytop,ybot))
datapoly <- merge(values, field.shape, by = c("id"))
fieldLines <- geom_segment(data=field.lines,aes(x=x1,y=y1,xend=x2,yend=y2,
linetype='a'),colour='white',
size = c(2,2,2,2,1,1))
minor.lines.df <- data.frame(xvals = seq(15,105,length.out = 19),
ybot = rep(ybot,19),
ytop = rep(ytop,19))
minor.field.lines <- geom_segment(data = minor.lines.df,aes(x = xvals,y = ybot,xend = xvals,yend = ytop),colour = 'white')
hash.marks.df <- data.frame(xvals = rep(11:109,4),
ybot = c(rep(ybot + 1/3,99),rep(22.91,99),rep(29.73,99),rep(ytop - 1,99)),
ytop = c(rep(ybot + 1 ,99),rep(23.57,99),rep(30.39,99),rep(ytop - 1/3,99)))
hash.marks <- geom_segment(data = hash.marks.df,aes(x = xvals,y = ybot,xend = xvals, yend = ytop),colour = 'white')
field.numbers.bot.df <- data.frame(textVals = unlist(lapply(c(1,0,2,0,3,0,4,0,5,0,4,0,3,0,2,0,1,0),toString)),
#x_text = c(8,12,18,22,28,32,38,42,48,52,58,62,68,72,78,82,88,92),
x_text = c(8.5,11.5,18.5,21.5,28.5,31.5,38.5,41.5,48.5,51.5,58.5,61.5,68.5,71.5,78.5,81.5,88.5,91.5)+10,
y_text = rep(ybot + 9,18))
show.bot.numbers <- geom_text(data=field.numbers.bot.df, aes(x = x_text, y = y_text, label = textVals),
size = 6,col='white',family = ifelse('Century' %in% fonts(),windowsFont('Century'),'Impact'))
field.numbers.top.df <- data.frame(textVals = unlist(lapply(c(0,1,0,2,0,3,0,4,0,5,0,4,0,3,0,2,0,1),toString)),
#x_text = c(8,12,18,22,28,32,38,42,48,52,58,62,68,72,78,82,88,92),
x_text = c(8.5,11.5,18.5,21.5,28.5,31.5,38.5,41.5,48.5,51.5,58.5,61.5,68.5,71.5,78.5,81.5,88.5,91.5)+10,
y_text = rep(ytop - 9,18))
show.top.numbers <- geom_text(data=field.numbers.top.df, aes(x = x_text, y = y_text, label = textVals),
size = 6,col='white',family = ifelse('Century' %in% fonts(),windowsFont('Century'),'Impact'),angle = 180)
left.endzone.df <- data.frame(textVals = 'T E A M', x_left = 5, y_left = ytop/2)
show.left.endzone <- geom_text(data = left.endzone.df, aes(x = x_left, y = y_left,label = textVals),
size = 10, col = 'white', family = ifelse('Copperplate Gothic Bold' %in% fonts(),windowsFont('Copperplate Gothic Bold'),'Georgia'),angle = 90)
right.endzone.df <- data.frame(textVals = 'T E A M', x_right = 115, y_right = ytop/2)
show.right.endzone <- geom_text(data = right.endzone.df, aes(x = x_right, y = y_right,label = textVals),
size = 10, col = 'white', family = ifelse('Copperplate Gothic Bold' %in% fonts(),windowsFont('Copperplate Gothic Bold'),'Georgia'),angle = -90)
big_box <- data.frame(x_big_box_s = c(-1,-1,-1,121),
x_big_box_e = c(121,121,-1,121),
y_big_box_s = c(ytop+.25,ybot-.2,ybot-.2,ybot-.2),
y_big_box_e = c(ytop+.25,ybot-.2,ytop+.25,ytop+.25))
baseNFL <- oldPlot +
# geom_polygon(data = datapoly,aes(group = id)) +
# scale_fill_identity() +
labs(x='',y='') +
minor.field.lines +
hash.marks +
show.bot.numbers + show.top.numbers +
show.left.endzone + show.right.endzone +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank(),
legend.position = 'none') +
fieldLines +
geom_segment(data=big_box,aes(x=x_big_box_s,y=y_big_box_s,xend=x_big_box_e,yend=y_big_box_e),colour='black')
baseNFL$layers <- c(geom_polygon(data = datapoly,aes(x = xg,y = yg),fill = 'black'), baseNFL$layers)
return(baseNFL)
}
ECA_Contour <- function(fieldContours,moveData,flipColors = F){
p <- ggplot(data = fieldContours) +
geom_contour_fill(data = fieldContours,aes(x = xPts,y = yPts,z = SumCol),breaks = seq(0,.7,length.out = 31)) +
scale_fill_divergent(midpoint = .25) +
geom_segment(data = moveData,
aes(x = x,y = y, xend = x + s * sin(dir * pi / 180), yend = y + s * cos(dir * pi / 180),colour = team),
arrow = arrow(length = unit(.4,"cm"))) +
geom_point(data = moveData,aes(x = x,y = y, colour = team,size = 2)) +
labs(x = '',y = '')
if(flipColors){
p = p + scale_color_manual(values = c('#619CFF','#00BA38','#F8766D'))
}
else{
p = p + scale_color_manual(values = c('#F8766D','#00BA38','#619CFF'))
}
return(p)
}
fullECAPlot_frame <- function(contourPlot){
return(addNFLField(contourPlot))
}
findECAData <- function(frameNum,playNum,gameNum,data = w1Data,givenMinX = NULL,givenMaxX = NULL){
frameToUse = isolateFrame(frameNum,playNum,gameNum,data)
defData = assignDefenders(playNum,gameNum,data)
# allInfo = playData[(playData$frameId == frameThrow),]
defFrame = defData[defData$frameId == frameNum,]
qbx = frameToUse[frameToUse$position == 'QB','x']
qby = frameToUse[frameToUse$position == 'QB','y']
fieldGridDf = distToGrid(qbx,qby,defData[1,'playDirection'],givenMinX,givenMaxX)
# print(paste(givenMinX,givenMaxX))
for(i in 1:nrow(defFrame)){
oneDefender = defFrame[i,]
covArea = findCoverage(oneDefender$x,oneDefender$y,oneDefender$s * sin(oneDefender$dir * pi / 180),
oneDefender$s * cos(oneDefender$dir * pi / 180),qbx,qby,oneDefender$playDirection,givenGrid = fieldGridDf[,1:3])
fieldGridDf[,as.character(oneDefender$displayName)] = covArea$CoveragePercentage
}
fieldGridDf$SumCol = rowSums(fieldGridDf[,4:ncol(fieldGridDf)])
fieldGridDf$SumCol = fieldGridDf$SumCol/(ncol(fieldGridDf) - 3)
return(list('ContourData' = fieldGridDf,'MovementData' = frameToUse))
}
makeECAPlot_Frame <- function(frameNum,playNum,gameNum,data = w1Data,givenMinX = NULL,givenMaxX = NULL,flipColors = F){
eca_data = findECAData(frameNum,playNum,gameNum,data = w1Data,givenMinX = givenMinX,givenMaxX = givenMaxX)
contPlot = ECA_Contour(eca_data$ContourData,eca_data$MovementData,flipColors = flipColors)
return(fullECAPlot_frame(contPlot))
}
addMovingPieces <- function(contourDf,movementDf){
contourDf$frame <- as.integer(contourDf$frame)
contourPlot <- ggplot() +
geom_contour_fill(data = contourDf,aes(x = xPts,y = yPts,z = SumCol,group = frame),breaks = seq(0,.7,length.out = 31)) +
scale_fill_divergent(midpoint = .25) +
transition_time(frame) +
labs(x = '',y = '')
fieldSupplement <- addNFLField(contourPlot)
fieldSupplement <- fieldSupplement + geom_segment(data = movementDf,
aes(x = x,y = y, xend = x + s * sin(dir * pi / 180), yend = y + s * cos(dir * pi / 180),colour = team),
arrow = arrow(length = unit(.4,"cm"))) +
geom_point(data = movementDf,aes(x = x,y = y, colour = team,size = 2))
return(animate(fieldSupplement,height = 550,width = 840,fps = 10))
}
makeECAPlot <- function(playNum,gameNum,data = w1Data){
p = isolatePlay(playNum,gameNum,data)
numFrames = max(p$frameId)
#Setup grid
playDir = p[1,'playDirection']
qbx_max = max(p[p$position == 'QB','x'])
qbx_min = min(p[p$position == 'QB','x'])
if(playDir == 'left'){
xmin = ifelse(qbx_max-60<xleft,xleft,qbx_max-60); xmax = qbx_max
}
else{
xmax = ifelse(qbx_max+60>xright,xright,qbx_max+60); xmin = qbx_max
}
# print(paste(xmin,xmax))
firstFrame = findECAData(1,playNum,gameNum,data = w1Data,givenMinX = xmin,givenMaxX = xmax)
# print(firstFrame)
bigContourDf = firstFrame$ContourData
bigMoveDf = firstFrame$MovementData
bigContourDf$frame = 1
for(frameNum in 2:numFrames){
print(frameNum)
# print(paste(xmin,xmax))
curFrame = findECAData(frameNum,playNum,gameNum,data = w1Data,givenMinX = xmin,givenMaxX = xmax)
curContour = curFrame$ContourData
curContour$frame = frameNum
bigContourDf <- rbind(bigContourDf,curContour)
bigMoveDf <- rbind(bigMoveDf,curFrame$MovementData)
}
bigMoveDf$frame = bigMoveDf$frameId
bigPlot <- addMovingPieces(bigContourDf,bigMoveDf)
return(bigPlot)
# return(list('contourDf' = bigContourDf,'movementDf' = bigMoveDf))
}
# #Play 2, TB/NO
# play2 = 4173
# game2 = 2018090906
# ECA_Gif_2 = makeECAPlot(play2,game2)
#
# contDf2 = ECA_Gif_2$contourDf
# moveDf2 = ECA_Gif_2$movementDf
#
# addMovingPieces(contDf2,moveDf2)
# makeECAPlot_Frame(38,play2,game2)
# #Arrives at 50
#
#
#
# #Play 3, HOU/NE
# play3 = 1533
# game3 = 2018090905
# ECA_Gif_3 = makeECAPlot(play3,game3)
#
# contDf3 = ECA_Gif_3$contourDf
# moveDf3 = ECA_Gif_3$movementDf
#
# addMovingPieces(contDf3,moveDf3)
# makeECAPlot_Frame(40,play3,game3)
# # Arrives at 55
makeECAPlot_BallDest <- function(playNum,gameNum,data = w1Data,givenMinX = NULL,givenMaxX = NULL,flipColors = F){
atPassDf = findFrameAtPass(playNum,gameNum,data)
frameAtPass = atPassDf[1,'frameId']
atArrivalDf = findFrameAtArrival(playNum,gameNum,data)
# frameAtArrival = atArrivalDf[1,'frameId']
# print(atArrivalDf)
ecaPlot = makeECAPlot_Frame(frameAtPass,playNum,gameNum,data = w1Data,givenMinX = givenMinX,givenMaxX = givenMaxX,flipColors = flipColors)
# print(ecaPlot)
ecaPlot <- ecaPlot + geom_point(data=atArrivalDf[atArrivalDf$displayName == 'Football',],
aes(x = x,y = y),size = 4,colour = 'burlywood4')
playDesc = findPlay(playNum,gameNum)$playDescription
if(!grepl('incomplete',as.character(playDesc))) playDesc = paste(strsplit(as.character(playDesc),'yards')[[1]][1],'yards.',sep = '')
ecaPlot <- ecaPlot + labs(title = playDesc)
return(ecaPlot)
}
makeECAPlot_BallDest(play2,game2,givenMinX = 0,givenMaxX = 55)
makeECAPlot_BallDest(play3,game3,givenMinX = 31,givenMaxX = 91)
# makeECAPlot_Frame(40,play2,game2)
<file_sep>#Expected Future Locations
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
source('FindAirDuration.R')
load('FinalPlays.Rdata')
findExpectedFutureLoc <- function(timeInSec,currentX,currentY,currentS,currentDir,currentA,currentO){
#Given time, current location, velocity, and acceleration, uses physics to predict future location
#in the certain amount of elapsed time. Assumes velocity and acceleration do not change over the time
#which is why this is the expect location, serving more or less as the mean of future positions
#Determine direction of acceleration, assuming acceleration is in the orientation of the player, unless backpedaling
#If angle of motion is opposite of orientation, then probably backpedaling
if(abs(abs(currentDir - currentO) - 180) < abs(currentDir - currentO) - 30){
#Backpedaling (probably)
accelAngle = currentO - 180
}
else{
accelAngle = currentO
}
v_x = currentS * sin(currentDir * pi / 180)
v_y = currentS * cos(currentDir * pi / 180)
a_x = currentA * sin(accelAngle * pi / 180)
a_y = currentA * cos(accelAngle * pi / 180)
fut_x = currentX + v_x * timeInSec + .5 * a_x * timeInSec^2
fut_y = currentY + v_y * timeInSec + .5 * a_y * timeInSec^2
return(list('Future_x' = fut_x,'Future_y' = fut_y))
}
# p = playsToUse[1,]
# p2 = findExpectedFutureLoc(1.101,p$defender1X,p$defender1Y,p$defender1S,p$defender1Dir,p$defender1A,p$defender1O)
#
# plot(p$defender1X,p$defender1Y)
# points(p2$Future_x,p2$Future_y,col='red')
# arrows(p$defender1X,p$defender1Y,p$defender1X+cos(p$defender1Dir * pi/180),p$defender1Y+sin(p$defender1Dir * pi/180),length = .02)
# arrows(p$defender1X,p$defender1Y,p$defender1X+cos(p$defender1O * pi/180),p$defender1Y+sin(p$defender1O * pi/180),length = .02)
plotExpectedFutureLocs <- function(playNum,gameNum,data = w1Data){
#First, just plot the play as it stands
base = baseNFLField()
playData = isolatePlay(playNum,gameNum,data)
playInfo = findPlay(playNum,gameNum)
playData[playData$displayName == 'Football','jerseyNumber'] = 'FB'
if(playData$playDirection[1] == 'right'){
LOS = playInfo$absoluteYardlineNumber
L2G = LOS + playInfo$yardsToGo
}
else{
LOS = playInfo$absoluteYardlineNumber
L2G = LOS - playInfo$yardsToGo
}
field.lines.df = data.frame(x = c(LOS,L2G),
ybot = rep(0,2),
ytop = rep(53.3,2))
actualLocPlot <- base + geom_point(data = playData,aes(x = x,y = y,col = team,size = 4)) +
geom_text(data = playData,aes(x = x,y = y,size = 4,label = jerseyNumber)) +
geom_segment(data=field.lines.df,
aes(x=x,y=ybot,xend=x,yend=ytop,linetype='a'),
inherit.aes = F,
col=c('blue','yellow')) +
transition_time(frameId) +
shadow_mark(alpha = .3,size = .5)
#Then, lets find out where they could be
#Find which players are covering who
defAssignDf = assignDefenders(play,game,data)
defAssignDf$Future_x = NA
defAssignDf$Future_y = NA
#Loop through the frames
for(frame in 1:max(defAssignDf$frameId)){
# for(frame in 1:2){
#Find distance from potential targets to qb
offInfo = playData[playData$frameId == frame,]
qb_x = offInfo[offInfo$position == 'QB','x']
qb_y = offInfo[offInfo$position == 'QB','y']
curDefFrame = defAssignDf[defAssignDf$frameId == frame,]
curPotTargets = unique(curDefFrame$PlayerDefending)
#Loop through the pot targets
for(targName in curPotTargets){
targ_x = offInfo[offInfo$displayName == targName,'x']
targ_y = offInfo[offInfo$displayName == targName,'y']
distToQb = sqrt((targ_x - qb_x)^2 + (targ_y - qb_y)^2)
#Find the time the ball would have to be in the air for each of those potential targets
potAirTimes = findAirDuration(distToQb)
#Just the median times right now
medAirTime = potAirTimes[4]
coveringDefRows = defAssignDf[(defAssignDf$frameId == frame) & (defAssignDf$PlayerDefending == targName),]
for(defPlayerName in coveringDefRows$displayName){
curCoverPlayer = coveringDefRows[coveringDefRows$displayName == defPlayerName,]
defAssignDf[(defAssignDf$frameId == frame) &
(defAssignDf$PlayerDefending == targName) &
(defAssignDf$displayName == defPlayerName),c('Future_x','Future_y')] =
findExpectedFutureLoc(medAirTime,curCoverPlayer$x,curCoverPlayer$y,curCoverPlayer$s,curCoverPlayer$dir,
curCoverPlayer$a,curCoverPlayer$o)
}
# defAssignDf[(defAssignDf$frameId == frame) & (defAssignDf$PlayerDefending == targName),
# c('Future_x','Future_y')] = findExpectedFutureLoc(medAirTime,)
}
}
futLocAddedPlot <- actualLocPlot + geom_point(data = defAssignDf,aes(x = Future_x,y = Future_y,col = team,size = 4)) +
geom_text(data = playData,aes(x = x,y = y,size = 4,label = jerseyNumber)) +
transition_time(frameId)
return(animate(futLocAddedPlot,height = 700,width = 840))
}
plotExpectedFutureLocs(play,game,w1Data)
<file_sep>#AirTime Vs Distance
library(fitdistrplus)
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
load('Plays_All_Offense_Defense_Ball.Rdata')
findAirDuration <- function(throwDistance,playData = playsToUse,medOnly = F){
#Given a throw distance, will find the fit gamma distribution of times for
#how long the ball might be in the air
#Finds previous data within a 1 yard range of the given distance, adds small 1e-6 to make gamma fitable with 0s
if(throwDistance < 1) throwDistance = 1
else if(throwDistance > 55) throwDistance = 55
laxSpace = ifelse(throwDistance < 30,.5,ifelse(throwDistance < 40,1,ifelse(throwDistance < 50,1.5,5)))
durationsToUse = playData[(playData$throwDistance >= throwDistance - laxSpace) &
(playData$throwDistance <= throwDistance + laxSpace) &
(playData$BallAirDuration >= 0) &
!is.na(playData$BallAirDuration),'BallAirDuration'] + 1e-6
# print(durationsToUse)
fit.gamma <- fitdist(durationsToUse,distr = 'gamma', method = 'mle')
if(medOnly){
timeQuants = qgamma(.5,fit.gamma$estimate[1],fit.gamma$estimate[2]) - 1e-6
names(timeQuants) = .5
}
else{
timeQuants = qgamma(c(.05,.1,.25,.5,.75,.9,.95),fit.gamma$estimate[1],fit.gamma$estimate[2]) - 1e-6
names(timeQuants) = c(.05,.1,.25,.5,.75,.9,.95)
}
return(timeQuants)
}
findAirDuration(20)
# plot(trimmedPlays$throwDistance,trimmedPlays$BallAirDuration)
# points(trimmedPlays[(trimmedPlays$throwDistance >19) & (trimmedPlays$throwDistance < 21),'throwDistance'],
# trimmedPlays[(trimmedPlays$throwDistance >19) & (trimmedPlays$throwDistance < 21),'BallAirDuration'],col='red')
# hist(trimmedPlays[(trimmedPlays$throwDistance >19) & (trimmedPlays$throwDistance < 21),'BallAirDuration'],breaks = 30)
#
# x = trimmedPlays[(trimmedPlays$throwDistance >19) & (trimmedPlays$throwDistance < 21),'BallAirDuration'] + 1e-6
# fit.gamma <- fitdist(x,distr = 'gamma', method = 'mle')
#
# hist(x,breaks = 30,freq=F)
# points(seq(0,4,length.out = 30),dgamma(seq(0,4,length.out = 30),shape = 8.107134,rate = 7.122155),col='blue')
# fit.gamma$estimate
# findAirDuration(24)
<file_sep>#SplitPlaysByWeek
setwd('F:/BigDataBowl2021')
games = read.csv('games.csv')
load('FinalPlays.Rdata')
# load('Combined2018PassingData.RData')
# w1Plays = plays[plays$gameId %in% games[games$week == 1,'gameId'],]
# w2Plays = plays[plays$gameId %in% games[games$week == 2,'gameId'],]
# w3Plays = plays[plays$gameId %in% games[games$week == 3,'gameId'],]
# w4Plays = plays[plays$gameId %in% games[games$week == 4,'gameId'],]
# w5Plays = plays[plays$gameId %in% games[games$week == 5,'gameId'],]
# w6Plays = plays[plays$gameId %in% games[games$week == 6,'gameId'],]
# w7Plays = plays[plays$gameId %in% games[games$week == 7,'gameId'],]
# w8Plays = plays[plays$gameId %in% games[games$week == 8,'gameId'],]
# w9Plays = plays[plays$gameId %in% games[games$week == 9,'gameId'],]
# w10Plays = plays[plays$gameId %in% games[games$week == 10,'gameId'],]
# w11Plays = plays[plays$gameId %in% games[games$week == 11,'gameId'],]
# w12Plays = plays[plays$gameId %in% games[games$week == 12,'gameId'],]
# w13Plays = plays[plays$gameId %in% games[games$week == 13,'gameId'],]
# w14Plays = plays[plays$gameId %in% games[games$week == 14,'gameId'],]
# w15Plays = plays[plays$gameId %in% games[games$week == 15,'gameId'],]
# w16Plays = plays[plays$gameId %in% games[games$week == 16,'gameId'],]
# w17Plays = plays[plays$gameId %in% games[games$week == 17,'gameId'],]
findWeekNum <- function(gameNum){
return(games[games$gameId == gameNum,'week'])
}
splitPlaysByWeek <- function(weekNum){
return(playsToUse[playsToUse$gameId %in% games[games$week == weekNum,'gameId'],])
}
splitTrackingByWeek <- function(weekNum){
return(read.csv(paste('week',weekNum,'.csv',sep='')))
}
<file_sep>#Attach TD Indicator
load('Plays_All_Offense_Defense_Ball.Rdata')
load('CoverageData.Rdata')
playsToUse$TD = NA
for(i in 1:nrow(playsToUse)){
playsToUse[i,'TD'] = grepl('TOUCHDOWN',playsToUse[i,'playDescription'],fixed = T)
}
coverageDf$TD = NA
for(i in 1:nrow(coverageDf)){
playNum = coverageDf[i,'Play']
gameNum = coverageDf[i,'Game']
p = findPlay(playNum,gameNum,playsToUse)
coverageDf[i,'TD'] = p$TD
}
<file_sep>#Find stuff
library(sp)
options(stringsAsFactors = F)
setwd('F:/BigDataBowl2021')
source('GridField.R')
rm(plays,trimmedPlays,w1Data)
coverageDf = data.frame(Week = numeric(),Game = numeric(),Play = numeric(),
Down = numeric(),Dist = numeric(),LOS = numeric(),PlayResult = numeric(),PassResult = character(),DPI = character(),
TargetReceiver = character(),YAC = numeric(),Route = character(),ThrowDistance = numeric(),
Def_Name = character(),Def_X = numeric(),Def_Y = numeric(),Def_Dist = numeric(),Def_Pos = character(),
Def_S = numeric(),Def_A = numeric(),Def_O = numeric(),Def_Dir = numeric(),AirDuration = numeric(),
Dest_X = numeric(),Dest_Y = numeric(),PlayDirection = character(),QB_X = numeric(),QB_Y = numeric())
# load('CoverageData.Rdata')
for(i in 1:nrow(playsToUse)){
print(i); print(nrow(coverageDf))
play = playsToUse[i,]
dest_x = play$Dest_X;dest_y = play$Dest_Y
if(!is.na(play$defender1Name)){
p1Hull = findMedianCoverageHull(play$defender1X,play$defender1Y,play$defender1S*sin(play$defender1Dir * pi / 180),
play$defender1S*cos(play$defender1Dir * pi / 180),play$QB_X,play$QB_Y,play$PlayDirection)
if(nrow(p1Hull) > 0){
if(point.in.polygon(dest_x,dest_y,p1Hull$xPts,p1Hull$yPts)){
coverageDf <- rbind(coverageDf,setNames(play[,c('week','gameId','playId','down','yardsToGo','absoluteYardlineNumber',
'offensePlayResult','passResult','isDefensivePI',
'MatchedTargetReceiver','YAC','route','throwDistance','defender1Name','defender1X',
'defender1Y','defender1Dist','defender1Pos','defender1S','defender1A','defender1O',
'defender1Dir','BallAirDuration','Dest_X','Dest_Y','PlayDirection','QB_X','QB_Y')],names(coverageDf)))
}
}
if(!is.na(play$defender2Name)){
p2Hull = findMedianCoverageHull(play$defender2X,play$defender2Y,play$defender2S*sin(play$defender2Dir * pi / 180),
play$defender2S*cos(play$defender2Dir * pi / 180),play$QB_X,play$QB_Y,play$PlayDirection)
if(nrow(p2Hull) > 0){
if(point.in.polygon(dest_x,dest_y,p2Hull$xPts,p2Hull$yPts)){
coverageDf <- rbind(coverageDf,setNames(play[,c('week','gameId','playId','down','yardsToGo','absoluteYardlineNumber',
'offensePlayResult','passResult','isDefensivePI',
'MatchedTargetReceiver','YAC','route','throwDistance','defender2Name','defender2X',
'defender2Y','defender2Dist','defender2Pos','defender2S','defender2A','defender2O',
'defender2Dir','BallAirDuration','Dest_X','Dest_Y','PlayDirection','QB_X','QB_Y')],names(coverageDf)))
}
}
if(!is.na(play$defender3Name)){
p3Hull = findMedianCoverageHull(play$defender3X,play$defender3Y,play$defender3S*sin(play$defender3Dir * pi / 180),
play$defender3S*cos(play$defender3Dir * pi / 180),play$QB_X,play$QB_Y,play$PlayDirection)
if(nrow(p3Hull) > 0){
if(point.in.polygon(dest_x,dest_y,p3Hull$xPts,p3Hull$yPts)){
coverageDf <- rbind(coverageDf,setNames(play[,c('week','gameId','playId','down','yardsToGo','absoluteYardlineNumber',
'offensePlayResult','passResult','isDefensivePI',
'MatchedTargetReceiver','YAC','route','throwDistance','defender3Name','defender3X',
'defender3Y','defender3Dist','defender3Pos','defender3S','defender3A','defender3O',
'defender3Dir','BallAirDuration','Dest_X','Dest_Y','PlayDirection','QB_X','QB_Y')],names(coverageDf)))
}
}
}
}
}
if(i %% 50 == 0) {
print('saving')
save(coverageDf,file = 'CoverageData.Rdata')
}
}
# i = 1
<file_sep>#Ball Air Time
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
load('Plays_All_Offense_Defense.Rdata')
trimmedPlays$BallAirDuration = NA
#Standard Loop through trimmedPlays
oldWeek = 0
# for(i in 1:nrow(trimmedPlays)){
for(i in 1:nrow(trimmedPlays)){
play = trimmedPlays[i,'playId']; game = trimmedPlays[i,'gameId']
newWeek = findWeekNum(game)
if(newWeek != oldWeek) {
trackData = splitTrackingByWeek(newWeek)
routeOpts = levels(trackData$route)
playData = splitPlaysByWeek(newWeek)
}
if(i %% 200 == 1) print(paste(round(100*i/nrow(trimmedPlays),2),'% Complete',sep=''))
#Action
frameArrive = findFrameAtArrival(play,game,trackData)
if(!any(is.na(frameArrive$x))){
framePass = findFrameAtPass(play,game,trackData)
timePass = framePass[1,'time']
timeArrive = frameArrive[1,'time']
trimmedPlays[i,'BallAirDuration'] = timeArrive - timePass
}
oldWeek = newWeek
}
# save(trimmedPlays,file = 'Plays_All_Offense_Defense_Ball.Rdata')
<file_sep>#Attach Defenders and Distances
setwd('F:/BigData<PASSWORD>21')
source('InstantExam.R')
source('SplitPlaysByWeek.R')
load('Plays_All_Offense.Rdata')
colsToUse = c('gameId','playId','playDescription','down',
'yardsToGo','possessionTeam','playType',
'absoluteYardlineNumber','passResult','offensePlayResult','isDefensivePI',
'MatchedTargetReceiver','YAC','week','route','throwDistance','Target_X','Target_Y')
trimmedPlays = plays[!is.na(plays$MatchedTargetReceiver) & !is.na(plays$throwDistance),colsToUse]
trimmedPlays$defender1Name = NA
trimmedPlays$defender1X = NA
trimmedPlays$defender1Y = NA
trimmedPlays$defender1Dist = NA
trimmedPlays$defender1Pos = NA
trimmedPlays$defender1S = NA
trimmedPlays$defender1A = NA
trimmedPlays$defender1dir = NA
trimmedPlays$defender1O = NA
trimmedPlays$defender2Name = NA
trimmedPlays$defender2X = NA
trimmedPlays$defender2Y = NA
trimmedPlays$defender2Dist = NA
trimmedPlays$defender2Pos = NA
trimmedPlays$defender2S = NA
trimmedPlays$defender2A = NA
trimmedPlays$defender2dir = NA
trimmedPlays$defender2O = NA
trimmedPlays$defender3Name = NA
trimmedPlays$defender3X = NA
trimmedPlays$defender3Y = NA
trimmedPlays$defender3Dist = NA
trimmedPlays$defender3Pos = NA
trimmedPlays$defender3S = NA
trimmedPlays$defender3A = NA
trimmedPlays$defender3dir = NA
trimmedPlays$defender3O = NA
load('Plays_All_Offense_Defense.Rdata')
#Standard Loop through trimmedPlays
oldWeek = 0
# for(i in 1:nrow(trimmedPlays)){
for(i in which(is.na(trimmedPlays$defender1X))[which(is.na(trimmedPlays$defender1X)) > 7500]){
play = trimmedPlays[i,'playId']; game = trimmedPlays[i,'gameId']
newWeek = findWeekNum(game)
if(newWeek != oldWeek) {
trackData = splitTrackingByWeek(newWeek)
routeOpts = levels(trackData$route)
playData = splitPlaysByWeek(newWeek)
}
if(i %% 200 == 1) print(paste(round(100*i/nrow(trimmedPlays),2),'% Complete',sep=''))
#Action
targRec = trimmedPlays[i,'MatchedTargetReceiver']
if(!is.na(targRec)){
frame = findFrameAtPass(play,game,trackData,assignDef = T)
defPlays = frame[frame$PlayerDefending == targRec,]
if(nrow(defPlays) == 1){
trimmedPlays[i,c('defender1Name','defender1X','defender1Y','defender1A','defender1S','defender1O','defender1Dir','defender1Dist','defender1Pos')] =
c(levels(defPlays$displayName)[defPlays$displayName],defPlays$x,defPlays$y,defPlays$a,defPlays$s,defPlays$o,defPlays$dir,
sqrt((defPlays$x - trimmedPlays[i,'Target_X'])^2 + (defPlays$y - trimmedPlays[i,'Target_Y'])^2),levels(defPlays$position)[defPlays$position])
# trimmedPlays[i,'defender1Name'] = levels(defPlays$displayName)[defPlays$displayName]
# trimmedPlays[i,'defender1X'] = defPlays$x
# trimmedPlays[i,'defender1Y'] = defPlays$y
# trimmedPlays[i,'defender1Dist'] = sqrt((trimmedPlays[i,'defender1X'] - trimmedPlays[i,'Target_X'])^2
# + (trimmedPlays[i,'defender1Y'] - trimmedPlays[i,'Target_Y'])^2)
# trimmedPlays[i,'defender1Pos'] = levels(defPlays$position)[defPlays[1,'position']]
}
else if(nrow(defPlays) == 2){
trimmedPlays[i,c('defender1Name','defender1X','defender1Y','defender1A','defender1S','defender1O','defender1Dir','defender1Dist','defender1Pos')] =
c(levels(defPlays$displayName)[defPlays[1,'displayName']],defPlays[1,'x'],defPlays[1,'y'],defPlays[1,'a'],defPlays[1,'s'],defPlays[1,'o'],defPlays[1,'dir'],
sqrt((defPlays[1,'x'] - trimmedPlays[i,'Target_X'])^2 + (defPlays[1,'y'] - trimmedPlays[i,'Target_Y'])^2),
levels(defPlays$position)[defPlays[1,'position']])
trimmedPlays[i,c('defender2Name','defender2X','defender2Y','defender2A','defender2S','defender2O','defender2Dir','defender2Dist','defender2Pos')] =
c(levels(defPlays$displayName)[defPlays[2,'displayName']],defPlays[2,'x'],defPlays[2,'y'],defPlays[2,'a'],defPlays[2,'s'],defPlays[2,'o'],defPlays[2,'dir'],
sqrt((defPlays[2,'x'] - trimmedPlays[i,'Target_X'])^2 + (defPlays[2,'y'] - trimmedPlays[i,'Target_Y'])^2),
levels(defPlays$position)[defPlays[2,'position']])
# trimmedPlays[i,'defender1Name'] = levels(defPlays$displayName)[defPlays[1,'displayName']]
# trimmedPlays[i,'defender1X'] = defPlays[1,'x']
# trimmedPlays[i,'defender1Y'] = defPlays[1,'y']
# trimmedPlays[i,'defender2Name'] = levels(defPlays$displayName)[defPlays[2,'displayName']]
# trimmedPlays[i,'defender2X'] = defPlays[2,'x']
# trimmedPlays[i,'defender2Y'] = defPlays[2,'y']
# trimmedPlays[i,'defender1Dist'] = sqrt((trimmedPlays[i,'defender1X'] - trimmedPlays[i,'Target_X'])^2
# + (trimmedPlays[i,'defender1Y'] - trimmedPlays[i,'Target_Y'])^2)
# trimmedPlays[i,'defender2Dist'] = sqrt((trimmedPlays[i,'defender2X'] - trimmedPlays[i,'Target_X'])^2
# + (trimmedPlays[i,'defender2Y'] - trimmedPlays[i,'Target_Y'])^2)
# trimmedPlays[i,'defender1Pos'] = levels(defPlays$position)[defPlays[1,'position']]
# trimmedPlays[i,'defender2Pos'] = levels(defPlays$position)[defPlays[2,'position']]
}
else if(nrow(defPlays) >= 3){
trimmedPlays[i,c('defender1Name','defender1X','defender1Y','defender1A','defender1S','defender1O','defender1Dir','defender1Dist','defender1Pos')] =
c(levels(defPlays$displayName)[defPlays[1,'displayName']],defPlays[1,'x'],defPlays[1,'y'],defPlays[1,'a'],defPlays[1,'s'],defPlays[1,'o'],defPlays[1,'dir'],
sqrt((defPlays[1,'x'] - trimmedPlays[i,'Target_X'])^2 + (defPlays[1,'y'] - trimmedPlays[i,'Target_Y'])^2),
levels(defPlays$position)[defPlays[1,'position']])
trimmedPlays[i,c('defender2Name','defender2X','defender2Y','defender2A','defender2S','defender2O','defender2Dir','defender2Dist','defender2Pos')] =
c(levels(defPlays$displayName)[defPlays[2,'displayName']],defPlays[2,'x'],defPlays[2,'y'],defPlays[2,'a'],defPlays[2,'s'],defPlays[2,'o'],defPlays[2,'dir'],
sqrt((defPlays[2,'x'] - trimmedPlays[i,'Target_X'])^2 + (defPlays[2,'y'] - trimmedPlays[i,'Target_Y'])^2),
levels(defPlays$position)[defPlays[2,'position']])
trimmedPlays[i,c('defender3Name','defender3X','defender3Y','defender3A','defender3S','defender3O','defender3Dir','defender3Dist','defender3Pos')] =
c(levels(defPlays$displayName)[defPlays[3,'displayName']],defPlays[3,'x'],defPlays[3,'y'],defPlays[3,'a'],defPlays[3,'s'],defPlays[3,'o'],defPlays[3,'dir'],
sqrt((defPlays[3,'x'] - trimmedPlays[i,'Target_X'])^2 + (defPlays[3,'y'] - trimmedPlays[i,'Target_Y'])^2),
levels(defPlays$position)[defPlays[3,'position']])
# trimmedPlays[i,'defender1Name'] = levels(defPlays$displayName)[defPlays[1,'displayName']]
# trimmedPlays[i,'defender1X'] = defPlays[1,'x']
# trimmedPlays[i,'defender1Y'] = defPlays[1,'y']
# trimmedPlays[i,'defender2Name'] = levels(defPlays$displayName)[defPlays[2,'displayName']]
# trimmedPlays[i,'defender2X'] = defPlays[2,'x']
# trimmedPlays[i,'defender2Y'] = defPlays[2,'y']
# trimmedPlays[i,'defender3Name'] = levels(defPlays$displayName)[defPlays[3,'displayName']]
# trimmedPlays[i,'defender3X'] = defPlays[3,'x']
# trimmedPlays[i,'defender3Y'] = defPlays[3,'y']
# trimmedPlays[i,'defender1Dist'] = sqrt((trimmedPlays[i,'defender1X'] - trimmedPlays[i,'Target_X'])^2
# + (trimmedPlays[i,'defender1Y'] - trimmedPlays[i,'Target_Y'])^2)
# trimmedPlays[i,'defender2Dist'] = sqrt((trimmedPlays[i,'defender2X'] - trimmedPlays[i,'Target_X'])^2
# + (trimmedPlays[i,'defender2Y'] - trimmedPlays[i,'Target_Y'])^2)
# trimmedPlays[i,'defender3Dist'] = sqrt((trimmedPlays[i,'defender3X'] - trimmedPlays[i,'Target_X'])^2
# + (trimmedPlays[i,'defender3Y'] - trimmedPlays[i,'Target_Y'])^2)
# trimmedPlays[i,'defender1Pos'] = levels(defPlays$position)[defPlays[1,'position']]
# trimmedPlays[i,'defender2Pos'] = levels(defPlays$position)[defPlays[2,'position']]
# trimmedPlays[i,'defender3Pos'] = levels(defPlays$position)[defPlays[3,'position']]
}
}
oldWeek = newWeek
}
# save(trimmedPlays,file = 'Plays_All_Offense_Defense.Rdata')
<file_sep>#Preliminary Analysis
setwd('F:/BigDataBowl2021')
source('InstantExam.R')
# load('Combined2018PassingData.RData')
load('UpdatedPlays.Rdata')
targetPlays = plays[!is.na(plays$MatchedTargetReceiver),]
play = 75
game = 2018090600
sideBySidePassPlot(play,game,w1Data)
<file_sep>#Attach Route
setwd('F:/<PASSWORD>')
source('InstantExam.R')
load('Plays_Week_Targets_YAC.Rdata')
source('SplitPlaysByWeek.R')
plays$route = NA
#Standard Loop through plays
oldWeek = 0
for(i in 1:nrow(plays)){
play = plays[i,'playId']; game = plays[i,'gameId']
newWeek = findWeekNum(game)
if(newWeek != oldWeek) {
trackData = splitTrackingByWeek(newWeek)
routeOpts = levels(trackData$route)
playData = splitPlaysByWeek(newWeek)
}
if(i %% 50 == 1) print(paste(round(100*i/nrow(plays),2),'% Complete',sep=''))
#Action
frame = isolateFrame(1,play,game,trackData)
targRec = plays[i,'MatchedTargetReceiver']
if(!is.na(targRec)) plays[i,'route'] = routeOpts[frame[frame$displayName == targRec,'route']]
oldWeek = newWeek
}
# save(plays,file = 'Plays_Week_Targets_YAC_Route.Rdata')
<file_sep>#Base NFL Field
library(ggplot2)
library(extrafont)
# font_import()
baseNFLField <- function(){
ytop = 53.3
ybot = 0
field.lines <- data.frame(x1 = c(0,0,0,120,110,10),
x2 = c(120,120,0,120,110,10),
y1 = c(ybot,ytop,ytop,ytop,ytop,ytop),
y2 = c(ybot,ytop,ybot,ybot,ybot,ybot))
ids = factor(c('endDef','fieldPlay','endOff'))
values <- data.frame(
id = ids,
color = c('darkgreen','darkgreen','darkgreen')
)
field.shape <- data.frame(id = unlist(matrix(t(matrix(rep(ids,4),nrow=3)),nrow=1)[1,]),
xg = c(0,0,10,10,10,10,110,110,110,110,120,120),
yg = c(ybot,ytop,ytop,ybot,ybot,ytop,ytop,ybot,ybot,ytop,ytop,ybot))
datapoly <- merge(values, field.shape, by = c("id"))
fieldLines <- geom_segment(data=field.lines,aes(x=x1,y=y1,xend=x2,yend=y2,
linetype='a'),colour='white',
size = c(2,2,2,2,1,1))
minor.lines.df <- data.frame(xvals = seq(15,105,length.out = 19),
ybot = rep(ybot,19),
ytop = rep(ytop,19))
minor.field.lines <- geom_segment(data = minor.lines.df,aes(x = xvals,y = ybot,xend = xvals,yend = ytop),colour = 'white')
hash.marks.df <- data.frame(xvals = rep(11:109,4),
ybot = c(rep(ybot + 1/3,99),rep(22.91,99),rep(29.73,99),rep(ytop - 1,99)),
ytop = c(rep(ybot + 1 ,99),rep(23.57,99),rep(30.39,99),rep(ytop - 1/3,99)))
hash.marks <- geom_segment(data = hash.marks.df,aes(x = xvals,y = ybot,xend = xvals, yend = ytop),colour = 'white')
field.numbers.bot.df <- data.frame(textVals = unlist(lapply(c(1,0,2,0,3,0,4,0,5,0,4,0,3,0,2,0,1,0),toString)),
#x_text = c(8,12,18,22,28,32,38,42,48,52,58,62,68,72,78,82,88,92),
x_text = c(8.5,11.5,18.5,21.5,28.5,31.5,38.5,41.5,48.5,51.5,58.5,61.5,68.5,71.5,78.5,81.5,88.5,91.5)+10,
y_text = rep(ybot + 9,18))
show.bot.numbers <- geom_text(data=field.numbers.bot.df, aes(x = x_text, y = y_text, label = textVals),
size = 6,col='white',family = ifelse('Century' %in% fonts(),windowsFont('Century'),'Impact'))
field.numbers.top.df <- data.frame(textVals = unlist(lapply(c(0,1,0,2,0,3,0,4,0,5,0,4,0,3,0,2,0,1),toString)),
#x_text = c(8,12,18,22,28,32,38,42,48,52,58,62,68,72,78,82,88,92),
x_text = c(8.5,11.5,18.5,21.5,28.5,31.5,38.5,41.5,48.5,51.5,58.5,61.5,68.5,71.5,78.5,81.5,88.5,91.5)+10,
y_text = rep(ytop - 9,18))
show.top.numbers <- geom_text(data=field.numbers.top.df, aes(x = x_text, y = y_text, label = textVals),
size = 6,col='white',family = ifelse('Century' %in% fonts(),windowsFont('Century'),'Impact'),angle = 180)
left.endzone.df <- data.frame(textVals = 'T E A M', x_left = 5, y_left = ytop/2)
show.left.endzone <- geom_text(data = left.endzone.df, aes(x = x_left, y = y_left,label = textVals),
size = 10, col = 'white', family = ifelse('Copperplate Gothic Bold' %in% fonts(),windowsFont('Copperplate Gothic Bold'),'Georgia'),angle = 90)
right.endzone.df <- data.frame(textVals = 'T E A M', x_right = 115, y_right = ytop/2)
show.right.endzone <- geom_text(data = right.endzone.df, aes(x = x_right, y = y_right,label = textVals),
size = 10, col = 'white', family = ifelse('Copperplate Gothic Bold' %in% fonts(),windowsFont('Copperplate Gothic Bold'),'Georgia'),angle = -90)
big_box <- data.frame(x_big_box_s = c(-1,-1,-1,121),
x_big_box_e = c(121,121,-1,121),
y_big_box_s = c(ytop+.25,ybot-.2,ybot-.2,ybot-.2),
y_big_box_e = c(ytop+.25,ybot-.2,ytop+.25,ytop+.25))
baseNFL <- ggplot(datapoly, aes(x = xg, y = yg)) +
geom_polygon(aes(fill = color, group = id)) +
scale_fill_identity() +
labs(x='',y='') +
minor.field.lines +
hash.marks +
show.bot.numbers + show.top.numbers +
show.left.endzone + show.right.endzone +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank(),
legend.position = 'none') +
fieldLines +
geom_segment(data=big_box,aes(x=x_big_box_s,y=y_big_box_s,xend=x_big_box_e,yend=y_big_box_e),colour='black')
return(baseNFL)
}
noColor_baseNFLField <- function(){
ytop = 53.3
ybot = 0
field.lines <- data.frame(x1 = c(0,0,0,120,110,10),
x2 = c(120,120,0,120,110,10),
y1 = c(ybot,ytop,ytop,ytop,ytop,ytop),
y2 = c(ybot,ytop,ybot,ybot,ybot,ybot))
ids = factor(c('endDef','fieldPlay','endOff'))
values <- data.frame(
id = ids,
color = c('white','white','white')
)
field.shape <- data.frame(id = unlist(matrix(t(matrix(rep(ids,4),nrow=3)),nrow=1)[1,]),
xg = c(0,0,10,10,10,10,110,110,110,110,120,120),
yg = c(ybot,ytop,ytop,ybot,ybot,ytop,ytop,ybot,ybot,ytop,ytop,ybot))
datapoly <- merge(values, field.shape, by = c("id"))
fieldLines <- geom_segment(data=field.lines,aes(x=x1,y=y1,xend=x2,yend=y2,
linetype='a'),colour='white',
size = c(2,2,2,2,1,1))
minor.lines.df <- data.frame(xvals = seq(15,105,length.out = 19),
ybot = rep(ybot,19),
ytop = rep(ytop,19))
minor.field.lines <- geom_segment(data = minor.lines.df,aes(x = xvals,y = ybot,xend = xvals,yend = ytop),colour = 'white')
hash.marks.df <- data.frame(xvals = rep(11:109,4),
ybot = c(rep(ybot + 1/3,99),rep(22.91,99),rep(29.73,99),rep(ytop - 1,99)),
ytop = c(rep(ybot + 1 ,99),rep(23.57,99),rep(30.39,99),rep(ytop - 1/3,99)))
hash.marks <- geom_segment(data = hash.marks.df,aes(x = xvals,y = ybot,xend = xvals, yend = ytop),colour = 'white')
field.numbers.bot.df <- data.frame(textVals = unlist(lapply(c(1,0,2,0,3,0,4,0,5,0,4,0,3,0,2,0,1,0),toString)),
#x_text = c(8,12,18,22,28,32,38,42,48,52,58,62,68,72,78,82,88,92),
x_text = c(8.5,11.5,18.5,21.5,28.5,31.5,38.5,41.5,48.5,51.5,58.5,61.5,68.5,71.5,78.5,81.5,88.5,91.5)+10,
y_text = rep(ybot + 9,18))
show.bot.numbers <- geom_text(data=field.numbers.bot.df, aes(x = x_text, y = y_text, label = textVals),
size = 6,col='white',family = ifelse('Century' %in% fonts(),windowsFont('Century'),'Impact'))
field.numbers.top.df <- data.frame(textVals = unlist(lapply(c(0,1,0,2,0,3,0,4,0,5,0,4,0,3,0,2,0,1),toString)),
#x_text = c(8,12,18,22,28,32,38,42,48,52,58,62,68,72,78,82,88,92),
x_text = c(8.5,11.5,18.5,21.5,28.5,31.5,38.5,41.5,48.5,51.5,58.5,61.5,68.5,71.5,78.5,81.5,88.5,91.5)+10,
y_text = rep(ytop - 9,18))
show.top.numbers <- geom_text(data=field.numbers.top.df, aes(x = x_text, y = y_text, label = textVals),
size = 6,col='white',family = ifelse('Century' %in% fonts(),windowsFont('Century'),'Impact'),angle = 180)
left.endzone.df <- data.frame(textVals = 'T E A M', x_left = 5, y_left = ytop/2)
show.left.endzone <- geom_text(data = left.endzone.df, aes(x = x_left, y = y_left,label = textVals),
size = 10, col = 'white', family = ifelse('Copperplate Gothic Bold' %in% fonts(),windowsFont('Copperplate Gothic Bold'),'Georgia'),angle = 90)
right.endzone.df <- data.frame(textVals = 'T E A M', x_right = 115, y_right = ytop/2)
show.right.endzone <- geom_text(data = right.endzone.df, aes(x = x_right, y = y_right,label = textVals),
size = 10, col = 'white', family = ifelse('Copperplate Gothic Bold' %in% fonts(),windowsFont('Copperplate Gothic Bold'),'Georgia'),angle = -90)
big_box <- data.frame(x_big_box_s = c(-1,-1,-1,121),
x_big_box_e = c(121,121,-1,121),
y_big_box_s = c(ytop+.25,ybot-.2,ybot-.2,ybot-.2),
y_big_box_e = c(ytop+.25,ybot-.2,ytop+.25,ytop+.25))
baseNFL <- ggplot(datapoly, aes(x = xg, y = yg)) +
geom_polygon(aes(group = id)) +
scale_fill_identity() +
labs(x='',y='') +
minor.field.lines +
hash.marks +
show.bot.numbers + show.top.numbers +
show.left.endzone + show.right.endzone +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank(),
legend.position = 'none') +
fieldLines +
geom_segment(data=big_box,aes(x=x_big_box_s,y=y_big_box_s,xend=x_big_box_e,yend=y_big_box_e),colour='black')
return(baseNFL)
}
baseNFLField()
noColor_baseNFLField()
# windowsFont('Century')
# windowsFont('Copperplate Gothic Bold')
| 3e90112284c2043f38b70dc3a84691eee2341fd3 | [
"R"
] | 28 | R | prestonbiro/BigDataBowl2020 | 5162c1407ac439797b02a50ea4fd64997589457a | 3743442cc3c835982865a7a3291599ef1151e6b1 |
refs/heads/master | <repo_name>apellis/manin_schechtman<file_sep>/ms.py
# =====================================================================================
# ms.py
# code related to Manin-Schechtman theory for arbitrary elements of S_n
# (c) <NAME>, 2013
# =====================================================================================
from symmetric.symmetric import read_comb_data, coxeter_to_one_line, \
one_line_to_coxeter, is_lex_less_than
from symmetric.config import comb_data
import math
from copy import copy
# =====================================================================================
# ===== CLASS: MCGraph
# =====================================================================================
def diam(n):
"""
Returns a decent matplotlib width/height for a graph with n nodes.
"""
return n * (n-1) * (n-2) * (3*n-5) / 24.
def ms_braid_adjacent(node):
"""
Returns all nodes braid-adjacent to node.
"""
ret = set([])
for i in range(len(node) - 2):
if node[i] == node[i+2]:
if node[i+1] == node[i] + 1 or node[i+1] == node[i] - 1:
t = list(node)
t[i] = node[i+1]
t[i+1] = node[i]
t[i+2] = node[i+1]
ret.add(tuple(t))
return ret
def ms_commute_adjacent(node):
"""
Returns all nodes commute-adjacent to node.
"""
ret = set([])
for i in range(len(node) - 1):
if math.fabs(node[i] - node[i+1]) > 1:
t = list(node)
t[i] = node[i+1]
t[i+1] = node[i]
ret.add(tuple(t))
return ret
class MSGraph:
def __init__(self, one_line=None, coxeter_word=None, n=None, leave_empty=False):
"""
Builds the Manin-Schechtman graph for an element of S_n, given in
one-line or Coxeter word notation. If no n is given, the minimal
possible n is inferred and used.
"""
# sometimes we want an empty one
if leave_empty:
return
# empty containers for nodes and edges
self.nodes = set([])
self.braid_edges = set([])
self.commute_edges = set([])
# get the initial node; initialize self.n
if coxeter_word:
if not n:
n = 1
for i in coxeter_word:
if n < i + 1:
n = i + 1
self.nodes.add(tuple(coxeter_word))
self.one_line = coxeter_to_one_line(coxeter_word, n)
self.coxeter_length = len(coxeter_word)
elif one_line:
if not n:
n = len(one_line)
self.nodes.add(tuple(one_line_to_coxeter(one_line, n)))
self.one_line = one_line
self.coxeter_length = len(one_line_to_coxeter(one_line, n))
else:
return
self.n = n
# recursively fill the graph
done = 0
while not done:
done = 1
for node in self.nodes:
for x in ms_braid_adjacent(node):
if self.add_node(x):
done = 0
if self.add_braid_edge(node, x):
done = 0
for y in ms_commute_adjacent(node):
if self.add_node(y):
done = 0
if self.add_commute_edge(node, y):
done = 0
if not done:
break
def __str__(self):
ret = "=== (n = %s)\n" % self.n
ret += "=== nodes:\n"
for n in self.nodes:
ret += str(n) + "\n"
ret += "=== braid edges:\n"
for e in self.braid_edges:
ret += str(e) + "\n"
ret += "=== commute edges:\n"
for e in self.commute_edges:
ret += str(e) + "\n"
return ret
def copy(self):
"""
Returns a deep copy of self.
"""
g = MSGraph(leave_empty = True)
g.n = self.n
g.nodes = self.nodes.copy()
g.braid_edges = self.braid_edges.copy()
g.commute_edges = self.commute_edges.copy()
g.one_line = self.one_line
g.coxeter_length = self.coxeter_length
return g
def add_node(self, x):
"""
Adds a node x.
"""
if tuple(x) not in self.nodes:
self.nodes.add(tuple(x))
return True
else:
return False
def add_braid_edge(self, x, y):
"""
Adds a braid-edge from x to y.
"""
if (tuple(x), tuple(y)) in self.braid_edges:
return False
elif (tuple(y), tuple(x)) in self.braid_edges:
return False
else:
self.braid_edges.add((tuple(x), tuple(y)))
return True
def add_commute_edge(self, x, y):
"""
Adds a commute-edge from x to y.
"""
if (tuple(x), tuple(y)) in self.commute_edges:
return False
elif (tuple(y), tuple(x)) in self.commute_edges:
return False
else:
self.commute_edges.add((tuple(x), tuple(y)))
return True
def is_node(self, x):
"""
Returns True/False according to whether x is a node.
"""
if tuple(x) in self.nodes:
return True
else:
return False
def is_braid_edge(self, x, y):
"""
Returns True/False according to whether x, y are connected by a
braid-edge.
"""
if (tuple(x), tuple(y)) in self.braid_edges:
return True
elif (tuple(y), tuple(x)) in self.braid_edges:
return True
else:
return False
def is_commute_edge(self, x, y):
"""
Returns True/False according to whether x, y are connected by a
commute-edge.
"""
if (tuple(x), tuple(y)) in self.commute_edges:
return True
elif (tuple(y), tuple(x)) in self.commute_edges:
return True
else:
return False
def braid_adjacent_to(self, x):
"""
Returns all nodes connected to x by a braid-edge.
"""
ret = set([])
for e in self.braid_edges:
if e[0] == tuple(x):
ret.add(e[1])
elif e[1] == tuple(x):
ret.add(e[0])
return ret
def commute_adjacent_to(self, x):
"""
Returns all nodes connected to x by a commute-edge.
"""
ret = set([])
for e in self.commute_edges:
if e[0] == tuple(x):
ret.add(e[1])
elif e[1] == tuple(x):
ret.add(e[0])
return ret
def all_adjacent_to(self, x):
"""
Returns all nodes adjacent to node .
"""
return self.braid_adjacent_to(x) | self.commute_adjacent_to(x)
def delete_node(self, x):
"""
Delete node x.
"""
if tuple(x) in self.nodes:
self.nodes.remove(tuple(x))
new_braid_edges = set([])
for e in self.braid_edges:
if e[0] != tuple(x) and e[1] != tuple(x):
new_braid_edges.add(e)
self.braid_edges = new_braid_edges
new_commute_edges = set([])
for e in self.commute_edges:
if e[0] != tuple(x) and e[1] != tuple(x):
new_commute_edges.add(e)
self.commute_edges = new_commute_edges
def number_of_commute_moves(self, x, y):
"""
Returns, mod 2, the number of commute moves to get from node x to
node y.
"""
if tuple(x) not in self.nodes or tuple(y) not in self.nodes:
print "ERROR: passed a non-node to MSGraph.number_of_commute_moves()"
if tuple(x) == tuple(y):
return 0
g = self.copy()
g.delete_node(x)
looked_any = 0
for z in self.braid_adjacent_to(x):
looked_any = 1
r = g.number_of_commute_moves(z, y)
if r != None:
return r % 2
for z in self.commute_adjacent_to(x):
looked_any = 1
r = g.number_of_commute_moves(z, y)
if r != None:
return (r + 1) % 2
if not looked_any:
# we ended up at an isolated node
return None
# print "ERROR in MSGraph.number_of_commute_moves()", x, y
return None
def display_graph(self, filename=None):
"""
Displays (using matplotlib, networkx) the graph.
"""
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
for x in self.nodes:
G.add_node(x)
for e in self.braid_edges:
G.add_edge(e[0], e[1])
G[e[0]][e[1]]['color'] = 'r'
G[e[0]][e[1]]['weight'] = 8
for e in self.commute_edges:
G.add_edge(e[0], e[1])
G[e[0]][e[1]]['color'] = 'b'
G[e[0]][e[1]]['weight'] = 8
pos = nx.spring_layout(G)
if diam(self.n) >= 6.:
fig = plt.figure(figsize=(5.*diam(self.n), 5.*diam(self.n))) # use figsize = (w, h) if needed
else:
fig = plt.figure(figsize=(6., 6.))
ax = fig.add_subplot(1, 1, 1)
ax.set_title("Manin-Schechtman graph for w = " + str(self.one_line))
ax.set_xticks([])
ax.set_yticks([])
nx.draw_networkx_nodes(G, pos, node_color='w', ax=ax, node_shape='o', node_size=500)
nx.draw_networkx_labels(G, pos, ax=ax, font_size=14, font_weight='bold')
nx.draw_networkx_edges(G, pos, edgelist=self.braid_edges, edge_color='#ff5555', width=5., ax=ax)
nx.draw_networkx_edges(G, pos, edgelist=self.commute_edges, edge_color='#5555ff', width=5., ax=ax)
if filename:
plt.savefig(filename)
else:
plt.show()
def lex_min_node(self):
"""
Returns the lexicographically minimal node.
"""
ret = None
for node in self.nodes:
if not ret:
ret = node
elif is_lex_less_than(node, ret):
ret = node
return ret
def lex_max_node(self):
"""
Returns the lexicographically maximal node.
"""
ret = None
for node in self.nodes:
if not ret:
ret = node
elif is_lex_less_than(ret, node):
ret = node
return ret
# =====================================================================================
# =====================================================================================
if __name__ == '__main__':
import networkx as nx
import matplotlib.pyplot as plt
comb_data = {}
read_comb_data(compositions_filename='../symmetric/pickle/compositions.pickle',
permutations_filename='../symmetric/pickle/permutations.pickle',
coxeter_expressions_filename='../symmetric/pickle/coxeter_expressions.pickle')
for n in range(2, 6):
for w in comb_data['permutations'][n]:
print w
g = MSGraph(one_line = tuple(w))
sw = ""
for i in w:
sw += str(i)
g.display_graph(filename='viz/A' + str(n-1) + '/' + sw + '.png')
<file_sep>/README.md
manin-schechtman
================
Code for creating and navigating Manin-Schechtman graphs for arbitrary elements of the symmetric group | 2c40ef3a869e68f0016ff214768d6b2234841bc1 | [
"Markdown",
"Python"
] | 2 | Python | apellis/manin_schechtman | 0d402d62fd434740fb51a20220309277275f6145 | 6344e518842a2b71629cd693d7006330f85b7fbf |
refs/heads/master | <file_sep>//
// MemeTableViewController.swift
// MemeEditorV2
//
// Created by <NAME> on 7/26/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class MemeTableViewController: UITableViewController {
// MARK: properties
var data: [Meme] {
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
return appDelegate.memeArray
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonTapped))
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Recent Memes"
}
@objc func addButtonTapped() {
let controller: MemeEditorViewController
controller = storyboard?.instantiateViewController(withIdentifier: "MemeEditorViewController") as! MemeEditorViewController
present(controller, animated: true, completion: nil)
}
//MARK: delegate functions
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let memeDetailViewController = self.storyboard!.instantiateViewController(withIdentifier: "MemeDetail") as! MemeDetailViewController
memeDetailViewController.memeImage = data[indexPath.row].memedImage
self.navigationController?.pushViewController(memeDetailViewController, animated: true)
}
// MARK: data source functions
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MemeTableCell") as! MemeTableViewCell
cell.topLabel.text = data[indexPath.row].topText
cell.bottomLabel.text = data[indexPath.row].bottomText
cell.cellImage.image = data[indexPath.row].pic
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(120)
}
}
class MemeTableViewCell: UITableViewCell {
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var bottomLabel: UILabel!
@IBOutlet weak var cellImage: UIImageView!
}
<file_sep>//
// MemeDetailViewController.swift
// MemeEditorV2
//
// Created by <NAME> on 7/27/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class MemeDetailViewController: UIViewController {
@IBOutlet weak var imageViewForMeme: UIImageView!
var memeImage: UIImage!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
imageViewForMeme.image = memeImage
self.title = "Meme"
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.tabBarController?.tabBar.isHidden = false
}
}
<file_sep>//
// MemeCollectionViewController.swift
// MemeEditorV2
//
// Created by <NAME> on 7/26/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class MemeCollectionViewController: UICollectionViewController {
// MARK: properties
@IBOutlet var flowLayout: UICollectionViewFlowLayout!
var data: [Meme] {
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
return appDelegate.memeArray
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Recent Memes"
let space: CGFloat = 3.0
let dimension = (view.frame.size.width - (2*space)) / 3.0 //3 items per row
//set spacing between items
flowLayout.minimumInteritemSpacing = space
//set spacing between rows
flowLayout.minimumLineSpacing = space
//set size of items, which are dependent on the size of the main view
flowLayout.itemSize = CGSize(width: dimension, height: dimension)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonTapped))
self.collectionView?.reloadData()
}
@objc func addButtonTapped() {
let controller: MemeEditorViewController
controller = storyboard?.instantiateViewController(withIdentifier: "MemeEditorViewController") as! MemeEditorViewController
present(controller, animated: true, completion: nil)
}
//MARK: delegate properties
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let memeDetailViewController = self.storyboard!.instantiateViewController(withIdentifier: "MemeDetail") as! MemeDetailViewController
memeDetailViewController.memeImage = data[indexPath.row].memedImage
self.navigationController?.pushViewController(memeDetailViewController, animated: true)
}
// MARK: data source properties
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MemeCollectionCell", for: indexPath) as! MemeCollectionViewCell
cell.collectionCellImage.image = data[indexPath.row].pic
return cell
}
}
class MemeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var collectionCellImage: UIImageView!
}
<file_sep>//
// ViewController.swift
// MemeEditorV2
//
// Created by <NAME> on 7/26/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
class MemeEditorViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: properties
@IBOutlet weak var displayImage: UIImageView!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!
@IBOutlet weak var takePictureButton: UIBarButtonItem!
@IBOutlet weak var cancelButton: UIBarButtonItem!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var topToolBar: UIToolbar!
@IBOutlet weak var bottomToolBar: UIToolbar!
//MARK: attritubtes for text fields
let memeTextAttributes: [String: Any] = [
NSAttributedStringKey.strokeColor.rawValue: UIColor.black,
NSAttributedStringKey.foregroundColor.rawValue: UIColor.white,
NSAttributedStringKey.font.rawValue: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSAttributedStringKey.strokeWidth.rawValue: -3
]
//MARK: lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Meme Editor"
//shareButton not enabled till user has created a meme image
shareButton.isEnabled = false
//custimize text fields and set text field delegates
setTextFieldAttributesAndDelegate(text: "BOTTOM", textField: bottomTextField)
setTextFieldAttributesAndDelegate(text: "TOP", textField: topTextField)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//disable take picture button if device - such as the simulator - does not have a camera
takePictureButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
//wnat to know when keyboard will appear in order to move the view up so the appearance of the keyboard doesn't cover the bottom textfield
subscribeToKeyboardNotifications()
self.tabBarController?.tabBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
self.tabBarController?.tabBar.isHidden = false
}
//MARK: textfields and keyboard functions
func setTextFieldAttributesAndDelegate(text: String, textField: UITextField) {
textField.defaultTextAttributes = memeTextAttributes
textField.text = text
textField.backgroundColor = .clear
textField.autocapitalizationType = .allCharacters
textField.textAlignment = .center
textField.borderStyle = .none
textField.delegate = self
}
//keyboard will disappear if user hits Return key on keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
//default text will disappear when user starts to edit textfield
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text == "TOP" || textField.text == "BOTTOM" {
textField.text = ""
}
}
//MARK: keyboard notification methods
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
//only want to move view if the bottom text field is being edited, not the top since the keyboard only blocks the bottom textfield
if bottomTextField.isFirstResponder {
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
@objc func keyboardWillHide(_ notification: Notification) {
view.frame.origin.y = 0
}
func getKeyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
//MARK: UIImagePickerController delegate methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
displayImage.image = image
displayImage.contentMode = .scaleAspectFit
//only want share button to be enabled after user selects a picture
shareButton.isEnabled = true
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
//MARK: IBAction functions
@IBAction func shareButtonPressed(_ sender: Any) {
//generate a memed image
let memedImage = generateMemedImage()
//define an instance of the ActivityViewController and pass it a meme as an activity item
let controller = UIActivityViewController(activityItems: [memedImage], applicationActivities: nil)
//present the ActivityViewController
present(controller, animated: true, completion: nil)
controller.completionWithItemsHandler = {
(activityType: UIActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) in
if completed {
self.save()
self.dismissView()
}
}
}
@IBAction func cancelButtonPressed(_ sender: Any) {
dismissView()
}
@IBAction func cameraButtonPressed(_ sender: Any) {
setupImagePickerController(sourceType: .camera)
}
@IBAction func albumButtonPressed(_ sender: Any) {
setupImagePickerController(sourceType: .photoLibrary)
}
//MARK: meme functions
func generateMemedImage() -> UIImage {
//hide toolbars
hideTopAndBottomToolBars(shouldHide: true)
//render view to an image
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
//show toolbars
hideTopAndBottomToolBars(shouldHide: false)
return memedImage
}
func save() {
let memedImage = generateMemedImage()
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, pic: displayImage.image!, memedImage: memedImage)
//save meme in array created in AppDelegate
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.memeArray.append(meme)
}
//MARK: function to reduce repetive code
func setupImagePickerController(sourceType: UIImagePickerControllerSourceType) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = sourceType
present(pickerController, animated: true, completion: nil )
}
//called when user hits cancel button or within the share function function
func dismissView() {
dismiss(animated: true, completion: nil)
}
func hideTopAndBottomToolBars(shouldHide: Bool) {
topToolBar.isHidden = shouldHide
bottomToolBar.isHidden = shouldHide
}
}
| be489400c01d4746b34a4a311cd6c79f576f4897 | [
"Swift"
] | 4 | Swift | JMallian/MemeEditorV2 | 1e60670e6ca636021675834b0c33f60188b70fdc | 4cae2a7c483a9b656d1e45b8121fdc9ab96d27e8 |
refs/heads/master | <file_sep>import pymongo
from pymongo import MongoClient
import twitter_credential as tc
from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import tweepy
import csv
from collections import OrderedDict
client=MongoClient('localhost')
db = client.test_database
collection = db.test_collection
print(client)
auth =OAuthHandler(tc.consumer_token, tc.consumer_sec)
api = tweepy.API(auth)
tweedt=[]
date=[]
liked=[]
location=[]
handle=[]
desc=[]
follow=[]
d = OrderedDict()
jok=OrderedDict()
for tweet in tweepy.Cursor(api.search, q='#UiPath',since="2019-05-29").items():
follow.append(tweet.user.followers_count)
date.append(str(tweet.created_at))
tweedt.append(tweet.retweet_count)
liked.append(tweet.favorite_count)
handle.append(tweet.user.screen_name)
location.append(tweet.user.location)
desc.append(tweet.user.description)
result = { k:v for k,*v in zip(liked,handle,desc,date)}
test_database=db.test_database.insert_many(result)
k=0
with open('people5.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow("sorted by likes")
for i in sorted (result) :
if(k<5):
with open('sort_likes.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(str(result[i]).split(","))
# print(str(result[i]).split(","))
k=k+1
result = { k:v for k,*v in zip(date,handle,desc,date)}
k=0
with open('people5.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow("sorted by date")
for i in sorted (result) :
if(k<5):
with open('sort_date.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(str(result[i]).split(","))
# print(str(result[i]).split(","))
k=k+1
result = { k:v for k,*v in zip(tweedt,handle,desc,date)}
k=0
with open('people5.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow("sorted by retweet")
for i in sorted (result) :
if(k<5):
with open('sort_retweet.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(str(result[i]).split(","))
# print(str(result[i]).split(","))
# print ((i,result[i]))
k=k+1
result = { k:v for k,*v in zip(follow,handle,desc,date,location)}
k=0
with open('people5.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow("sorted by followers")
for i in sorted (result) :
if(k<5):
with open('sort_followers.csv', 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(str(result[i]).split(","))
# print(str(result[i]).split(","))
k=k+1
# test_database=db.test_database.insert_one(post)
# db.collection_names(include_system_collections=False) | 252b7d84dba300d0e0b39bf8c1e6a6a5e24b9ed4 | [
"Python"
] | 1 | Python | nithinaakash/pymongo | b12337e2af492318f5104858e561fb6cfa67c574 | 508ad8cc4c1d836dcf99be04a06bc99f7ee75f4a |
refs/heads/master | <repo_name>zoya-sh/TDD-Kata-FindAPerson<file_sep>/FindPersonTests.py
import unittest
from Crowdmap import Crowdmap
class FindPersonTests(unittest.TestCase):
def setUp(self):
self.crowdmap = Crowdmap(["I met Or A. at Chabad house Bangkok", "We found Or A. R.I.P at Langtang valley"
,"MissingCowboy","Lassy Come Home"])
def test_getAllPostsForName(self):
posts = self.crowdmap.get_all_posts_for("Or")
self.assertEquals(posts, ["I met Or A. at Chabad house Bangkok", "We found Or A. R.I.P at Langtang valley"])
def test_getAllPostForMissingName(self):
posts = self.crowdmap.get_all_posts_for("Joe")
self.assertEquals([], posts)
def test_existingLocationInformationReturnsTrue(self):
location_exist = self.crowdmap.is_location_for_name("Or")
self.assertTrue(location_exist)
def test_isMapConsistence(self):
consistence = self.crowdmap.is_map_consistence("Or")
self.assertTrue(consistence)
if __name__ == '__main__':
unittest.main()<file_sep>/Crowdmap.py
class Crowdmap(object):
def __init__(self, init_list):
self.list = init_list
def get_all_posts_for(self, name):
return [post for post in self.list if post.find(name) != -1]
def is_location_for_name(self, name):
posts = [post for post in self.list if post.find(name) != -1 and post.find('at') != -1]
return len(posts) != 0
def is_map_consistence(self, name):
existsInMap = False
for i in self.list:
if i.find(name) != -1 and existsInMap:
return False
if i.find(name) != -1:
existInMap = True
return True | 710319f509ddc6feb76eefebaacd79a2b9d48176 | [
"Python"
] | 2 | Python | zoya-sh/TDD-Kata-FindAPerson | 2eac31686588ebb197b1afe479001ba116216abb | bce2e67432462dc8404c7d57d2043a053eef15bb |
refs/heads/master | <file_sep>import './index.pug'
import * as Reveal from 'reveal.js'
import 'reveal.js/css/reveal.css'
import 'reveal.js/css/theme/black.css'
import * as hljs from 'highlight.js'
import 'highlight.js/styles/gruvbox-dark.css'
Reveal.initialize({
});
hljs.initHighlightingOnLoad();
| dc9f3d724132da58e67d8038044e31437cb4c708 | [
"TypeScript"
] | 1 | TypeScript | deemson-talks/git-rebase-flow | fbe424a40d40bb3bf7cf8a5d4a755b6d6df50f5a | f211b8ab2fbe0b7f817ba89e544d8c5243b763fc |
refs/heads/master | <repo_name>cimm/pvpulse<file_sep>/pvpulse.ino
// PvPulse
// Sends an MQTT message on each pulse generated by the kilowatt meter.
// Will reconnect via ethernet to the MQTT broker if disconnected (but
// will only learn it’s disconnected after a pulse).
// The onboard LED indicates if the board is connected or not.
#include <Ethernet.h>
#include <ArduinoMqttClient.h>
// Configurable variables
const byte interruptPin = 2; // pin that detects pulse
const byte ledPin = 9; // built-in Arduino Ethernet LED
byte mac[6] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // see sticker on Arduino Ethernet
const char broker[19] = "test.mosquitto.org";
int port = 1883; // for MQTT broker
const char topic[17] = "home/solar/pulse"; // MQTT topic to publish to
// Internal variables
EthernetClient ethClient;
MqttClient mqttClient(ethClient);
bool isConnected = false;
void setup() {
Serial.begin(9600);
Serial.println("+ Booting");
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), pulseDetected, RISING);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (isConnected) {
mqttClient.poll(); // keep alive
} else {
if (connect()) {
Serial.println("+ Ethernet & MQTT connected");
} else {
Serial.println("! Ethernet or MQTT connection failed");
return;
}
}
delay(30000);
}
// Sends an MQTT message if the interruptPin
// detected a voltage increase
void pulseDetected() {
Serial.println("+ Pulse detected");
if (isConnected && publish("1")) {
Serial.println("+ MQTT message sent");
} else {
Serial.println("! MQTT message failed");
}
}
// Keeps track of connection state and turns
// status LED on or off
void setConnected(bool status) {
isConnected = status;
digitalWrite(ledPin, status);
}
// Connect to ethernet & an MQTT broker,
// return true on success, false on failure
bool connect() {
if (Ethernet.begin(mac)) {
delay(4000); // needs time to connect
} else {
setConnected(false);
return false;
}
if (!mqttClient.connect(broker, port)) {
setConnected(false);
return false;
}
setConnected(true);
return true;
}
// Send an MQTT message to an already connected broker,
// return true on success, false on failure
bool publish(String payload) {
int qos = 2; // receive confirmation from broker
if (mqttClient.beginMessage(topic, payload.length(), false, qos) != 1) {
setConnected(false);
return false;
}
if (mqttClient.print(payload) != 1) {
setConnected(false);
return false;
}
if (mqttClient.endMessage() != 1) {
setConnected(false);
return false;
}
return true;
}
| 764e4556cff300dca59f82b458f6c17aacc5f702 | [
"C++"
] | 1 | C++ | cimm/pvpulse | 0793afdc2f54ef18cb4778c6a464c1347c282a15 | 94cf7270d16bab420c33ea4c36ded31132efa3e5 |
refs/heads/master | <repo_name>douglas20345/linux-tibia-ip-changer<file_sep>/setup.h
#ifndef SETUP_H
#define SETUP_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
class Setup
{
public:
bool saveSetup(string, string);
string loadSetupValue(string);
};
#endif //SETUP_H
<file_sep>/languages.h
#ifndef LANGUAGES_H
#define LANGUAGES_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
class Languages
{
public:
vector<string> getLanguagesFiles();
string loadLanguage(string);
vector<string> getLanguagesList();
int count;
};
#endif //LANGUAGES_H
<file_sep>/change.h
#ifndef CHANGE_H
#define CHANGE_H
#include <fstream>
#include <sstream>
#include <cstring>
#include <iomanip>
#include <errno.h>
#include <vector>
const char RSA_KEY[]="109120132967399429278860960508995541528237502902798129123468757937\
266291492576446330739696001110603907230888610072655818825358503429057592827629436\
413108566029093628212635953836686562675849720620786279431090218017681061521755056\
710823876476444260558147179707119674283982419152118103759076030616683978566631413";
class Change
{
const unsigned int pid;
public:
Change(int);
bool changeIP(std::string, int, std::string);
bool isCorrectVersion(std::string);
};
#endif // CHANGE_H
<file_sep>/network.h
#ifndef NETWORK_H
#define NETWORK_H
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#define GOOGLECODE "code.google.com"
#define ACTUALVERSION "1.6"
#define CODENAME "eta"
class Network
{
public:
std::string getIpCangerFromWebSite();
};
#endif // NETWORK_H
<file_sep>/history.cpp
#include "history.h"
string History::getUserName(){
string data;
char buffer[10];
FILE *stream = popen("echo $USERNAME", "r");
while(fgets(buffer, 10, stream) != NULL)
data.append(buffer);
pclose(stream);
return data.substr(0, data.size()-1);
}
bool History::saveHistory(string new_host){
ifstream file(string("/home/" + getUserName() +"/.linux-ip-changer/history").c_str());
if(!file.is_open())
return false;
vector<string>out;
string line;
while(getline(file, line)){
if(line != new_host)
out.push_back(line);
}
out.insert(out.begin(), new_host);
ofstream plik(string("/home/" + getUserName() +"/.linux-ip-changer/history").c_str());
for(int i = 0; i < int(out.size()); i++)
plik<<out.at(i)<<endl;
plik.close();
return true;
}
int History::getLinesCount(){
int i = 0;
ifstream file(string("/home/" + getUserName() +"/.linux-ip-changer/history").c_str());
if(!file.is_open())
return i;
string line;
while(getline(file, line))
i++;
return i;
}
vector<string> History::getHistory(){
vector<string>tab;
ifstream file(string("/home/" + getUserName() +"/.linux-ip-changer/history").c_str());
if(!file.is_open())
return tab;
string line;
while(getline(file, line))
tab.push_back(line);
return tab;
}
<file_sep>/languages.cpp
#include "languages.h"
#include "history.h"
vector<string> Languages::getLanguagesFiles(){
History h;
vector<string>tab;
DIR *dp;
struct dirent *dirp;
if((dp = opendir(string("/home/" + h.getUserName() +"/.linux-ip-changer/Languages").c_str())) == NULL) {
cout << "Error opening " << "/home/"<< h.getUserName() <<"/.linux-ip-changer/Languages" << endl;
return tab;
}
while((dirp = readdir(dp)) != NULL){
string s = string(dirp->d_name);
if(s.substr(0,1) != "."){
if(s.find(".lang"))
tab.push_back(s);
}
}
closedir(dp);
count = int(tab.size());
return tab;
}
string Languages::loadLanguage(string lname){
History h;
vector<string>name;
name = getLanguagesFiles();
for(int i = 0; i < name.size(); i++){
ifstream file(string("/home/" + h.getUserName() +"/.linux-ip-changer/Languages/" + name.at(i)).c_str());
if(!file.is_open())
return "";
string line, tmp;
bool b = false;
while(getline(file, line)){
if(line.substr(0,1) != "#"){
if(lname == line)
b = true;
tmp += line + ",";
}
}
if(b)
return tmp;
}
}
vector<string> Languages::getLanguagesList(){
History h;
vector<string>name, tab;
name = getLanguagesFiles();
for(int i = 0; i < name.size(); i++){
ifstream file(string("/home/" + h.getUserName() +"/.linux-ip-changer/Languages/" + name.at(i)).c_str());
if(!file.is_open())
return tab;
string line;
while(getline(file, line)){
if(line.substr(0,1) != "#"){
tab.push_back(line);
break;
}
}
}
return tab;
}
<file_sep>/process.h
#ifndef PROCESS_H
#define PROCESS_H
#include <cstring>
#include <string>
#include <sys/ptrace.h>
#include <sys/wait.h>
class Process
{
const unsigned int pid;
public:
Process(int);
bool readMemory(unsigned, char*, unsigned);
bool writeMemory(unsigned, const char*, unsigned);
std::string readClientVersion(unsigned addr);
};
#endif //PROCESS_H
<file_sep>/configure
#!/bin/bash
gpp=$"g++"
if [ "$1" == "--with-gui" ]
then
echo "CC=g++
CFLAGS=-O2 \$(shell wx-config --cxxflags --unicode=yes) -D__GUI__
LDFLAGS=\$(shell wx-config --libs --unicode=yes) -D__GUI__
SOURCES=main.cpp change.cpp process.cpp tibiapid.cpp gui.cpp history.cpp languages.cpp setup.cpp network.cpp
OBJECTS=\$(SOURCES:.cpp=.o)
EXECUTABLE=change
all: \$(SOURCES) \$(EXECUTABLE)
\$(EXECUTABLE): \$(OBJECTS)
\$(CC) \$(LDFLAGS)\$(OBJECTS) -o \$@
mv *.o ./Objects
.cpp.o:
\$(CC) -c \$< \$(CFLAGS) -o \$@
clean:
rm -rf ./Objects/*.o \$(EXECUTABLE)
install:
mv \$(EXECUTABLE) /usr/local/bin
cp -R ./Languages /home/$USER/.linux-ip-changer
uninstall:
rm -rf /usr/local/bin/\$(EXECUTABLE)" > Makefile
echo "Configured with GUI & Console mode!"
else
echo "CC=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=main.cpp change.cpp process.cpp tibiapid.cpp history.cpp
OBJECTS=\$(SOURCES:.cpp=.o)
EXECUTABLE=change
all: \$(SOURCES) \$(EXECUTABLE)
\$(EXECUTABLE): \$(OBJECTS)
\$(CC) \$(LDFLAGS) \$(OBJECTS) -o \$@
mv *.o ./Objects
.cpp.o:
\$(CC) \$(CFLAGS) \$< -o \$@
clean:
rm -rf ./Objects/*.o \$(EXECUTABLE)
install:
mv \$(EXECUTABLE) /usr/local/bin
uninstall:
rm -rf /usr/local/bin/\$(EXECUTABLE)" > Makefile
echo "Configured with Console mode!"
fi
<file_sep>/change.cpp
#include <iostream>
#include <cstdlib>
#include "process.h"
#include "change.h"
#include "clientsversions.h"
Change::Change(int PID) :
pid(PID)
{}
std::string lastIp;
bool Change::changeIP(std::string IP, int port, std::string v){
errno=0;
Process process(pid);
if(lastIp.size() < 2)
lastIp = "tib";
bool ver = false;
int LoginServersStart, ServerStep, PortStep, RSA, ServerCount;
for(int i = 0; i < int(sizeof(clients)/sizeof(clients[1])); i++){
if(v == "Auto")
ver = isCorrectVersion(clients[i][0]);
if(clients[i][0] == v || ver){
std::istringstream ilss(clients[i][1]);
ilss >> std::setbase(0) >> LoginServersStart;
std::istringstream iss(clients[i][2]);
iss >> std::setbase(0) >> ServerStep;
std::istringstream ips(clients[i][3]);
ips >> std::setbase(0) >> PortStep;
std::istringstream irsa(clients[i][4]);
irsa >> std::setbase(0) >> RSA;
ServerCount = atoi(clients[i][5].c_str());
if(!isCorrectVersion(clients[i][0]))
return false;
break;
}
}
bool result=process.writeMemory(RSA, RSA_KEY, strlen(RSA_KEY)+1);
if(!result||errno)
return false;
for(unsigned s=0;s<unsigned(ServerCount);s++){
result=process.writeMemory(LoginServersStart+s*ServerStep,
IP.c_str(), IP.size()+1);
if(!result||errno)
return false;
}
for(unsigned s=0;s<unsigned(ServerCount);s++){
result=process.writeMemory(LoginServersStart+s*ServerStep+PortStep,
(char*)&port, 4);
if(!result||errno)
return false;
}
lastIp = IP.substr(0, 3);
return true;
}
bool Change::isCorrectVersion(std::string v){
Process process(pid);
int LoginServersStart;
for(int i = 0; i < int(sizeof(clients)/sizeof(clients[1])); i++){
if(clients[i][0] == v){
std::istringstream ilss(clients[i][1]);
ilss >> std::setbase(0) >> LoginServersStart;
std::string s = process.readClientVersion(LoginServersStart);
if(s == "tib" || s == "log" || s == lastIp)
return true;
else
return false;
}
}
return false;
}
<file_sep>/tibiapid.h
#ifndef PID_H
#define PID_H
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#ifdef __GUI__
#include <wx/arrstr.h>
#include <wx/string.h>
#endif
class TibiaPid
{
public:
std::string name;
int getTibiaPidConsole();
#ifdef __GUI__
wxArrayString getTibiaPidGUI();
#endif
};
#endif //PID_H
<file_sep>/network.cpp
#include "network.h"
std::string Network::getIpCangerFromWebSite(){
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1)
return "";
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(80);
struct hostent *h = gethostbyname(GOOGLECODE);
if(!h)
return "";
memcpy(&sa.sin_addr.s_addr, h->h_addr_list[0], 4);
if(connect(sock, (struct sockaddr*)&sa, sizeof(struct sockaddr)) == -1){
return "";
}
char Packet[] =
"GET /p/linux-tibia-ip-changer/wiki/Changelog HTTP/1.1\r\n"
"Host: " GOOGLECODE "\r\n"
"\r\n";
int rtn = 0;
rtn = send(sock, Packet, sizeof(Packet)-1, 0);
if(rtn == -1)
return "";
char buf[100];
std::string Buffer;
while(true){
rtn = recv(sock, buf, 100, 0);
Buffer += buf;
if(Buffer.find("</body>") != std::string::npos)
break;
}
std::string str("Actual");
Buffer.erase(0, Buffer.find("Actual")+7);
Buffer.erase(Buffer.find("Actual")+4, Buffer.length());
close(sock);
return Buffer;
}
<file_sep>/process.cpp
#include "process.h"
Process::Process(int PID) :
pid(PID)
{}
bool Process::readMemory(unsigned addr, char *data, unsigned size){
if(ptrace(PTRACE_ATTACH, pid, 0, 0)!=0)
return false;
wait(0);
for(unsigned i=0;i<size;i+=sizeof(int)){
int buff;
buff=ptrace(PTRACE_PEEKDATA, pid, addr+i, 0);
memcpy(data+i, &buff, sizeof(int));
}
if(ptrace(PTRACE_DETACH, pid, 0, 0)!=0)
return false;
return true;
}
bool Process::writeMemory(unsigned addr, const char *data, unsigned size){
if(ptrace(PTRACE_ATTACH, pid, 0, 0)!=0)
return false;
wait(0);
for(unsigned i=0;i<size;i+=sizeof(int)){
int buff;
memcpy(&buff, data+i, sizeof(int));
ptrace(PTRACE_POKEDATA, pid, addr+i, buff);
}
if(ptrace(PTRACE_DETACH, pid, 0, 0)!=0)
return false;
return true;
}
std::string Process::readClientVersion(unsigned addr){
char data[4];
bool ret = readMemory(addr, data, 4);
if(!ret)
return "";
std::string ver = data;
ver = ver.substr(0, 3);
return ver;
}
<file_sep>/gui.cpp
#include "gui.h"
#include "change.h"
#include "tibiapid.h"
#include "history.h"
#include "languages.h"
#include "setup.h"
#include "clientsversions.h"
#include "network.h"
#include "ico.xpm"
#include "refresh.xpm"
#include "download.xpm"
Setup s;
History h;
Languages lang;
std::vector<wxString>wxLang;
BEGIN_EVENT_TABLE(Panel,wxFrame)
EVT_CLOSE(Panel::OnClose)
EVT_MENU(wxID_EXIT, Panel::PanelClickEvents)
EVT_MENU(wxID_SETUP, Panel::PanelClickEvents)
EVT_MENU(MENU_INFO, Panel::PanelClickEvents)
EVT_MENU(MENU_CLEAR_HISTORY, Panel::PanelClickEvents)
EVT_BUTTON(wxID_EXIT, Panel::PanelClickEvents)
EVT_BUTTON(BUTTON_TO_TRAY, Panel::PanelClickEvents)
EVT_BUTTON(BUTTON_REFRESH, Panel::PanelClickEvents)
EVT_COMBOBOX(CB_IP, Panel::comboSelect)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(MyTaskBarIcon, wxTaskBarIcon)
EVT_TASKBAR_LEFT_DCLICK(MyTaskBarIcon::TrayLeftClick)
EVT_MENU(wxID_EXIT, MyTaskBarIcon::TrayClickEvents)
EVT_MENU(MENU_O_M, MyTaskBarIcon::TrayClickEvents)
END_EVENT_TABLE()
MyTaskBarIcon::MyTaskBarIcon(Panel* frame)
: wxTaskBarIcon()
, frame(frame)
{
}
MyDialog::MyDialog(Panel* frame)
: wxDialog(frame, wxID_ANY, wxLang.at(21), wxDefaultPosition, wxSize(160, 130))
, frame(frame)
{
wxPanel *p = new wxPanel(this, wxID_ANY, wxPoint(-1, -1), wxSize(130, 130));
(void) new wxStaticText(p, wxID_ANY, wxLang.at(22), wxPoint(5, 5), wxSize(160, 25));
wxString tab[lang.count];
vector<string>z;
z = lang.getLanguagesList();
for(int i = 0; i < z.size(); i++){
wxString wxs(z.at(i).c_str(), wxConvUTF8);
tab[i] = wxs;
}
langCombo = new wxComboBox(p, wxID_ANY, tab[0], wxPoint(5, 25), wxSize(80, 25), WXSIZEOF(tab), tab, wxCB_READONLY);
(void) new wxButton(p, BUTTON_OK, wxT("Ok"), wxPoint(125, 95), wxSize(30, 25));
Connect(BUTTON_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(MyDialog::Ok));
}
UpDialog::UpDialog(Panel* frame)
: wxDialog(frame, wxID_ANY, wxT("Update"), wxDefaultPosition, wxSize(200, 170), wxDEFAULT_DIALOG_STYLE | wxSTAY_ON_TOP)
, frame(frame)
{
wxPanel *p = new wxPanel(this, wxID_ANY, wxPoint(-1, -1), wxSize(200, 170));
(void) new wxStaticBitmap(p, wxID_ANY, wxBitmap(download_xpm), wxPoint(5, 5), wxSize(100, 100));
(void) new wxStaticText(p, wxID_ANY, wxT("Update!"), wxPoint(125, 35), wxSize(50, 25));
(void) new wxStaticText(p, wxID_ANY, wxLang.at(27), wxPoint(5, 115), wxSize(195, 50));
link = new wxHyperlinkCtrl(p, HYPERLINK, wxLang.at(28), wxT("http://code.google.com/p/linux-tibia-ip-changer/downloads/list"), wxPoint(35, 147), wxDefaultSize, wxHL_DEFAULT_STYLE, wxHyperlinkCtrlNameStr);
Connect(link->GetId(), wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler(UpDialog::useLink));
}
Panel::Panel(const wxString& title)
: wxFrame(NULL, wxID_ANY, title, wxPoint(-1, -1), wxSize(350, 170))
{
panel = new wxPanel(this, wxID_ANY, wxPoint(-1, -1), wxSize(350, 170));
SetMinSize(wxSize(350, 170));
SetMaxSize(wxSize(350, 170));
std::string tmp;
std::string st = lang.loadLanguage(s.loadSetupValue("lang"));
for(int i = 0; i < st.size(); i++){
std::string str;
str += st.at(i);
if(str != ",")
tmp += str;
else{
wxString wxs(tmp.c_str(), wxConvUTF8);
wxLang.push_back(wxs);
tmp.clear();
}
str.clear();
}
int ile = int(sizeof(clients)/sizeof(clients[1]));
wxString tab[ile+1];
tab[0] = wxT("Auto");
for(int i = 0; i < ile; i++){
wxString wxs(clients[i][0].insert(1, ".").c_str(), wxConvUTF8);
tab[i+1] = wxs;
}
tibiaversion = new wxComboBox(panel, -1, tab[0], wxPoint(274, 60), wxSize(65, 25), WXSIZEOF(tab), tab, wxCB_READONLY);
statusbar = new wxStatusBar(this, wxID_ANY);
statusbar->SetFieldsCount(1);
int stat[1];
stat[0] = -1;
statusbar->SetStatusWidths(1,stat);
SetStatusBar(statusbar);
(void) new wxStaticText(panel, wxID_ANY, wxLang.at(1), wxPoint(5, 5), wxSize(350, 25));
(void) new wxStaticText(panel, wxID_ANY, wxLang.at(2), wxPoint(286, 5), wxSize(350, 25));
(void) new wxStaticText(panel, wxID_ANY, wxLang.at(3), wxPoint(272, 47), wxSize(350, 25));
(void) new wxStaticText(panel, wxID_ANY, wxLang.at(25), wxPoint(5, 47), wxSize(350, 25));
vector<string>z;
z = h.getHistory();
wxString tabb[z.size()];
for(int i = 0; i < z.size(); i++){
wxString wxs(z[i].c_str(), wxConvUTF8);
tabb[i] = wxs;
}
ip = new wxComboBox(panel, CB_IP, wxT(""), wxPoint(5, 20), wxSize(264, 25), WXSIZEOF(tabb), tabb);
port = new wxSpinCtrl(panel, wxID_ANY, wxT("7171"), wxPoint(287, 20), wxSize(54, 25), wxSP_ARROW_KEYS, 1000, 9999, 7171);
TibiaPid pid;
wxArrayString arr = pid.getTibiaPidGUI(), arrTmp;
if(arr.GetCount() != 0){
for(int i = 0; i < arr.GetCount(); i++)
arrTmp.Add(wxString(wxT("Tibia (") + arr[i] + wxT(")")));
}else
arrTmp.Add(wxLang.at(26));
process = new wxComboBox(panel, -1, arrTmp[0], wxPoint(5, 60), wxSize(215, 25), arrTmp, wxCB_READONLY);
wxMenuBar *menubar = new wxMenuBar;
wxMenu *file = new wxMenu;
file->Append(MENU_CLEAR_HISTORY, wxLang.at(4));
file->Append(wxID_SETUP, wxLang.at(5));
file->AppendSeparator();
file->Append(wxID_EXIT, wxLang.at(6));
menubar->Append(file, wxLang.at(7));
wxMenu *help = new wxMenu;
help->Append(MENU_INFO, wxLang.at(8));
menubar->Append(help, wxLang.at(9));
SetMenuBar(menubar);
trayIcon = new MyTaskBarIcon(this);
wxIcon icon(ico_xpm);
if(!trayIcon->SetIcon(icon, wxT("IP Changer")))
wxMessageBox(wxT("Could not set icon."));
(void) new wxButton(panel, BUTTON_CHANGE_IP, wxLang.at(10), wxPoint(60, 90), wxSize(90, 33));
Connect(BUTTON_CHANGE_IP, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Panel::PanelClickEvents));
(void) new wxButton(panel, BUTTON_TO_TRAY, wxLang.at(11), wxPoint(155, 90), wxSize(90, 33));
(void) new wxButton(panel, wxID_EXIT, wxLang.at(12), wxPoint(250, 90), wxSize(90, 33));
(void) new wxBitmapButton(panel, BUTTON_REFRESH, wxBitmap(refresh_xpm), wxPoint(236, 60), wxSize(25, 25), wxBU_TOP);
this->SetIcon(icon);
Centre();
Network n;
std::string socketinfo = n.getIpCangerFromWebSite();
if(socketinfo != ACTUALVERSION && socketinfo != ""){
wxDialog *dial = new UpDialog(this);
dial->Show();
}
}
void sendDialog(wxString str, long styles){
wxMessageDialog *dial = new wxMessageDialog(NULL, str, wxLang.at(24), styles);
dial->ShowModal();
}
void guiChangeIP(Panel *frame, int eventId){
TibiaPid pid;
int tpid = 0;
wxArrayString arr = pid.getTibiaPidGUI();
if(arr.GetCount() != 0){
int select = frame->process->GetCurrentSelection();
if(select == -1 || arr.GetCount() < select+1)
select = 0;
tpid = wxAtoi(arr[select]);
}
if(std::string(frame->process->GetValue().mb_str()).find("Tibia") == string::npos){
frame->statusbar->SetStatusText(wxLang.at(29),0);
if(eventId == MENU_CHANGE_IP)
sendDialog(wxLang.at(29), wxOK | wxICON_ERROR);
return;
}
if(tpid == 0){
frame->statusbar->SetStatusText(wxLang.at(16),0);
if(eventId == MENU_CHANGE_IP)
sendDialog(wxLang.at(16), wxOK | wxICON_ERROR);
return;
}
std::string sip = std::string(frame->ip->GetValue().mb_str());
int sport = frame->port->GetValue();
std::string client = std::string(frame->tibiaversion->GetValue().mb_str());
if(sip == ""){
frame->statusbar->SetStatusText(wxLang.at(17),0);
if(eventId == MENU_CHANGE_IP)
sendDialog(wxLang.at(17), wxOK | wxICON_ERROR);
return;
}
size_t found = sip.find(":");
if(found != string::npos){
sport = atoi(sip.substr(found+1, sip.size()).c_str());
sip = sip.substr(0, found);
wxString wxip(sip.c_str(), wxConvUTF8);
frame->ip->SetValue(wxip);
frame->port->SetValue(sport);
}
if(client != "Auto"){
std::string s ="";
s += client.at(1);
if(s == ".")
client = client.erase(1,1);
}
Change c(tpid);
bool ret = c.changeIP(sip, sport, client);
if(ret){
frame->statusbar->SetStatusText(wxLang.at(18),0);
if(eventId == MENU_CHANGE_IP)
sendDialog(wxString(wxLang.at(18) + wxT("\n") + wxLang.at(1) + wxT(" ") + frame->ip->GetValue() + wxT("\n") + wxLang.at(2) + wxT(" ") + wxString::Format(wxT("%i"), sport)), wxOK);
}else{
frame->statusbar->SetStatusText(wxLang.at(19),0);
if(eventId == MENU_CHANGE_IP)
sendDialog(wxLang.at(16), wxOK | wxICON_ERROR);
return;
}
char buf[4];
sprintf(buf,"%d",sport);
h.saveHistory(std::string(sip + ":" + buf));
frame->ip->Clear();
vector<string>z;
z = h.getHistory();
for(int i = 0; i < z.size(); i++){
wxString wxs(z[i].c_str(), wxConvUTF8);
frame->ip->Append(wxs);
}
}
void Panel::comboSelect(wxCommandEvent& event){
std::string sip = std::string(event.GetString().mb_str());
size_t found = sip.find(":");
if(found != string::npos){
int host = atoi(sip.substr(found+1, sip.size()).c_str());
sip = sip.substr(0, found);
wxString wxs(sip.c_str(), wxConvUTF8);
ip->SetValue(wxs);
port->SetValue(host);
}
}
void Panel::OnClose(wxCloseEvent& event){
Iconize(true);
Show(false);
}
void Panel::PanelClickEvents(wxCommandEvent& event){
switch(event.GetId()){
case wxID_EXIT:{
trayIcon->RemoveIcon();
Destroy();
break;
}
case BUTTON_TO_TRAY:{
Iconize(true);
Show(false);
break;
}
case BUTTON_CHANGE_IP:{
guiChangeIP(this, BUTTON_CHANGE_IP);
break;
}
case MENU_INFO:{
wxString ver(ACTUALVERSION, wxConvUTF8);
wxString code_name(CODENAME, wxConvUTF8);
wxString info = wxT("This program change IP tibia client in order to connect to Open Tibia Server.\nContinue Moraxus project.\nLicense: GNU GPL\nVersion: ") + ver + wxT(" ") + code_name + wxT("\nProgrammer: Miziak.\nAdress Finder: Virtelio.\nWrote in wxWidgets library.");
sendDialog(info, wxOK);
break;
}
case wxID_SETUP:{
wxDialog *dial = new MyDialog(this);
dial->Show();
break;
}
case MENU_CLEAR_HISTORY:{
ofstream plik(string("/home/" + h.getUserName() +"/.linux-ip-changer/history").c_str());
plik<<"";
plik.close();
ip->Clear();
statusbar->SetStatusText(wxLang.at(20),0);
ip->SetValue(wxT(""));
break;
}
case BUTTON_REFRESH:{
TibiaPid pid;
wxArrayString arr = pid.getTibiaPidGUI();
if(arr.GetCount() != 0){
process->Clear();
for(int i = 0; i < arr.GetCount(); i++)
process->Append(wxString(wxT("Tibia (") + arr[i] + wxT(")")));
process->SetValue(wxString(wxT("Tibia (") + arr[0] + wxT(")")));
}else{
process->Clear();
process->Append(wxLang.at(26));
process->SetValue(wxLang.at(26));
}
break;
}
}
}
void MyDialog::Ok(wxCommandEvent& event){
s.saveSetup("lang", std::string(langCombo->GetValue().mb_str()));
this->Destroy();
wxMessageDialog *dial = new wxMessageDialog(NULL, wxLang.at(23), wxLang.at(24), wxOK);
dial->ShowModal();
}
void UpDialog::useLink(wxHyperlinkEvent& event){
wxLaunchDefaultBrowser(event.GetURL());
this->Destroy();
}
void MyTaskBarIcon::TrayClickEvents(wxCommandEvent& event){
switch(event.GetId()){
case wxID_EXIT:{
RemoveIcon();
frame->Destroy();
break;
}
case MENU_O_M:{
if(frame->IsIconized()){
frame->Iconize(false);
frame->Show(true);
}else{
frame->Iconize(true);
frame->Show(false);
}
break;
}
case MENU_CHANGE_IP:{
guiChangeIP(frame, MENU_CHANGE_IP);
break;
}
}
}
void MyTaskBarIcon::TrayLeftClick(wxTaskBarIconEvent& event){
if(frame->IsIconized()){
frame->Iconize(false);
frame->Show(true);
}else{
frame->Iconize(true);
frame->Show(false);
}
}
wxMenu* MyTaskBarIcon::CreatePopupMenu()
{
menuTray = new wxMenu();
menuTray->Append(MENU_CHANGE_IP, wxLang.at(10));
Connect(MENU_CHANGE_IP, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyTaskBarIcon::TrayClickEvents));
if(frame->IsIconized())
menuTray->Append(MENU_O_M, wxLang.at(13));
else
menuTray->Append(MENU_O_M, wxLang.at(14));
menuTray->AppendSeparator();
menuTray->Append(wxID_EXIT, wxLang.at(15));
return menuTray;
}
<file_sep>/Makefile
CC=g++
CFLAGS=-O2 $(shell wx-config --cxxflags --unicode=yes) -D__GUI__
LDFLAGS=$(shell wx-config --libs --unicode=yes) -D__GUI__
SOURCES=main.cpp change.cpp process.cpp tibiapid.cpp gui.cpp history.cpp languages.cpp setup.cpp network.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=change
all: $(SOURCES) $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CC) $(LDFLAGS)$(OBJECTS) -o $@
mv *.o ./Objects
.cpp.o:
$(CC) -c $< $(CFLAGS) -o $@
clean:
rm -rf ./Objects/*.o $(EXECUTABLE)
install:
mv $(EXECUTABLE) /usr/local/bin
cp -R ./Languages /home/miziak/.linux-ip-changer
uninstall:
rm -rf /usr/local/bin/$(EXECUTABLE)
<file_sep>/tibiapid.cpp
#include "tibiapid.h"
using namespace std;
int TibiaPid::getTibiaPidConsole(){
if(name == "")
name = "Tibia";
string data;
char buffer[10];
FILE *stream = popen(string("pgrep " + name).c_str(), "r");
while(fgets(buffer, 10, stream) != NULL)
data.append(buffer);
pclose(stream);
return atoi(data.c_str());
}
#ifdef __GUI__
wxArrayString TibiaPid::getTibiaPidGUI(){
string data;
char buffer[100];
wxArrayString arr;
FILE *stream = popen("pgrep Tibia", "r");
while(fgets(buffer, 100, stream) != NULL)
arr.Add(wxString::Format(wxT("%i"), atoi(buffer)));
pclose(stream);
return arr;
}
#endif
<file_sep>/history.h
#ifndef HISTORY_H
#define HISTORY_H
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class History
{
public:
bool saveHistory(string);
int getLinesCount();
vector<string> getHistory();
string getUserName();
};
#endif // HISTORY_H
<file_sep>/main.cpp
#include <iostream>
#include <stdio.h>
#ifdef __GUI__
#include <wx/init.h>
#include <wx/app.h>
#include "main.h"
#include "gui.h"
#include "history.h"
#endif
#include "change.h"
#include "tibiapid.h"
#include "clientsversions.h"
#include "network.h"
TibiaPid pid;
using namespace std;
void usage(string w){
if(w == "h"){
cout<<"This program change IP tibia client in order to connect to Open Tibia Server."<<endl<<"Continue Moraxus project."<<endl<<"License: GNU GPL"<<endl<<"Programmer: Miziak ,Adress Finder: Virtelio."<<endl;
cout<<"Usage:"<<endl<<" change -ip serverIp serverPort clientVersion This commond change IP"<<endl;
cout<<" change -un serverIp serverPort clientVersion unstandardTibiaProcessName This commond change IP"<<endl<<" Client Versions:"<<endl;
string str;
for(int i = 0; i < int(sizeof(clients)/sizeof(clients[1])); i++)
str += clients[i][0].insert(1, ".") + ", ";
str = str.substr(0, str.size()-2);
cout<<" "<<str<<endl<<" change -h This commond display this help page."<<endl;
}
else if(w == "v")
cout<<"Version "<<ACTUALVERSION<<" "<<CODENAME<<endl;
}
int main(int argc, char **argv)
{
#ifdef __GUI__
History h;
string history = "/home/" + h.getUserName() +"/.linux-ip-changer/history";
string config = "/home/" + h.getUserName() +"/.linux-ip-changer/config.cfg";
#endif
int agr = 1;
while (argc > agr)
{
if(!strcmp(argv[1], "-ip")){
agr = 4;
--argc;
++argv;
}
else if(!strcmp(argv[1], "-un")){
agr = 5;
--argc;
++argv;
}
else if(!strcmp(argv[1], "-h")){
usage("h");
return 0;
}
else if(!strcmp(argv[1], "-v")){
usage("v");
return 0;
}
else{
#ifdef __GUI__
wxApp::SetInstance(new MyApp());
if(access(history.c_str(), F_OK) != 0){
(void)system("mkdir ~/.linux-ip-changer");
(void)system("touch ~/.linux-ip-changer/history");
}
if(access(config.c_str(), F_OK) != 0){
(void)system("touch ~/.linux-ip-changer/config.cfg");
ofstream plik(config.c_str());
plik<<"lang=\"English\""<<endl;
plik.close();
}
return wxEntry(argc, argv);
#else
usage("h");
return 0;
#endif
}
}
if (argc != agr || (argc == 1 && agr == 1)){
#ifdef __GUI__
wxApp::SetInstance(new MyApp());
if(access(history.c_str(), F_OK) != 0){
(void)system("mkdir ~/.linux-ip-changer");
(void)system("touch ~/.linux-ip-changer/history");
}
if(access(config.c_str(), F_OK) != 0){
(void)system("touch ~/.linux-ip-changer/config.cfg");
ofstream plik(config.c_str());
plik<<"lang=\"English\""<<endl;
plik.close();
}
return wxEntry(argc, argv);
#else
usage("h");
return 0;
#endif
}
if(agr == 5)
pid.name = argv[4];
string v = argv[3], s ="";
s += v.at(1);
if(s == ".")
v = v.erase(1,1);
int tpid = pid.getTibiaPidConsole();
if(tpid == 0){
cout<<(argv[4]? argv[4] : "Tibia")<<" process not found!"<<endl;
return 0;
}
Change c(tpid);
bool ret = c.changeIP(argv[1], atoi(argv[2]), v);
if(ret)
cout<<"IP changed to "<<argv[1]<<":"<<atoi(argv[2])<<"!"<<endl;
else
cout<<"IP not changed!"<<endl;
return ret;
}
#ifdef __GUI__
bool MyApp::OnInit()
{
Panel *panel = new Panel(wxT("IP Changer"));
panel->Show(true);
return true;
}
#endif
<file_sep>/setup.cpp
#include "setup.h"
#include "history.h"
bool Setup::saveSetup(string v, string value){
History h;
ifstream file(string("/home/" + h.getUserName() +"/.linux-ip-changer/config.cfg").c_str());
if(!file.is_open())
return false;
bool b = true;
string line;
ofstream plik(string("/home/" + h.getUserName() +"/.linux-ip-changer/config.cfg").c_str());
while(getline(file, line)){
if(line.find(v)!=string::npos)
plik<<line<<endl;
else{
plik<<v<<"=\""<<value<<"\""<<endl;
b = false;
}
}
if(b)
plik<<v<<"=\""<<value<<"\""<<endl;
plik.close();
return true;
}
string Setup::loadSetupValue(string v){
History h;
ifstream file(string("/home/" + h.getUserName() +"/.linux-ip-changer/config.cfg").c_str());
if(!file.is_open())
return "";
string line;
while(getline(file, line)){
if(line.find(v)!=string::npos){
string tmp;
bool b = false;
for(int i = 0; i < line.size(); i++){
string s;
s += line.at(i);
if(s == "\"" || s == "'")
b = !b;
if(b && !(s == "\"" || s == "'"))
tmp += s;
s.clear();
}
if(tmp != "")
return tmp;
}
}
return "";
}
<file_sep>/gui.h
#ifndef GUI_H
#define GUI_H
#include <wx/wx.h>
#include <wx/taskbar.h>
#include <wx/spinctrl.h>
#include <wx/hyperlink.h>
enum{
MENU_O_M = 101,
BUTTON_CHANGE_IP = 102,
MENU_INFO = 103,
BUTTON_TO_TRAY = 104,
ID_COMBO = 105,
MENU_CLEAR_HISTORY = 106,
BUTTON_OK = 107,
MENU_CHANGE_IP = 108,
BUTTON_REFRESH = 109,
HYPERLINK = 110,
CB_IP = 111
};
class Panel : public wxFrame
{
public:
Panel(const wxString& title);
wxComboBox *ip;
wxSpinCtrl *port;
wxComboBox *tibiaversion;
wxComboBox *process;
wxStatusBar *statusbar;
private:
wxPanel *panel;
wxTaskBarIcon *trayIcon;
//Functions
void OnClose(wxCloseEvent& event);
void PanelClickEvents(wxCommandEvent& event);
void comboSelect(wxCommandEvent& event);
DECLARE_EVENT_TABLE();
};
class MyTaskBarIcon: public wxTaskBarIcon
{
public:
MyTaskBarIcon(Panel* frame);
Panel* frame;
virtual wxMenu* CreatePopupMenu();
private:
wxMenu *menuTray;
void TrayLeftClick(wxTaskBarIconEvent& event);
void TrayClickEvents(wxCommandEvent& event);
DECLARE_EVENT_TABLE()
};
class MyDialog: public wxDialog
{
public:
MyDialog(Panel* frame);
Panel* frame;
wxComboBox *langCombo;
private:
void Ok(wxCommandEvent& event);
};
class UpDialog: public wxDialog{
private:
wxHyperlinkCtrl *link;
void useLink(wxHyperlinkEvent& event);
public:
UpDialog(Panel* frame);
Panel* frame;
};
#endif //GUI_H
| 3d7ea7023841b897573bc57ca806845facf3d320 | [
"Makefile",
"C++",
"Shell"
] | 19 | C++ | douglas20345/linux-tibia-ip-changer | 4ed6e6bf61306388673ae16be8a3ffda1f75db24 | c3df07ba212bc1ec742d0e125f147c7c95c03524 |
refs/heads/master | <repo_name>mitalikhundiwala/arcatalog-console<file_sep>/src/lib/firebase.storage.ts
import { firebase } from './firebase.auth';
console.log(firebase);
const storage = firebase.storage();
const storageRef = storage.ref();
export default class FirebaseStorageService {
static uploadFile(file: File): Promise<string> {
console.log(file);
const metadata = {
contentType: 'image/jpeg'
};
const uploadTask = storageRef
.child('images/' + file.name)
.put(file, metadata);
const promise = new Promise<string>((resolve, reject) => {
uploadTask.on(
firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
},
(error) => {
console.log('error::', error);
reject(error);
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
// switch (error.code) {
// case 'storage/unauthorized':
// // User doesn't have permission to access the object
// reject(error.code);
// break;
// case 'storage/canceled':
// // User canceled the upload
// break;
// case 'storage/unknown':
// // Unknown error occurred, inspect error.serverResponse
// break;
// }
},
() => {
// Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref
.getDownloadURL()
.then(function (downloadURL: string) {
console.log('File available at', downloadURL);
resolve(downloadURL);
});
}
);
});
return promise;
}
}
<file_sep>/src/models/user.ts
export default class User {
userId: string;
displayName: string;
picture: string;
email: string;
constructor(data) {
this.userId = data.userId;
this.displayName = data.displayName;
this.picture = data.picture;
this.email = data.email;
}
}
<file_sep>/src/lib/apollo.client.ts
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { ApolloLink } from 'apollo-link';
import fetch from 'node-fetch';
const httpLink = createHttpLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL_SERVER_URL,
fetch
});
const middlewareLink = new ApolloLink((operation, forward) => {
const token = sessionStorage.getItem('AUTH_TOKEN');
operation.setContext({
headers: {
authorization: token
}
});
return forward(operation);
});
const requestLink = middlewareLink.concat(httpLink);
export default new ApolloClient({
link: ApolloLink.from([
onError(({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
// sendToLoggingService(graphQLErrors);
console.log(graphQLErrors);
// for (const err of graphQLErrors) {
// switch (err.extensions.code) {
// case 'UNAUTHENTICATED':
// console.log(operation.getContext());
// const oldHeaders = operation.getContext().headers;
// // operation.setContext({
// // headers: {
// // ...oldHeaders,
// // authorization: getNewToken()
// // }
// // });
// // // retry the request, returning the new observable
// // return forward(operation);
// }
// }
}
if (networkError) {
// logoutUser();
console.log(networkError);
}
}),
requestLink
]),
cache: new InMemoryCache()
});
<file_sep>/src/services/adapters/user.ts
import User from '../../models/user';
export default class UserAdapter {
static fromFirebaseResponse(data: any): User {
return new User({
userId: data.userId,
displayName: data.displayName,
picture: data.photoURL,
email: data.email
});
}
}
<file_sep>/src/lib/firebase.auth.ts
import * as firebase from 'firebase/app';
import 'firebase/database';
import 'firebase/auth';
import 'firebase/storage';
const config = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET
};
!firebase.apps.length && firebase.initializeApp(config);
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
export { firebase, googleAuthProvider };
| a871a650df3d8a08fdfe0d5c4d8f09617b330600 | [
"TypeScript"
] | 5 | TypeScript | mitalikhundiwala/arcatalog-console | 2dca4317c7f0275960fb8e6f6838ac874c11df42 | f7e281798d97db67e9aa18de9f5b56047500aed5 |
refs/heads/master | <repo_name>filipepiressemait/testapimagento2<file_sep>/config.sample.php
<?php
/**
* Created by PhpStorm.
* User: filipe
* Date: 22/09/17
* Time: 00:48
*/
define('USERNAME', NULL);
define('PASSWORD', NULL);
define('URL', NULL);
define('PARAMS1', '/index.php/rest/V1/integration/admin/token');
define('PARAMS2', '/index.php/rest/V1/customers/1');<file_sep>/README.md
# testapimagento2
## Testing connection in magento 2 api
<p>In config.sample.php duplicate file to config.php</p>
<p>Put your credentials in config.php</p>
<file_sep>/token.php
<?php
include './config.php';
if (!USERNAME || !PASSWORD || !URL) return;
$data = ["username" => USERNAME, "password" => <PASSWORD>];
$data_string = json_encode($data);
$ch = curl_init(URL . PARAMS1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$token = curl_exec($ch);
$token_string = json_decode($token);
$header = ["Content-Type: application/json", "Authorization:Bearer " . $token_string];
$ch = curl_init(URL . PARAMS2);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
header("Content-type:application/json");
echo $result; | b6903c77b277a8fdf55595b4a6adeec086c829f6 | [
"Markdown",
"PHP"
] | 3 | PHP | filipepiressemait/testapimagento2 | 1267000e07e1d486a6db08b989130ffdbd9788ef | 9c199d26353ed20a39357e1f4df8a4cc9707cb0d |
refs/heads/master | <file_sep>import firebase from 'firebase';
const firebaseConfig = {
apiKey: "AIzaSyATd7bNDhU6s4sh0qy1x7WheWheq0kw-aw",
authDomain: "twitter-d81b1.firebaseapp.com",
projectId: "twitter-d81b1",
storageBucket: "twitter-d81b1.appspot.com",
messagingSenderId: "62739218711",
appId: "1:62739218711:web:3a9c397a867dee3c6ef752",
measurementId: "G-EPJQEGM4XD"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
export default db; | fa33546203df3212d60a00160e880fc03c85ec20 | [
"JavaScript"
] | 1 | JavaScript | triforze1-git/twitter-clone | c9715b511ac552fef4127571a73cacda8ba131c5 | 555a305f6aa562b00b1a2dc905969489ffdfe993 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-07-06 08:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='productlikes',
name='product',
),
migrations.RemoveField(
model_name='productlikes',
name='user',
),
migrations.AlterModelOptions(
name='productcomments',
options={'ordering': ['-created_at']},
),
migrations.AddField(
model_name='product',
name='likes',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='product',
name='slug',
field=models.CharField(max_length=100, unique=True),
),
migrations.DeleteModel(
name='ProductLikes',
),
]
<file_sep>from django.core.mail import send_mail
from django.utils import timezone
from .models import ProductLikes, ProductComments
def send_report():
day_before = timezone.now() - timezone.timedelta(days=1)
likec_c = ProductLikes.objects.filter(created_at__gte=day_before).count()
comments_c = ProductComments.objects.filter(created_at__gte=day_before).count()
subject = 'Daily report from site'
message = 'From {} to {} you got {} likes and {} comments'.format(
day_before.strftime("%Y-%m-%d %H:%M"),
timezone.now().strftime("%Y-%m-%d %H:%M"),
likec_c,
comments_c
)
from_email = '<EMAIL>'
to_mail = ['<EMAIL>']
# if subject and message:
# try:
send_mail(subject, message, from_email, to_mail)
# except Exception as err:
# print Exception
<file_sep>from django.core.paginator import (Paginator,
EmptyPage,
PageNotAnInteger
)
from django.db.models import Count
from django.http import JsonResponse
from django.shortcuts import (render,
get_object_or_404
)
from django.utils import timezone
from .forms import (CommentForm,
LikesForm
)
from .models import (Product,
ProductComments,
ProductLikes
)
def index(request):
template_name = 'product/products_list.html'
order_by = request.GET.get('order_by')
products = Product.objects.all()
if order_by == 'likes':
products = products.annotate(l=Count('likes__text')).order_by('-l')
paginator = Paginator(products, 5)
page = request.GET.get('page')
try:
prod = paginator.page(page)
except PageNotAnInteger:
prod = paginator.page(1)
except EmptyPage:
prod = paginator.page(paginator.num_pages)
context = {
'products': prod,
'order_by': order_by
}
return render(request, template_name, context)
def product_detail(request, slug):
template_name = 'product/product_detail.html'
day_before = timezone.now() - timezone.timedelta(days=1)
product = get_object_or_404(Product, slug=slug)
comments = ProductComments.objects.filter(product__slug=slug,
created_at__gte=day_before
)
context = {
'comments': comments,
'product': product,
}
response = render(request, template_name, context)
return response
def likes(request):
form = LikesForm(request.POST or None)
print 'request.user.profile', request.user.profile.is_blocked == False
if (request.POST and form.is_valid() and
request.is_ajax() and request.user.profile.is_blocked == False
):
product = form.cleaned_data['product']
user = request.user.profile.id
user_likes_in_product = ProductLikes.objects.filter(user=user,
product_id=product
)
if user_likes_in_product.count() == 0:
form = form.save(commit=False)
form.user_id = user
form.save()
status = 'False'
else:
status = 'True'
context = {
'status': status
}
else:
print 'blocked user'
context = {
'status': 'blocked'
}
return JsonResponse(context)
def add_comment(request):
form = CommentForm(request.POST or None)
status = 'False'
if (request.POST and form.is_valid() and
request.is_ajax() and request.user.profile.is_blocked == False):
form = form.save(commit=False)
form.user_id = request.user.profile.id
form.save()
text = form.text
context = {
'text': text,
'status': 'success'
}
return JsonResponse(context)
elif (request.POST and form.is_valid() and
request.is_ajax() and request.user.profile.is_blocked == True):
print 'blocked'
return JsonResponse({'status': 'blocked'})
else:
return JsonResponse({'status': status})
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-07-07 12:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product', '0003_productlikes'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='likes',
),
migrations.AlterField(
model_name='productlikes',
name='product',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='likes', to='product.Product'),
),
]
<file_sep>from django.conf.urls import url
from . import views
app_name = 'products'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^add_like/$', views.likes, name='add_like'),
url(r'^add_comment/$', views.add_comment, name='add_comment'),
url(r'^(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'),
]
<file_sep>from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth.forms import UserCreationForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.shortcuts import render
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('<PASSWORD>')
user = authenticate(username=username, password=<PASSWORD>)
auth_login(request, user)
return HttpResponseRedirect(reverse('products:index'))
else:
form = UserCreationForm()
return render(request, 'user_profile/signup.html', {'form': form})
def login(request):
if request.method == 'POST' and request.is_ajax():
print 'ajax'
print request.POST
data = {}
username = request.POST['username']
password = request.POST['<PASSWORD>']
user = authenticate(username=username, password=<PASSWORD>)
if (not user is None) and (user.is_active):
auth_login(request, user)
if not request.POST.get('rem', None):
request.session.set_expiry(0)
data['status'] = 'true' # "You have been successfully Logged In"
data['userr'] = user.profile.id
else:
data['status'] = 'false' # "There was an error logging you in. Please Try again"
return JsonResponse(data)
<file_sep>from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.db import models
from apps.user_profile.models import Profile
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=2000)
price = models.DecimalField(max_digits=8, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products:product_detail',
kwargs={
'slug': self.slug
})
class ProductComments(models.Model):
user = models.ForeignKey(Profile, related_name='user_profile_comments')
product = models.ForeignKey(Product, related_name='comments')
text = models.CharField(max_length=1000)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return (self.text).encode('utf-8')
def get_absolute_url(self):
return reverse('products:product_detail',
kwargs={
'slug': self.product.slug
})
class ProductLikes(models.Model):
user = models.ForeignKey(Profile, related_name='user_profile_likes')
product = models.ForeignKey(Product, related_name='likes')
text = models.IntegerField(default=1)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.text)
def get_absolute_url(self):
return reverse('products:product_detail',
kwargs={
'slug': self.product.slug
})
<file_sep>from __future__ import absolute_import, unicode_literals
from celery.task import periodic_task
from celery.utils.log import get_task_logger
from datetime import timedelta
from .report_admin import send_report
from celery.schedules import crontab
logger = get_task_logger(__name__)
@periodic_task(run_every=crontab(minute=0, hour=10))
def report():
try:
send_report()
except Exception as err:
print 'exc', err
logger.info('OK!')
<file_sep>from django.forms import ModelForm
from .models import (ProductComments,
ProductLikes
)
class LikesForm(ModelForm):
class Meta:
model = ProductLikes
fields = ['product']
class CommentForm(ModelForm):
class Meta:
model = ProductComments
fields = ['text', 'product']
<file_sep>from django.contrib import admin
from .models import (Product,
ProductComments,
ProductLikes
)
@admin.register(Product)
class AdminProduct(admin.ModelAdmin):
list_display = ('name',)
@admin.register(ProductLikes)
class AdminProduct(admin.ModelAdmin):
list_display = ('product', 'user')
admin.site.register(ProductComments)
| 7df947a2e59a972fe0db696c4ee505ce360f212b | [
"Python"
] | 10 | Python | AndrewMishchenko/dspsl | 6a50c1b9977193e080ccfeb321780cde8829fa01 | 2a96e745deea7dc71957996a7cfc44093020cd19 |
refs/heads/main | <repo_name>ducanhald/to-do-list<file_sep>/src/App.js
import { useState } from "react";
function App() {
const [JOB, setJOB] = useState("");
const [jobs, setJob] = useState([]);
const submit = () => {
setJob((pre) => [...pre, JOB]);
setJOB("");
};
return (
<div className="App">
<input value={JOB} onChange={(e) => setJOB(e.target.value)} />
<button onClick={submit}>submit</button>
<ul>
{jobs.map((job, index) => {
return <li key={index}>{job}</li>;
})}
</ul>
</div>
);
}
export default App;
| 027b04a99e623d008bf5565d6bdf9cba3312ee94 | [
"JavaScript"
] | 1 | JavaScript | ducanhald/to-do-list | c863700b85dd4db12d26fdf8fc0d6152e8d95c6c | 833035cafaa4d856521155846f5f5881ef8d47a5 |
refs/heads/master | <repo_name>sereg/agar-live<file_sep>/world/split.go
package world
import (
math2 "agar-life/math"
"agar-life/math/crd"
"agar-life/math/vector"
"agar-life/object/alive/animal/behavior"
"agar-life/object/alive/animal/species"
_const "agar-life/world/const"
"agar-life/world/frame"
"math"
"agar-life/object/alive/animal"
gnt "agar-life/world/generate"
)
func Split(fr *frame.Frame, el animal.Animal, direction crd.Crd, cycle uint) {
if el.GetSize() < _const.MinSizeSplit {
return
}
size := math2.Round(el.GetSize() * _const.SplitRatio)
el.SetSize(size)
el.SetGlueTime(cycle)
var parent animal.Animal
if p := el.GetParent(); p != nil {
parent = p
} else {
parent = el
}
direction = vector.GetCrdWithLength(el.GetCrd(), direction, _const.SplitDist)
el.SetInertia(direction)
alv := species.NewBeast(behavior.NewFollower())
alv.SetParent(parent)
alv.SetGlueTime(cycle)
parent.AddChild(alv)
gnt.Generate(
alv,
gnt.Size(size),
gnt.Name(el.GetGroup()),
gnt.Color(el.GetColor()),
gnt.Crd(gnt.FixCrd(el.GetX(), el.GetY())),
)
fr.Add(alv)
}
func Burst(fr *frame.Frame, el animal.Animal, cycle uint) bool {
burstCount := _const.BurstCount
if _const.SplitMaxCount < (el.Count() + burstCount - 1) {
burstCount = _const.SplitMaxCount - el.Count()
if burstCount < 2 {
return true
}
}
size := math2.Round(el.GetSize() / float64(burstCount))
if size < _const.MinSizeAlive {
burstCount = int(el.GetSize() / _const.MinSizeAlive)
if burstCount < 2 {
return false
}
size = math2.Round(el.GetSize() / float64(burstCount))
}
el.SetSize(size)
addAngel := 2.0 * math.Pi / float64(burstCount)
vec := vector.GetVectorByPoint(el.GetCrd(), crd.NewCrd(el.GetX()+_const.SplitDist, el.GetY()))
el.SetInertia(vec.GetPointFromVector(el.GetCrd()))
el.SetGlueTime(cycle)
var parent animal.Animal
if p := el.GetParent(); p != nil {
parent = p
} else {
parent = el
}
for i := 1; i < burstCount; i++ {
alv := species.NewBeast(behavior.NewFollower())
alv.SetParent(parent)
alv.SetGlueTime(cycle)
parent.AddChild(alv)
gnt.Generate(
alv,
gnt.Size(size),
gnt.Name(el.GetGroup()),
gnt.Color(el.GetColor()),
gnt.Crd(gnt.FixCrd(el.GetX(), el.GetY())),
)
vec.AddAngle(addAngel)
alv.SetInertia(vec.GetPointFromVector(el.GetCrd()))
fr.Add(alv)
}
return true
}
<file_sep>/object/alive/plant/interface.go
package plant
import "agar-life/object/alive"
type Plant interface {
alive.Alive
}
<file_sep>/world/frame/grid/spiral_test.go
package grid
import "testing"
type spiralData struct{
x, y int
}
func TestSpiral(t *testing.T) {
testData := []spiralData{
spiralData{9,10},
spiralData{9,11},
spiralData{10,11},
spiralData{11,11},
spiralData{11,10},
spiralData{11,9},
spiralData{10,9},
spiralData{9,9},
spiralData{8,9},
spiralData{8,10},
}
x, y := 10, 10
sp := spiral(x, y)
for i:=0; i < 10; i++ {
x, y := sp()
if x != testData[i].x || y != testData[i].y {
t.Errorf("spet %d found - %d, %d, expected - %d, %d", i, x, y, testData[i].x, testData[i].y)
}
}
}
<file_sep>/object/interface.go
package object
import "agar-life/math/crd"
//Object the base interface for all objects
type Object interface {
GetColor() string
SetColor(string)
GetSize() float64
SetSize(size float64)
GetViewSize() float64
SetViewSize(size float64)
GetGrowSize() float64
GetCrd() crd.Crd
SetCrd(crd.Crd)
SetX(float64)
SetY(float64)
SetXY(float64, float64)
GetX() float64
GetY() float64
GetHidden() bool
SetHidden(bool)
}
<file_sep>/math/crd/crd.go
package crd
import (
math2 "agar-life/math"
"fmt"
"math"
)
//Crd coordinates
type Crd struct {
X, Y float64
}
//NewCrd return new instance of crd
func NewCrd(x, y float64) Crd {
return Crd{X: math2.Round(x), Y: math2.Round(y)}
}
//SetX set X
func (c *Crd) SetX(x float64) {
c.X = math2.Round(x)
}
//GetX it return X
func (c Crd) GetX() float64 {
return c.X
}
//GetY set X
func (c *Crd) SetY(y float64) {
c.Y = math2.Round(y)
}
//SetXY set X and Y
func (c *Crd) SetXY(x float64, y float64) {
if (x == 0 && y == 0) || (x == 1 && y == 1) {
fmt.Println("ff")
}
c.X, c.Y = math2.Round(x), math2.Round(y)
}
//GetY it return Y
func (c Crd) GetY() float64 {
return c.Y
}
//GetCrd it return crd
func (c Crd) GetCrd() Crd {
return c
}
func (c *Crd) SetCrd(a Crd) {
if !math.IsNaN(a.GetX()) && !math.IsNaN(a.GetY()) {
c.X, c.Y = math2.Round(a.GetX()), math2.Round(a.GetY())
}
}
<file_sep>/math/geom/shap.go
package geom
func Intersects( cx, cy, radius, left, top, right, bottom float64) bool{
closestX := 0.0
if cx < left {
closestX = left
} else if cx > right {
closestX = right
}else {
closestX = cx
}
closestY := 0.0
if cy < top {
closestY = top
} else if cy > bottom {
closestY = bottom
}else {
closestY = cy
}
dx := closestX - cx
dy := closestY - cy
return ( dx * dx + dy * dy ) <= radius * radius
}
<file_sep>/math/vector/vector_test.go
package vector
import (
"math"
"testing"
)
func TestGetVec(t *testing.T) {
}
func TestPerpendicular(t *testing.T) {
}
func TestAngle(t *testing.T) {
}
func TestByAngle(t *testing.T) {
}
type xy struct {
x, y float64
}
func TestAddAngle(t *testing.T) {
testRes := map[float64]xy{
0: xy{x:100, y:110},
0.5: xy{x:110, y:100},
1: xy{x:100, y:90},
1.5: xy{x:90, y:100},
}
startX, startY := 100.0, 100.0
vec := GetVectorByPoint(startX, startY, 110, 100)
vec.SetAngle(0)
count := float64(4)
step := 2 / count
for i := 0.0; i < 2; i+=step {
ve := vec
angel := math.Pi * i
ve.AddAngle(angel)
var ans xy
ans.x, ans.y = ve.GetPointFromVector(startX, startY)
if a, ok := testRes[i]; !ok || a!= ans {
t.Errorf("step - %f, angel - %f, recieved unexpected result, expected - %f, got - %f", i, angel, testRes[step], ans)
}
}
}
<file_sep>/math/geom/line_test.go
package geom
import (
"agar-life/math"
"fmt"
"testing"
)
func TestIntersect(t *testing.T) {
}
type lineByPoint struct {
p1, p2 Point
y, slope float64
}
func TestLineByPoint(t *testing.T) {
testRes := []lineByPoint{
lineByPoint{
p1: NewPoint(1, 1), p2: NewPoint(3, 3), y: 0, slope: 1, //y = x
},
lineByPoint{
p1: NewPoint(1, 1), p2: NewPoint(4, 2), y: 0.666667, slope: 0.333333, //y = x
},
}
for _, v := range testRes {
line := NewLine(v.p1, v.p2)
if math2.ToFixed(line.y, 6) != v.y || math2.ToFixed(line.slope, 6) != v.slope {
fmt.Println(line.y != v.y)
fmt.Println(line.slope != v.slope)
t.Errorf("p1 - %v, p2 - %v, recieved unexpected result, expected - '%f', '%f', got - '%f', '%f'", v.p1, v.p2, v.y, v.slope ,line.y ,line.slope)
}
}
}<file_sep>/world/frame/frame.go
package frame
import (
"agar-life/object/alive"
"agar-life/object/alive/animal"
"agar-life/object/alive/animal/behavior/ai"
)
type Frame struct {
w, h float64
updateState bool
secID int
el []alive.Alive
}
func NewFrame(count int, w, h float64) Frame {
return Frame{
el: make([]alive.Alive, count),
w: w, h: h,
updateState: true,
}
}
func (f *Frame) Delete(index int) {
if len(f.el) <= index {
return
}
if el, ok := f.el[index].(animal.Animal); ok {
if parent := el.GetParent(); parent != nil {
parent.DeleteChild(el.GetID())
}
if children := el.GetChildren(); len(children) > 0 {
parent := el.Child(0)
parent.SetParent(nil)
parent.SetBehaviour(ai.NewAiv1(f.w, f.h))
parent.SetCountChildren(len(children))
for i := 1; i < len(children); i++ {
el.Child(i).SetParent(parent)
parent.AddChild(el.Child(i))
}
}
}
f.el = alive.Remove(f.el, index)
}
func (f Frame) Get(index int) alive.Alive {
if len(f.el) <= index {
return nil
}
return f.el[index]
}
func (f *Frame) Set(index int, el alive.Alive) {
if len(f.el) <= index {
return
}
el.SetID(f.sec())
f.el[index] = el
}
func (f Frame) All() []alive.Alive {
return f.el
}
func (f *Frame) SetUpdateState(state bool) {
f.updateState = state
}
func (f Frame) UpdateState() bool {
return f.updateState
}
func (f *Frame) Add(el alive.Alive) {
el.SetID(f.sec())
f.el = append(f.el, el)
}
func (f *Frame) sec() (id int) {
id = f.secID
f.secID++
return
}
<file_sep>/math/geom/degree.go
package geom
import "math"
func ModuleDegree(f float64) float64 {
if f < 0 {
f = math.Pi + math.Pi + f
}
return f
}
<file_sep>/world/bench_test.go
package world
import (
_const "agar-life/world/const"
"strconv"
"testing"
)
func benchmarkCycle(size float64, b *testing.B) {
_const.GridSize = size
for n := 0; n < b.N; n++ {
cycle()
}
}
func BenchmarkCycle(b *testing.B) {
for i:= 10; i < 300; i +=10{
b.Run("Cycle" + strconv.Itoa(i), func(b *testing.B) {
_const.GridSize = float64(i)
for n := 0; n < b.N; n++ {
cycle()
}
})
}
}<file_sep>/world/frame/grid/struct.go
package grid
type xy struct {
x, y int
}
type structGrid struct {
cellSize float64
data map[xy][]int
}
func NewStruct(size float64, cap int) Grid {
return &structGrid{
cellSize: size,
data: make(map[xy][]int, cap),
}
}
func (g structGrid) Len() int {
return len(g.data)
}
func (g *structGrid) Reset() {
}
func (g *structGrid) Set(x, y, size float64, i int) {
xInt := int(x / g.cellSize)
yInt := int(y / g.cellSize)
key := structGridKey(xInt, yInt)
if _, ok := g.data[key]; ok {
g.data[key] = append(g.data[key], i)
} else {
g.data[key] = []int{i}
}
}
func structGridKey(xInt, yInt int) xy {
return xy{x: xInt, y: yInt}
}
func (g structGrid) GetObjInRadius(x, y, radius float64, size float64, exclude int) ([]int, int) {
ltx, lty := int((x-radius)/g.cellSize), int((y-radius)/g.cellSize)
rdx, rdy := int((x+radius)/g.cellSize), int((y+radius)/g.cellSize)
var obj []int
for cx := ltx; cx <= rdx; cx++ {
for cy := lty; cy <= rdy; cy++ {
key := structGridKey(cx, cy)
if ob, ok := g.data[key]; ok {
obj = append(obj, ob...)
}
}
}
return obj, 0
}<file_sep>/world/const/const.go
package _const
//EatRatio ratio when one object can eat another
const (
AnimalTypeAlive = "animal"
PlantTypeAlive = "plant"
FoodSize = 3
AliveStartSize = 10
GrowTime = 10
EatIncreaseRation = 0.2
EatSelfIncreaseRation = 0.95
EatRatio = 1.1
ResurrectTime = 1200
SpeedRatio = 10
StartSpeed = 12
VisionRatio = 7
StartVision = 10
MinSizeAlive = 6
GlueTime = 600
MinSizeSplit = 20
SplitRation = 0.9
SplitSpeed = 5
SplitDeceleration = 0.11
SplitTime = 60
SplitMaxCount = 10
SplitRatio = 0.5
BurstCount = 8
PoisonColor = "#8eb021"
PoisonSize = 15
)
var (
SplitDist = 0.0
GridSize = 70.0
)
func init() {
v := float64(SplitSpeed)
for {
v -= SplitDeceleration
if v <= 0 {
break
}
SplitDist += v
}
println(int(SplitDist))
}
<file_sep>/world/move/move.go
package move
import (
"agar-life/math/crd"
"agar-life/math/vector"
"agar-life/object/alive"
_const "agar-life/world/const"
)
type Move struct {
ChCrd crd.Crd
OldDirection crd.Crd
OldDist float64
Inertia Inertia
}
type Inertia struct{
Direction crd.Crd
Speed, Acceleration float64
}
func (i *Inertia) SetInertia(direction crd.Crd) {
i.Direction = direction
i.Acceleration = _const.SplitDeceleration
i.Speed = _const.SplitSpeed
}
func (m *Move) SetInertia(direction crd.Crd) {
m.Inertia.SetInertia(direction)
}
func (m *Move) SetInertiaImport(direction crd.Crd, speed, acceleration float64) {
m.Inertia.Direction = direction
m.Inertia.Speed = speed
m.Inertia.Acceleration = acceleration
}
func (m *Move) GetInertia() (direction crd.Crd, speed float64){
direction = m.Inertia.Direction
speed = m.Inertia.Speed
if m.Inertia.Speed > 0 {
m.Inertia.Speed -= m.Inertia.Acceleration
}
if m.Inertia.Speed < 0 {
m.Inertia.Speed = 0
}
return
}
func (m *Move) GetDirection() crd.Crd {
return m.OldDirection
}
func (m *Move) SetCrdByDirection(a alive.Alive, direction crd.Crd, dist float64, changeDirection bool) {
if direction == a.GetCrd() {
return
}
if changeDirection || direction != m.OldDirection || m.OldDist != dist{
c := vector.GetCrdWithLength(a.GetCrd(), direction, dist)
xDif, yDif := c.GetX()-a.GetX(), c.GetY()-a.GetY()
m.ChCrd.SetXY(xDif, yDif)
}
m.OldDirection = direction
m.OldDist = dist
a.SetXY(a.GetX() + m.ChCrd.GetX(), a.GetY() + m.ChCrd.GetY())
}
<file_sep>/math/geom/distance.go
package geom
import (
"agar-life/math/crd"
"math"
)
func GetDistanceByCrd(crd1, crd2 crd.Crd) float64 {
d1 := crd1.GetX() - crd2.GetX()
d2 := crd1.GetY() - crd2.GetY()
return math.Sqrt(
d1*d1 + d2*d2,
)
}
<file_sep>/math/tofixed.go
package math
import "math"
// Round left 2 sign after comma
func Round(num float64) float64 {
return float64(int(num * 100)) / 100
}
// ToFixed returns float with precision
func ToFixed(num float64, precision int) float64 {
output := math.Pow(10, float64(precision))
return float64(round(num*output)) / output
}
func round(num float64) int {
return int(num + math.Copysign(0.5, num))
}
<file_sep>/math/geom/segment.go
package geom
import "agar-life/math/crd"
type Segment struct{
a, b crd.Crd
}
func NewSegment(a, b crd.Crd) Segment {
return Segment{
a: a, b: b,
}
}
func (s Segment) Intersection(s1 Segment) bool {
ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 := s.a.GetX(), s.a.GetY(), s.b.GetX(), s.b.GetY(), s1.a.GetX(), s1.a.GetY(), s1.b.GetX(), s1.b.GetY()
v1 := (bx2-bx1)*(ay1-by1) - (by2-by1)*(ax1-bx1)
v2 := (bx2-bx1)*(ay2-by1) - (by2-by1)*(ax2-bx1)
v3 := (ax2-ax1)*(by1-ay1) - (ay2-ay1)*(bx1-ax1)
v4 := (ax2-ax1)*(by2-ay1) - (ay2-ay1)*(bx2-ax1)
return (v1*v2 < 0) && (v3*v4 < 0)
}
func (s Segment) Len() float64 {
return GetDistanceByCrd(s.Start(), s.Finish())
}
func (s Segment) IntersectionPoint(s1 Segment) (intersect bool, cr crd.Crd) {
// Line AB represented as a1x + b1y = c1
a1 := s.Finish().GetY() - s.Start().GetY()
b1 := s.Start().GetX() - s.Finish().GetX()
c1 := a1*s.Start().GetX() + b1*s.Start().GetY()
// Line CD represented as a2x + b2y = c2
a2 := s1.Finish().GetY() - s1.Start().GetY()
b2 := s1.Start().GetX() - s1.Finish().GetX()
c2 := a2*s1.Start().GetX() + b2*s1.Start().GetY()
determinant := a1*b2 - a2*b1
if determinant == 0 {
return
} else {
x := (b2*c1 - b1*c2)/determinant
y := (a1*c2 - a2*c1)/determinant
return true, crd.NewCrd(x, y)
}
}
func (s *Segment) SetStart(cr crd.Crd) {
s.a = cr
}
func (s *Segment) SetFinish(cr crd.Crd) {
s.b = cr
}
func (s Segment) Start() crd.Crd {
return s.a
}
func (s Segment) Finish() crd.Crd {
return s.b
}
func (s Segment) MidPoint() crd.Crd {
return crd.NewCrd((s.a.GetX() + s.b.GetX()) / 2, (s.a.GetY() + s.b.GetY()) / 2)
}
<file_sep>/assets/node/Dockerfile
FROM node
WORKDIR /project
ADD . /usr/local/
RUN chmod +x /usr/local/docker-entrypoint.sh
USER node
# RUN npm install \
# npm run src
ENTRYPOINT ["/usr/local/docker-entrypoint.sh"]<file_sep>/world/generate/generate.go
package generate
import (
math2 "agar-life/math"
"agar-life/math/crd"
"agar-life/object/alive"
_const "agar-life/world/const"
"strconv"
)
func Generate(el alive.Alive, opts ...Option) {
opt := DefaultOptions()
for _, o := range opts {
o(&opt)
}
if el.GetDanger() {
el.SetColor(_const.PoisonColor)
el.SetSize(_const.PoisonSize)
el.SetViewSize(_const.PoisonSize)
} else {
if opt.color == nil {
el.SetColor(getRandomColor())
} else {
el.SetColor(*opt.color)
}
el.SetSize(opt.size)
el.SetViewSize(opt.size)
}
el.SetCrd(opt.crdFn(opt.w, opt.h))
el.Revive()
if opt.name != "" {
el.SetGroup(opt.name)
}
}
type crdFunc func(x, y float64) crd.Crd
type Options struct {
w, h, size float64
name string
crdFn crdFunc
color *string
}
func DefaultOptions() Options {
return Options{
size: _const.FoodSize,
//size: _const.PoisonSize,
crdFn: RandomCrd,
}
}
//Option it is type for config of declare option
type Option func(*Options)
// SetGroup sets name option
func Name(name string) Option {
return func(o *Options) {
o.name = name
}
}
// SetColor sets color option
func Color(color string) Option {
return func(o *Options) {
o.color = &color
}
}
// Crd sets function for setting crdFn
func Crd(crdFn crdFunc) Option {
return func(o *Options) {
o.crdFn = crdFn
}
}
func RandomCrd(x, y float64) crd.Crd {
return crd.NewCrd(float64(math2.Random(0, int(x))), float64(math2.Random(0, int(y))))
}
func FixCrd(x, y float64) crdFunc {
return func(float64, float64) crd.Crd {
return crd.NewCrd(x, y)
}
}
// WorldWH sets size of world option
func WorldWH(w, h float64) Option {
return func(o *Options) {
o.w, o.h = w, h
}
}
// Type sets name option
func Size(size float64) Option {
return func(o *Options) {
o.size = size
}
}
func getRandomColor() string {
r := strconv.FormatInt(int64(math2.Random(50, 250)), 16)
g := strconv.FormatInt(int64(math2.Random(50, 250)), 16)
b := strconv.FormatInt(int64(math2.Random(50, 250)), 16)
return "#" + r + g + b
}
<file_sep>/world/space_test.go
package world
import (
_const "agar-life/world/const"
"fmt"
"math"
"os"
"testing"
)
func TestCycle(t *testing.T) {
cycle()
}
func TestExport(t *testing.T) {
//world := NewWorld(80, 10, 500, 500)
file, err := os.Open("/home/serega/Downloads/export.json")
if err != nil {
panic(err)
}
defer file.Close()
world := NewWorldFromFile(file)
//loop:
for i := 0; i < 10000; i++ {
world.Cycle()
//animalList := world.GetAnimal()
//for _, v := range animalList {
//el := v.(animal.Animal)
//if el.GetParent() != nil {
// break loop
//}
//}
}
//s := world.ExportWorld()
//fmt.Println(s)
}
func TestImport(t *testing.T) {
file, err := os.Open("/home/serega/Downloads/export3.json")
if err != nil {
panic(err)
}
defer file.Close()
world := NewWorldFromFile(file)
for i := 0; i < 10; i++ {
world.Cycle()
animalList := world.GetAnimal()
for _, v := range animalList {
_ = v
}
}
}
func cycle() {
//world := NewWorldTest(2, 1, 1000, 969)
world := NewWorld(1000, 10, 1000, 1000)
for i := 0; i < 10000; i++ {
world.Cycle()
animalList := world.GetAnimal()
for _, v := range animalList {
_ = v
}
}
}
func Te1stLog(t *testing.T) {
for i := 1; i < 100; i += 2 {
fmt.Printf("%d - %f\r\n", i, reduce(float64(i)))
}
for i := 1; i < 1000; i += 10 {
fmt.Printf("%d - %f\r\n", i, reduce(float64(i)))
}
}
func reduce(i float64) float64 {
return (_const.StartSpeed - math.Log(i*_const.SpeedRatio)) / 10
}
//s= v0*t + 0.5*a*t^2
func Tes1tReduceSpeed(t *testing.T) {
dist := 0.0
tt := 60.0
v := 5.0
//a := getAcceleration(v, tt, dist)
a := 0.1
for i := 0.0; i < tt; i++ {
dist += v
v -= a
fmt.Println(i)
fmt.Println(v)
fmt.Println(dist)
if v <= 0 {
break
}
}
//fmt.Println(a)
//fmt.Println(getDist(5.0, tt, a))
}
//a=(s-v0*t)/(0.5*t*t)
func getAcceleration(v0, t, s float64) float64 {
return math.Abs((s - v0*t) / (0.5 * t * t))
}
func getDist(v0, t, a float64) float64 {
return v0*t + 0.5*a*t*t
}
<file_sep>/object/alive/animal/species/beast.go
package species
import (
"agar-life/math/crd"
"agar-life/object/alive"
"agar-life/object/alive/animal"
)
type beast struct {
Base
}
func NewBeast(behavior animal.Behavior) animal.Animal {
b := beast{}
b.SetBehaviour(behavior)
return &b
}
func (b *beast) Action(animals []alive.Alive, plants []alive.Alive, cycle uint) (crd.Crd, bool) {
return b.GetBehaviour().Action(animal.Animal(b), animals, plants, cycle)
}
<file_sep>/world/frame/grid/bench_test.go
package grid
import (
"testing"
)
//
func BenchmarkStruct(b *testing.B) {
grid := func() Grid {
return NewStruct(50, 6400)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
testGrid(grid)
}
}
func BenchmarkString(b *testing.B) {
grid := func() Grid {
return NewString(50, 6400)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
testGrid(grid)
}
}
func BenchmarkMultiply(b *testing.B) {
grid := func() Grid {
return NewMultiply(50, 6400)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
testGrid(grid)
}
}
func BenchmarkArray(b *testing.B) {
grid := func() Grid {
return NewArray(50, 5000, 5000)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
testGrid(grid)
}
}<file_sep>/world/frame/grid/multiply.go
package grid
type multiply struct {
cellSize float64
data map[int][]int
}
func NewMultiply(size float64, cap int) Grid {
return &multiply{
cellSize: size,
data: make(map[int][]int, cap),
}
}
func (g *multiply) Len() int {
return len(g.data)
}
func (g *multiply) Reset() {
}
func (g *multiply) Set(x, y, size float64, i int) {
xInt := int(x / g.cellSize)
yInt := int(y / g.cellSize)
key := multiplyKey(xInt, yInt)
if _, ok := g.data[key]; ok {
g.data[key] = append(g.data[key], i)
} else {
g.data[key] = []int{i}
}
}
func multiplyKey(xInt, yInt int) int {
return (xInt + 1) * 10000 + yInt
}
func (g *multiply) GetObjInRadius(x, y, radius float64, size float64, exclude int) ([]int, int) {
ltx, lty := int((x-radius)/g.cellSize), int((y-radius)/g.cellSize)
rdx, rdy := int((x+radius)/g.cellSize), int((y+radius)/g.cellSize)
var obj []int
for cx := ltx; cx <= rdx; cx++ {
for cy := lty; cy <= rdy; cy++ {
key := multiplyKey(cx, cy)
if ob, ok := g.data[key]; ok {
obj = append(obj, ob...)
}
}
}
return obj, 0
}<file_sep>/math/random.go
package math
import "math/rand"
// Random returns a random value between the min and max
func Random(min, max int) int {
return rand.Intn(max-min) + min
}
<file_sep>/object/alive/base.go
package alive
import (
"agar-life/object"
)
//Base is basic realization on object alive
type Base struct {
object.Base
Deed bool
Group string
ID int
Danger bool
Edible bool
}
//GetDanger it returns is Danger of the object
func (b Base) GetDanger() bool{
return b.Danger
}
//GetEdible it returns is edibility
func (b Base) GetEdible() bool{
return b.Edible
}
//SetDanger set Danger
func (b *Base)SetDanger(st bool) {
b.Danger = st
}
//SetEdible set Edible
func (b *Base) SetEdible(st bool) {
b.Edible = st
}
//GetID it gets ID
func (b Base) GetID() int{
return b.ID
}
//SetID it sets ID
func (b *Base) SetID(id int){
b.ID = id
}
//Die it kills the object
func (b *Base) Die(){
b.Deed = true
b.SetHidden(true)
}
//Revive it revives the object
func (b *Base) Revive(){
b.Deed = false
b.SetHidden(false)
}
//GetDead it returns status of the object
func (b Base) GetDead() bool {
return b.Deed
}
func (b Base) Grow() {
}
func (b Base) Decrease(){
}
func (b Base) GetGroup() string{
return b.Group
}
func (b *Base) SetGroup(group string) {
b.Group = group
}
func (b Base) GetGlueTime() uint {
return 0
}
func (b Base) SetGlueTime(cycle uint) {
}<file_sep>/object/alive/animal/behavior/follower.go
package behavior
import (
"agar-life/math/crd"
"agar-life/object/alive"
"agar-life/object/alive/animal"
)
const (
FollowerName = "follower"
)
type follower struct {
direction crd.Crd
Name string
}
func NewFollower() animal.Behavior {
return &follower{Name: FollowerName}
}
func (a *follower) Action(self animal.Animal, animals []alive.Alive, plants []alive.Alive, cycle uint) (crd.Crd, bool) {
if parent := self.GetParent(); parent != nil {
a.direction.SetCrd(parent.GetCrd())
}
return a.direction, false
}<file_sep>/object/alive/plant/species/plant.go
package species
import (
"agar-life/object/alive/plant"
)
type plantX struct {
Base
}
func NewPlant() plant.Plant{
p := plantX{}
p.SetDanger(false)
p.SetEdible(true)
return &p
}
<file_sep>/object/alive/animal/behavior.go
package animal
import (
"agar-life/math/crd"
"agar-life/object/alive"
)
type Behavior interface{
Action(self Animal, animals []alive.Alive, plants []alive.Alive, cycle uint) (crd.Crd, bool)
}
<file_sep>/go.mod
module agar-life
go 1.13
require (
github.com/NYTimes/gziphandler v1.1.1
github.com/bradrydzewski/go-mimetype v0.0.0-20171006003642-47218b6fef13
github.com/gabriel-vasile/mimetype v0.3.22
github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a // indirect
)
<file_sep>/math/vector/vector.go
package vector
import (
"agar-life/math/crd"
"math"
)
type Vector struct {
x, y float64
}
func NewVector(crd crd.Crd) Vector {
return Vector{x: crd.GetX(), y: crd.GetY()}
}
func GetVectorByPoint(a, b crd.Crd) Vector {
vec := Vector{}
vec.x = b.GetX() - a.GetX()
vec.y = b.GetY() - a.GetY()
return vec
}
func GetVectorWithLength(a, b crd.Crd, dist float64) Vector {
vec := GetVectorByPoint(a, b)
length := vec.Len()
ratio := dist / length
vec.MultiplyByScalar(ratio)
return vec
}
func GetCrdWithLength(a, b crd.Crd, dist float64) crd.Crd {
vec := GetVectorWithLength(a, b, dist)
return vec.GetPointFromVector(a)
}
func (vec Vector) Len() float64 {
return math.Sqrt(vec.x*vec.x + vec.y*vec.y)
}
func (vec *Vector) MultiplyByScalar(s float64) {
vec.x *= s
vec.y *= s
}
func (vec Vector) MultiplyByVector(s Vector) Vector {
//vec.x *= s
//vec.y *= s
return vec
}
func (vec *Vector) AddAngle(angle float64) {
l := vec.Len()
y := math.Cos(vec.GetAngle() + angle) * l
x := math.Sin(vec.GetAngle() + angle) * l
if x == l {
y = 0
}
if y == l {
x = 0
}
vec.x = x
vec.y = y
}
func (vec *Vector) SetAngle(angle float64) {
l := vec.Len()
y := math.Cos(angle) * l
x := math.Sin(angle) * l
if x == l {
y = 0
}
if y == l {
x = 0
}
vec.x = x
vec.y = y
}
func (vec Vector) GetPointFromVector(a crd.Crd) crd.Crd {
xr := vec.x + a.GetX()
yr := vec.y + a.GetY()
return crd.NewCrd(xr, yr)
}
func (vec Vector) GetAngle() float64 {
angel := math.Atan2(vec.x, vec.y)
if math.IsNaN(angel) {
angel = math.Pi
}
return angel
}
func (vec Vector) GetPerpendicularVector(x float64) Vector {
y := (-1 * vec.x * x) / vec.y
return Vector{x: x, y: y}
}
func Add(a, b Vector) Vector {
a.x += b.x
a.y += b.y
return a
}
func Compare(a, b Vector) bool {
return a.x == b.x && a.y == b.y
}
<file_sep>/cmd/js/main.go
package main
import (
"agar-life/canvas"
"agar-life/world"
"math/rand"
"strconv"
"strings"
"syscall/js"
"time"
)
//set GOARCH=wasm
//set GOOS=js
//go src -o ./assets/lib.wasm cmd/js/main.go
//GOARCH=wasm GOOS=js go build -o ./assets/public/lib.wasm cmd/js/main.go
//go test -cpuprofile profile.out
//go test -memprofile profile.out
//go tool pprof --web profile.out
func main() {
rand.Seed(time.Now().UTC().UnixNano())
jsCon := canvas.NewJsConnect()
w, h := jsCon.GetW(), jsCon.GetH()
countPlants := 50
countAnimal := 5
space := world.NewWorld(countPlants, countAnimal, w, h)
fieldPlants := jsCon.NewCanvas("first")
fieldAnimals := &canvas.Animal{Base: *jsCon.NewCanvas("second")}
story := story{}
cycle := getCycleFn(&space, fieldPlants, fieldAnimals, &story)
js.Global().Set("cycle", cycle)
js.Global().Set("restart", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
space = world.NewWorld(countPlants, countAnimal, w, h)
cycle = getCycleFn(&space, fieldPlants, fieldAnimals, &story)
js.Global().Set("cycle", cycle)
jsCon.GetWindow().Call("requestAnimationFrame", cycle)
return nil
}))
js.Global().Set("generate", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
countAnimal = args[0].Int()
countPlants = args[1].Int()
space = world.NewWorld(countPlants, countAnimal, w, h)
cycle = getCycleFn(&space, fieldPlants, fieldAnimals, &story)
js.Global().Set("cycle", cycle)
jsCon.GetWindow().Call("requestAnimationFrame", cycle)
return nil
}))
js.Global().Set("export", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
test := space.ExportWorld()
return test
}))
js.Global().Set("import", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
data := args[0].String()
space = world.NewWorldFromFile(strings.NewReader(data))
cycle = getCycleFn(&space, fieldPlants, fieldAnimals, &story)
js.Global().Set("cycle", cycle)
jsCon.GetWindow().Call("requestAnimationFrame", cycle)
return nil
}))
js.Global().Set("backward", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if len(story.story) == 0 {
return nil
}
data := story.getLast()
story.story = story.story[:len(story.story)-1]
space = world.NewWorldFromFile(strings.NewReader(data))
cycle = getCycleFn(&space, fieldPlants, fieldAnimals, &story)
js.Global().Set("cycle", cycle)
jsCon.GetWindow().Call("requestAnimationFrame", cycle)
return nil
}))
js.Global().Set("get", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
x, y := args[0].Float(), args[1].Float()
info := space.GetID(x, y)
return info
}))
js.Global().Set("changePosition", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
x, y := args[0].Float(), args[1].Float()
info := space.GetEl(x, y)
jsCon.GetWindow().Call("requestAnimationFrame", cycle)
return info
}))
js.Global().Set("addFromJSON", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
data := args[0].String()
x, y := args[1].Float(), args[2].Float()
info := space.AddFromJSON(data, x, y)
jsCon.GetWindow().Call("requestAnimationFrame", cycle)
return info
}))
js.Global().Set("add", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
typ := args[0].String()
x, y := args[1].Float(), args[2].Float()
_, _, _ = typ, x, y
return nil
}))
js.Global().Set("setSize", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
data := args[0].String()
space.SetSize(data)
return nil
}))
js.Global().Set("delete", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
story.reset()
id := args[0].Int()
_ = id
return nil
}))
jsCon.GetWindow().Call("requestAnimationFrame", cycle)
println("WASM Go Initialized field " + strconv.Itoa(int(jsCon.GetW())) + " " + strconv.Itoa(int(jsCon.GetH())))
select {
case <-time.After(999999 * time.Second):
}
}
type story struct {
story []string
}
func (s *story) reset() {
s.story = []string{}
}
func (s *story) getLast() string {
return s.story[len(s.story)-1]
}
func getCycleFn(space *world.World, fieldPlants, fieldAnimals canvas.Canvas, story *story) js.Func {
return js.FuncOf(func(this js.Value, args []js.Value) interface{} {
space.Cycle()
plant := space.GetPlant()
if len(plant) > 0 { //TODO rewrite method, return special marker of not update
fieldPlants.Save()
fieldPlants.Refresh()
for _, v := range plant {
fieldPlants.Draw(v)
}
fieldPlants.Restore()
}
animalList := space.GetAnimal()
fieldAnimals.Save()
fieldAnimals.Refresh()
for _, v := range animalList {
fieldAnimals.Draw(v)
}
fieldAnimals.Restore()
if space.GetCycle()%20 == 0 {
story.story = append(story.story, space.ExportWorld())
if len(story.story) > 20 {
story.story = story.story[1:]
}
}
return nil
})
}
<file_sep>/world/frame/grid/correct_test.go
package grid
import "testing"
func TestCorrectArray(t *testing.T) {
testData := []struct{
name string
fn func() Grid
}{
{
name: "array",
fn: func() Grid {
return NewArray(50, 5000, 5000)
},
},
{
name: "struct",
fn: func() Grid {
return NewStruct(50, 6400)
},
}, {
name: "string",
fn: func() Grid {
return NewString(50, 6400)
},
},
{
name: "Multiply",
fn: func() Grid {
return NewMultiply(50, 6400)
},
},
}
expectedUsed, expectedFound := 6400, 207025
for _, v := range testData{
l, f := testGrid(v.fn)
if l != expectedUsed {
t.Errorf("%s used - %d, expected - %d", v.name, l, expectedUsed)
}
if f != expectedFound {
t.Errorf("%s found - %d, expected - %d", v.name, f, expectedFound)
}
}
}
func testGrid(fn func() Grid) (l, f int) {
found := []int{}
grid := fn()
for i:= 0.0; i < 100; i++ {
for j := 0.0; j < 100; j++ {
Set(i * 40, j * 40, i, -1)
}
}
for i:= 0.0; i < 100; i++ {
for j := 0.0; j < 100; j++ {
found = append(found, GetObjInRadius(i * 40, j * 40, 70, -1)...)
}
}
l = Len()
f = len(found)
return
}<file_sep>/object/alive/animal/behavior/ai/memory.go
package ai
import "agar-life/math/crd"
type memory struct {
valid bool
priority uint8
validTime uint
reason string
crd crd.Crd
}
func (m *memory) set(pr uint8, vt uint, reason string, crd crd.Crd) {
m.valid = true
m.priority = pr
m.validTime = vt
m.reason = reason
m.crd = crd
}
func (m *memory) check(pr uint8, cycle uint) (bool, crd.Crd) {
if m.valid && m.validTime < cycle && m.priority >= pr {
return true, m.crd
}
//m.reset()
return false, m.crd
}
func (m *memory) checkByReason(pr uint8, cycle uint, reason string) (bool, crd.Crd) {
if m.valid && m.validTime > cycle && m.priority >= pr && m.reason == reason {
return true, m.crd
}
m.reset()
return false, m.crd
}
func (m *memory) reset() {
m.valid = false
}
<file_sep>/world/frame/grid/array.go
package grid
type array struct {
cellSize float64
data [][][]int
}
func NewArray(size, w, h float64) Grid {
rows := int(w/size) + 1
columns := int(h/size) + 1
data := make([][][]int, rows)
for i := range data {
data[i] = make([][]int, columns)
}
return &array{
cellSize: size,
data: data,
}
}
func (g array) Len() int {
count := 0
for _, v1 := range g.data {
for _, v := range v1 {
if len(v) > 0 {
count++
}
}
}
return count
}
func (g *array) Reset() {
for i, v1 := range g.data {
for i1, v := range v1 {
if len(v) > 0 {
g.data[i][i1] = make([]int, 0, 10)
}
}
}
}
func (g *array) Set(x, y, size float64, i int) {
ltx, lty := toInt((x-size)/g.cellSize), toInt((y-size)/g.cellSize)
rdx, rdy := toInt((x+size)/g.cellSize), toInt((y+size)/g.cellSize)
cx, cy := 0, 0
for cx = ltx; cx <= rdx; cx++ {
for cy = lty; cy <= rdy; cy++ {
if len(g.data) > cx {
d := g.data[cx]
if len(d) > cy {
d[cy] = append(d[cy], i)
continue
}
}
}
}
}
func (g array) GetObjInRadius(x, y, radius, size float64, exclude int) ([]int, int) {
lrx, lry := toInt((x-radius)/g.cellSize), toInt((y-radius)/g.cellSize)
rrx, rry := toInt((x+radius)/g.cellSize), toInt((y+radius)/g.cellSize)
lsx, lsy := toInt((x-size)/g.cellSize), toInt((y-size)/g.cellSize)
rsx, rsy := toInt((x+size)/g.cellSize), toInt((y+size)/g.cellSize)
far := make([]int, 0, 5)
closest := make([]int, 0, 5)
for cx := lrx; cx <= rrx; cx++ {
for cy := lry; cy <= rry; cy++ {
if len(g.data) <= cx {
continue
}
d := g.data[cx]
if len(d) <= cy {
continue
}
if cx >= lsx && cx <= rsx && cy >= lsy && cy <= rsy {
closest = append(closest, d[cy]...)
} else {
far = append(far, d[cy]...)
}
}
}
closest = excludeByID(closest, exclude)
obj := append(closest, far...)
return obj, len(closest)
}
func excludeByID(a []int, id int) []int {
prev := -1
for k := 0; k < len(a); k++ {
v := a[k]
if v == id || v == prev {
a = removeFromInt(a, k)
k--
}
prev = v
}
return a
}
func removeFromInt(a []int, i int) []int {
a[i] = a[len(a)-1] // Copy last element to index i.
a[len(a)-1] = 0 // Erase last element (write zero value).
a = a[:len(a)-1]
return a
}
func toInt(f float64) int {
if f < 0 {
return 0
}
return int(f)
}
<file_sep>/object/alive/plant/species/poison.go
package species
import (
"agar-life/object/alive/plant"
)
type poison struct {
Base
}
func NewPoison() plant.Plant {
p := poison{}
p.SetDanger(true)
p.SetEdible(false)
return &p
}
<file_sep>/assets/src/wasm.js
// import Go from './wasm_exec.js';
export async function init() {
const go = new Go();
// let result = await WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject);
// await go.run(result.instance);
let {instance, module} = await WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject);
await go.run(instance);
}
export class Universe {
async cycle() {
await window.cycle();
}
async restart() {
await window.restart();
}
/**
* @returns {string}
*/
async export() {
return window.export();
}
/**
* @param {string} text
*/
async import(text) {
await window.import(text);
}
/**
* @param {number} countAnimal
* @param {number} countPlant
*/
async generate(countAnimal, countPlant) {
await window.generate(countAnimal, countPlant);
}
async backward() {
await window.backward();
}
/**
* @param {string} params
*/
async setSize(params) {
await window.setSize(params);
}
/**
* @param {number} x
* @param {number} y
* @returns {string}
*/
async changePosition(x, y) {
return window.changePosition(x, y);
}
/**
* @param {string} data
* @param {number} x
* @param {number} y
* @returns {string}
*/
async addFromJSON(data, x, y) {
return window.addFromJSON(data, x, y);
}
}<file_sep>/object/alive/animal/behavior/ai/ai-v1.go
package ai
import (
"agar-life/math/crd"
"agar-life/math/geom"
"agar-life/math/vector"
"agar-life/object/alive"
"agar-life/object/alive/animal"
"agar-life/object/alive/animal/behavior"
"agar-life/object/alive/animal/behavior/checkangels"
"agar-life/world/const"
"strconv"
"strings"
)
type aiV1 struct {
behavior.Simple
Name string
mem memory
}
const (
AIV1Name = "aiV1"
running = 100
eating = 50
nothing = 9
)
var (
top checkangels.Obstacle
down checkangels.Obstacle
left checkangels.Obstacle
right checkangels.Obstacle
)
func NewAiv1(w, h float64) animal.Behavior {
top = checkangels.NewLine(geom.NewSegment(crd.NewCrd(0, 0), crd.NewCrd(w, 0)))
down = checkangels.NewLine(geom.NewSegment(crd.NewCrd(0, h), crd.NewCrd(w, h)))
left = checkangels.NewLine(geom.NewSegment(crd.NewCrd(0, 0), crd.NewCrd(0, h)))
right = checkangels.NewLine(geom.NewSegment(crd.NewCrd(w, 0), crd.NewCrd(w, h)))
return &aiV1{
Simple: behavior.NewSimple(w, h),
Name: AIV1Name,
}
}
func tD(speed, distance float64, cycle uint) uint {
//return 3 + cycle
return uint(distance/speed*0.5) + cycle
}
type strategy struct {
priority uint8
mem bool
condition func() bool
reason func() string
action func() crd.Crd
}
func (a *aiV1) Action(self animal.Animal, animals []alive.Alive, plants []alive.Alive, cycle uint) (crd.Crd, bool) {
dangerous := dangerous(self, animals)
poisons := poisons(self, plants)
edges := a.edgeObstacle(self)
poisonCount := strconv.Itoa(len(poisons))
edgesCount := strconv.Itoa(len(edges))
dangerousCount := strconv.Itoa(len(dangerous.obj))
var dAngeles checkangels.Angels
dAngelesFn := func() checkangels.Angels {
if dAngeles.Angel() == 0 {
dAngeles = checkangels.CheckAngels(self, append(poisons, edges...))
}
return dAngeles
}
var closest *crd.Crd
split := false
closestFn := func() *crd.Crd {
if len(animals) == 0 && len(plants) == 0 {
return nil
}
closest, split = closestFn(self, animals, plants, dAngeles)
return closest
}
strategies := []strategy{
{ //running
priority: running,
mem: true,
condition: func() bool {
return len(dangerous.obj) > 0
},
reason: func() string {
return dangerousCount + "-" + poisonCount + "-" + edgesCount
},
action: func() crd.Crd {
dAngelesFn()
sum := vector.GetVectorByPoint(self.GetCrd(), self.GetCrd())
for _, v := range dangerous.obj {
sum = vector.Add(sum, v.vec)
}
vecAngel := geom.ModuleDegree(sum.GetAngle())
reachable, _ := dAngeles.Check(vecAngel, sum.Len())
if !reachable {
sum.SetAngle(dAngeles.ClosestAvailable(vecAngel))
}
//TODO hide in poison plant if size of them more then object
return sum.GetPointFromVector(self.GetCrd())
},
},
{ //running from memory
priority: running,
mem: false,
condition: func() bool {
valid, _ := a.mem.check(running, cycle)
return valid
},
action: func() crd.Crd {
_, crdRes := a.mem.check(running, cycle)
return crdRes
},
},
{ //eating
priority: eating,
mem: true,
condition: func() bool {
dAngelesFn()
return closestFn() != nil
},
reason: func() string {
return strconv.Itoa(len(animals)) + "-" + strconv.Itoa(len(plants)) + "-" + poisonCount + "-" + edgesCount
},
action: func() crd.Crd {
//TODO check object reachability
return closest.GetCrd()
},
},
{ //default
priority: nothing,
mem: true,
condition: func() bool {
return true
},
reason: func() string {
return strconv.Itoa(len(animals)) + "-" + strconv.Itoa(len(plants)) + "-" + poisonCount + "-" + edgesCount
},
action: func() crd.Crd {
cr, _ := a.Simple.Action(self, nil, nil, 0, dAngeles)
return cr
},
},
}
for _, strategy := range strategies {
if strategy.condition() {
//fmt.Println(self.GetCrd())
reason := ""
if strategy.mem {
reason = strategy.reason()
if valid, cr := a.mem.checkByReason(strategy.priority, cycle, reason); valid {
a.SetDir(cr)
break
}
}
cr := strategy.action()
if strategy.mem {
a.mem.set(strategy.priority, tD(self.GetSpeed(), self.GetVision(), cycle), reason, cr)
}
a.SetDir(cr)
break
}
}
//if self.GetSize() < 80 {
// self.SetSize(80)
//}
return a.Dir(), split
}
func (a *aiV1) edgeObstacle(el animal.Animal) (obstacles []checkangels.Obstacle) {
if el.GetX()-el.GetVision() < 0 {
obstacles = append(obstacles, left)
}
if el.GetX()+el.GetVision() > a.W() {
obstacles = append(obstacles, right)
}
if el.GetY()-el.GetVision() < 0 {
obstacles = append(obstacles, top)
}
if el.GetY()+el.GetVision() > a.H() {
obstacles = append(obstacles, down)
}
return
}
func closestFn(self animal.Animal, animals, plants []alive.Alive, dAngeles checkangels.Angels) (closest *crd.Crd, split bool) {
closestFnAn := func() (closest *crd.Crd, split bool) {
return getClosest(self, animals, true, 1, dAngeles)
}
closestFnPl := func() (closest *crd.Crd, split bool) {
return getClosest(self, plants, false, 1, dAngeles)
}
if closest, split := closestFnAn(); closest == nil {
return closestFnPl()
} else {
return closest, split
}
}
type dp struct {
vec vector.Vector
name string
}
type dangerObj struct {
obj []dp
}
func (d dangerObj) Names() string {
names := make([]string, len(d.obj))
for k, v := range d.obj {
names[k] = v.name
}
return strings.Join(names, "")
}
func (d *dangerObj) add(a, b crd.Crd, vision float64, name string) {
vec := vector.GetVectorWithLength(b, a, vision)
for _, v := range d.obj {
if vector.Compare(v.vec, vec) {
return
}
}
d.obj = append(d.obj, dp{vec: vec, name: name})
}
func dangerous(el animal.Animal, animals []alive.Alive) dangerObj {
danObj := dangerObj{}
for i := 0; i < len(animals); i++ {
el1 := animals[i]
if el != nil && el1 != nil && el1.GetSize()/el.GetSize() > _const.EatRatio && el1.GetGroup() != el.GetGroup() && !el1.GetDead() {
danObj.add(el.GetCrd(), el1.GetCrd(), el.GetVision(), el1.GetGroup())
}
}
return danObj
}
func poisons(el animal.Animal, plants []alive.Alive) (poisons []checkangels.Obstacle) {
if el.GetSize()-_const.MinSizeAlive < _const.MinSizeAlive || el.Count() >= _const.SplitMaxCount {
return poisons
}
poisons = make([]checkangels.Obstacle, 0, len(plants)/10)
for i := 0; i < len(plants); i++ {
el1 := plants[i]
if el == nil || el1 == nil || el1.GetDead() {
continue
}
if el1.GetSize() < el.GetSize() && el1.GetDanger() {
poisons = append(poisons, checkangels.NewPoint(el1))
}
}
return
}
func getClosest(el animal.Animal, els []alive.Alive, animal bool, repeat int, dAngeles checkangels.Angels) (closest *crd.Crd, split bool) {
dist := 9e+5
mass := 0.0
obstacle := true
for i := 0; i < len(els); i++ {
el1 := els[i]
if el1 == nil {
continue
}
distRes := -1.0
var vec vector.Vector
distFn := func() float64 {
if distRes == -1.0 {
vec = vector.GetVectorByPoint(el.GetCrd(), el1.GetCrd())
distRes = vec.Len() - el.GetSize()
}
return distRes
}
if el != nil && el1 != nil && !el1.GetDanger() &&
el.GetSize()/el1.GetSize() > _const.EatRatio &&
(mass < el1.GetSize() || obstacle) && //TODO add equation choice distance or size
el1.GetGroup() != el.GetGroup() && !el1.GetDead() && distFn() < dist &&
distFn() < el.GetVision() {
vecAngel := geom.ModuleDegree(vec.GetAngle())
reachable, dangerous := dAngeles.Check(vecAngel, distRes)
if !reachable && !obstacle {
continue
}
cr := el1.GetCrd()
if reachable {
obstacle = false
} else if dangerous {
angel := dAngeles.ClosestAvailable(vecAngel)
vec.SetAngle(angel)
cr = vec.GetPointFromVector(el.GetCrd())
if rabl := func() bool {
if repeat > 5 {
return false
}
cCrd := el.GetCrd()
el.SetCrd(cr)
defer el.SetCrd(cCrd)
if cl, _ := getClosest(el, []alive.Alive{el1}, animal, repeat + 1, dAngeles); cl == nil || *cl != el1.GetCrd() {
return false
}
return true
}(); !rabl {
continue
}
}
closest = &cr
dist = distRes
if dist * 1.3 < _const.SplitDist && (el.GetSize()*_const.SplitRatio)/el1.GetSize() > _const.EatRatio && !dangerous && animal {
split = true
break
}
mass = el1.GetSize()
} else {
if !obstacle && i > 10 && mass > 0 && !animal && distFn() > _const.GridSize {
return
}
}
}
return
}
<file_sep>/assets/src/const/Const.ts
export const enum Status {
"playing",
"stop"
}
export const Animal = "animal";
export const Plant = "plant";
export const Size = "size";<file_sep>/world/resurrect.go
package world
import (
"agar-life/object/alive"
"agar-life/object/alive/animal"
"agar-life/world/const"
"agar-life/world/frame"
gnt "agar-life/world/generate"
)
type resurrect struct {
frame *frame.Frame
el alive.Alive
cycleRevive uint
}
type resurrects struct {
r []resurrect
}
func (r *resurrects) add(frame *frame.Frame, el alive.Alive, cycle uint) {
r.r = append(r.r, resurrect{frame: frame, el: el, cycleRevive: cycle + _const.ResurrectTime})
}
func (r *resurrects) resurrect(cycle uint, w, h float64) {
for i := 0; i < len(r.r); i++ {
el := r.r[i]
if el.cycleRevive <= cycle {
alv := el.el
if _, ok := alv.(animal.Animal); ok {
gnt.Generate(alv, gnt.WorldWH(w, h), gnt.Size(6))
} else {
gnt.Generate(alv, gnt.WorldWH(w, h))
}
el.frame.Add(alv)
el.frame.SetUpdateState(true)
r.r = removeFromResurrect(r.r, i)
i--
}
}
}
func removeFromResurrect(a []resurrect, i int) []resurrect {
a[i] = a[len(a)-1] // Copy last element to index i.
a = a[:len(a)-1]
return a
}
<file_sep>/world/space.go
package world
import (
math2 "agar-life/math"
"agar-life/math/crd"
"agar-life/math/geom"
"agar-life/math/vector"
"agar-life/object/alive"
"agar-life/object/alive/animal"
"agar-life/object/alive/animal/behavior/ai"
"agar-life/object/alive/animal/species"
"agar-life/object/alive/plant"
sp "agar-life/object/alive/plant/species"
"agar-life/world/const"
"agar-life/world/frame"
"agar-life/world/frame/grid"
gnt "agar-life/world/generate"
"encoding/json"
"math"
"sort"
"strconv"
"strings"
)
type World struct {
w, h float64
animal frame.Frame
plant frame.Frame
cycle uint
gridPlant grid.Grid //TODO move grid index to frame
gridAnimal grid.Grid
resurrect resurrects
countPlant uint
countAnimal uint
action bool
}
func NewWorld(countPlant, countAnimal int, w, h float64) World {
world := World{
w: w,
h: h,
gridPlant: grid.NewArray(_const.GridSize, w, h),
gridAnimal: grid.NewArray(_const.GridSize, w, h),
animal: frame.NewFrame(countAnimal, w, h),
plant: frame.NewFrame(countPlant, w, h),
countAnimal: uint(countAnimal),
countPlant: uint(countPlant),
}
for i := 0; i < countAnimal; i++ {
el := species.NewBeast(ai.NewAiv1(w, h))
gnt.Generate(el, gnt.WorldWH(w, h), gnt.Name("a"+strconv.Itoa(i)), gnt.Size(_const.AliveStartSize))
world.gridAnimal.Set(el.GetX(), el.GetY(), el.GetSize(), i)
world.animal.Set(i, el)
}
for i := 0; i < countPlant; i++ {
var el plant.Plant
if poison() {
el = sp.NewPoison()
} else {
el = sp.NewPlant()
}
gnt.Generate(el, gnt.WorldWH(w, h), gnt.Name("p"+strconv.Itoa(i)))
world.gridPlant.Set(el.GetX(), el.GetY(), el.GetSize(), i)
world.plant.Set(i, el)
}
return world
}
func poison() bool {
return math2.Random(0, 10) > 8
}
func (w *World) Cycle() {
first := true
if w.cycle > 0 && !w.action {
first = false
w.plant.SetUpdateState(false)
} else {
w.action = false
}
removeList := rmList{}
for i := 0; i < len(w.animal.All()); i++ {
el := w.animal.Get(i).(animal.Animal)
if el.GetDead() {
continue
}
idC, inner, closest := getClosest(w.gridAnimal, el, w.animal, i)
closestAnimal := append(w.forIntersect(el, closest[:inner], idC[:inner], &w.animal, &removeList), closest[inner:]...)
idC, inner, closest = getClosest(w.gridPlant, el, w.plant, -1)
closestPlant := append(w.forIntersect(el, closest[:inner], idC[:inner], &w.plant, &removeList), closest[inner:]...)
var direction crd.Crd
split := false
dist := el.GetSpeed()
if directionL, speed := el.GetInertia(); speed > 0 {
direction, dist = directionL, speed
el.SetCrdByDirection(el, direction, dist, first)
} else {
direction, split = el.Action(closestAnimal, closestPlant, w.cycle)
if split {
Split(&w.animal, el, direction, w.cycle)
}
direction = w.fixNeighborhood(el, direction)
el.SetCrdByDirection(el, direction, dist, first)
}
w.fixLimit(el)
grow(el)
if el.GetSize() < el.GetViewSize() && el.GetGrowSize() >= 0 {
}
}
w.resurrect.resurrect(w.cycle, w.w, w.h)
w.remove(removeList)
w.gridAnimal.Reset()
for i := 0; i < len(w.animal.All()); i++ {
el := w.animal.Get(i)
w.gridAnimal.Set(el.GetX(), el.GetY(), el.GetSize(), i)
}
if w.plant.UpdateState() {
w.gridPlant.Reset()
for i := 0; i < len(w.plant.All()); i++ {
el := w.plant.Get(i)
w.gridPlant.Set(el.GetX(), el.GetY(), el.GetSize(), i)
}
}
w.cycle++
w.countAnimal++
}
func grow(el animal.Animal) {
if el.GetSize() == el.GetViewSize() {
return
}
if math.Abs(el.GetSize()-el.GetViewSize()) > math.Abs(el.GetGrowSize())*2 {
el.SetViewSize(el.GetViewSize() + el.GetGrowSize())
} else {
el.SetViewSize(el.GetSize())
}
}
func (w *World) fixNeighborhood(el animal.Animal, dir crd.Crd) crd.Crd {
var parent animal.Animal
if parent = el.GetParent(); parent == nil {
return dir
}
intersected := false
sum := vector.GetVectorByPoint(el.GetCrd(), el.GetCrd())
for _, v := range parent.GetChildren() {
var el1 animal.Animal
if v.GetID() == el.GetID() {
el1 = parent
} else {
el1 = v
}
if el.GetGlueTime() <= w.cycle && el1.GetGlueTime() <= w.cycle {
continue
}
dis := geom.GetDistanceByCrd(el.GetCrd(), el1.GetCrd())
if dis < el.GetSize()+el1.GetSize() {
intersected = true
sum = vector.Add(sum, vector.GetVectorWithLength(el1.GetCrd(), el.GetCrd(), el.GetSize()+el1.GetSize()))
}
}
if intersected {
dir = sum.GetPointFromVector(el.GetCrd())
}
return dir
}
func (w World) GetPlant() []alive.Alive {
var el []alive.Alive
if !w.plant.UpdateState() {
return el
}
return w.plant.All()
}
func (w World) GetCycle() uint {
return w.cycle
}
type Alive struct {
ID int
Size float64
Typ string
}
func (w World) GetID(x, y float64) string {
id, typ := w.get(x, y)
if id == -1 {
return ""
}
var el alive.Alive
if typ == _const.AnimalTypeAlive {
el = w.animal.Get(id)
} else {
el = w.plant.Get(id)
}
exp := Alive{ID: el.GetID(), Size: el.GetSize(), Typ: typ}
jData, err := json.MarshalIndent(exp, "", "\t")
if err != nil {
println(err)
return ""
}
return string(jData)
}
func (w World) get(x, y float64) (int, string) {
radius := float64(_const.PoisonSize)
cr := crd.NewCrd(x, y)
for radius < 200 {
inGrid := func(fr *frame.Frame, gr grid.Grid) int {
idInt, _ := gr.GetObjInRadius(x, y, radius, radius, -1)
for _, index := range idInt {
el1 := fr.Get(index)
dist := geom.GetDistanceByCrd(cr, el1.GetCrd())
if dist < el1.GetSize() {
return index
}
}
return -1
}
if index := inGrid(&w.animal, w.gridAnimal); index != -1 {
return index, _const.AnimalTypeAlive
}
if radius == float64(_const.PoisonSize) {
if index := inGrid(&w.plant, w.gridPlant); index != -1 {
return index, _const.PlantTypeAlive
}
}
radius += 50
}
return -1, ""
}
type ElType struct {
Type string
}
func (w *World) GetEl(x, y float64) string {
id, typ := w.get(x, y)
if id == -1 {
return ""
}
var el alive.Alive
if typ == _const.AnimalTypeAlive {
el = w.animal.Get(id)
} else {
el = w.plant.Get(id)
}
exp := struct {
Type string
El alive.Alive
}{typ, el}
jData, err := json.MarshalIndent(exp, "", "\t")
if err != nil {
println(err)
}
w.deleteBYIndex(id, typ)
return string(jData)
}
type animalType struct {
Type string
El Animal
}
type plantType struct {
Type string
El Plant
}
func (w *World) AddFromJSON(data string, x, y float64) string {
if data == "" {
return ""
}
var typ ElType
err := json.NewDecoder(strings.NewReader(data)).Decode(&typ)
if err != nil {
println(err)
return ""
}
var el1 alive.Alive
if typ.Type == _const.AnimalTypeAlive {
var infoEl animalType
err := json.NewDecoder(strings.NewReader(data)).Decode(&infoEl)
if err != nil {
println(err)
return ""
}
an := infoEl.El
an.X = x
an.Y = y
var parent animal.Animal
if an.Parent != nil {
if parentID := w.getIndexByID(*an.Parent, _const.AnimalTypeAlive); parentID != -1 {
parent = w.animal.Get(parentID).(animal.Animal)
}
}
el1 = createAnimalFromJSON(an, w.w, w.w, parent)
w.animal.Add(el1)
}
if typ.Type == _const.PlantTypeAlive {
var infoEl plantType
err := json.NewDecoder(strings.NewReader(data)).Decode(&infoEl)
if err != nil {
println(err)
return ""
}
pl := infoEl.El
pl.X = x
pl.Y = y
el1 = createPlantFromJSON(pl)
w.plant.Add(el1)
w.plant.SetUpdateState(true)
w.action = true
}
exp := struct {
Type string
El alive.Alive
}{typ.Type, el1}
jData, err := json.MarshalIndent(exp, "", "\t")
if err != nil {
println(err)
}
return string(jData)
}
type elInfo struct {
ID int
Size float64
Type string
}
func (w *World) SetSize(data string) {
var info elInfo
err := json.NewDecoder(strings.NewReader(data)).Decode(&info)
if err != nil {
println(err)
return
}
if index := w.getIndexByID(info.ID, info.Type); index != -1 {
var el alive.Alive
if info.Type == _const.AnimalTypeAlive {
el = w.animal.Get(index)
}
if info.Type == _const.PlantTypeAlive {
el = w.plant.Get(index)
}
if el == nil {
return
}
el.SetSize(info.Size)
}
}
func (w *World) DeleteByID(id int, typ string) {
w.deleteBYIndex(w.getIndexByID(id, typ), typ)
}
func (w *World) deleteBYIndex(index int, typ string) {
if index == -1 {
return
}
if typ == _const.AnimalTypeAlive {
w.animal.Delete(index)
} else {
w.plant.Delete(index)
w.plant.SetUpdateState(true)
}
w.action = true
}
func (w World) getIndexByID(id int, typ string) int {
getEl := func(fr frame.Frame) int {
for index, el := range fr.All() {
if el.GetID() == id {
return index
}
}
return -1
}
if typ == _const.AnimalTypeAlive {
return getEl(w.animal)
}
if typ == _const.PlantTypeAlive {
return getEl(w.plant)
}
return -1
}
func (w *World) GetAnimal() []alive.Alive {
return w.animal.All()
}
type remove struct {
index int
fr *frame.Frame
}
type rmList struct {
list []remove
}
func (r *rmList) add(index int, fr *frame.Frame) {
r.list = append(r.list, remove{
index: index,
fr: fr,
})
}
func (r rmList) Len() int { return len(r.list) }
func (r rmList) Less(i, j int) bool { return r.list[i].index > r.list[j].index }
func (r rmList) Swap(i, j int) { r.list[i], r.list[j] = r.list[j], r.list[i] }
func (w *World) remove(m rmList) {
if len(m.list) > 1 {
sort.Sort(m)
}
for i := 0; i < len(m.list); i++ {
v := m.list[i]
index, fr := v.index, v.fr
if el, ok := fr.Get(index).(animal.Animal); ok {
if el.GetParent() == nil && len(el.GetChildren()) == 0 {
w.resurrect.add(fr, fr.Get(index), w.cycle)
}
} else {
w.resurrect.add(fr, fr.Get(index), w.cycle)
}
fr.Delete(index)
}
}
func (w *World) forIntersect(
el animal.Animal,
closest []alive.Alive,
idInt []int,
fr *frame.Frame,
removeList *rmList,
) []alive.Alive {
for j := 0; j < len(closest); j++ {
index := idInt[j]
el1 := fr.Get(index)
dis := -1.0
dist := func() float64 {
if dis == -1.0 {
dis = geom.GetDistanceByCrd(el.GetCrd(), el1.GetCrd())
}
return dis
}
died := false
if el != nil && el1 != nil && !el1.GetDead() {
if (el.GetSize()/el1.GetSize() > _const.EatRatio || (el.GetGroup() == el1.GetGroup() &&
el1.GetGlueTime() <= w.cycle && el.GetGlueTime() <= w.cycle)) && !el1.GetDanger() && dist() < el.GetSize() {
died = true
el.Eat(el1)
}
if !died && el1.GetDanger() && el1.GetSize() < el.GetSize() && dist() < el.GetSize() {
if Burst(&w.animal, el, w.cycle) {
died = true
}
}
if died {
el1.Die()
removeList.add(index, fr)
fr.SetUpdateState(true)
closest = alive.Remove(closest, j)
idInt = removeFromInt(idInt, j)
j--
}
}
}
return closest
}
func removeFromInt(a []int, i int) []int {
a[i] = a[len(a)-1] // Copy last element to index i.
a[len(a)-1] = 0 // Erase last element (write zero value).
a = a[:len(a)-1]
return a
}
func getClosest(gr grid.Grid, el animal.Animal, fr frame.Frame, ind int) ([]int, int, []alive.Alive) {
idInt, inner := gr.GetObjInRadius(el.GetX(), el.GetY(), el.GetVision(), el.GetSize(), ind)
closest := make([]alive.Alive, 0, len(idInt))
was := map[int]struct{}{}
j := 0
for i := 0; i < len(idInt); i++ {
id := idInt[i]
if _, ok := was[id]; ok {
continue
} else {
//was[id] = struct{}{}
}
closest = append(closest, fr.Get(id))
j++
}
return idInt, inner, closest
}
func (w *World) fixLimit(el animal.Animal) {
x, y := el.GetX(), el.GetY()
if x < 0 {
x = 1
}
if x > w.w {
x = w.w - 1
}
if y < 0 {
y = 1
}
if y > w.h {
y = w.h - 1
}
if x != el.GetX() || y != el.GetY() {
el.SetXY(x, y)
}
}
func NewWorldTest(countPlant, countAnimal int, w, h float64) World {
world := World{
w: w,
h: h,
gridPlant: grid.NewArray(_const.GridSize, w, h),
gridAnimal: grid.NewArray(_const.GridSize, w, h),
animal: frame.NewFrame(countAnimal, w, h),
plant: frame.NewFrame(countPlant, w, h),
}
crAnimal := func(i int, x, y, size float64) {
el := species.NewBeast(ai.NewAiv1(w, h))
//el := species.NewBeast(behavior.NewTestAngel(math.Pi / 2 * -1))
//el := species.NewBeast(behavior.NewSimple(w, h))
//gnt.Generate(el, gnt.WorldWH(w, h), gnt.SetGroup("a"+strconv.Itoa(i)), gnt.SetSize(6))
gnt.Generate(el, gnt.WorldWH(w, h), gnt.Name("a"+strconv.Itoa(i)), gnt.Size(size), gnt.Crd(gnt.FixCrd(x, y)))
world.gridAnimal.Set(el.GetX(), el.GetY(), el.GetSize(), i)
world.animal.Set(i, el)
}
crPlant := func(i int, x, y float64, poison bool) {
var el plant.Plant
if poison {
el = sp.NewPoison()
} else {
el = sp.NewPlant()
}
gnt.Generate(el, gnt.WorldWH(w, h), gnt.Name("p"+strconv.Itoa(i)), gnt.Crd(gnt.FixCrd(x, y)))
world.gridPlant.Set(el.GetX(), el.GetY(), el.GetSize(), i)
world.plant.Set(i, el)
}
//ratio := 6.0
//size := 10.0
//for i :=0; i < countAnimal; i++ {
// fmt.Println(size)
// size += ratio * float64(i)
// crAnimal(i, 50 + float64(i) * float64(i) * 30 + size, 400, size)
//}
//crPlant(0, 30, 50, false)
//crAnimal(0, 110.09, 209.04, 26)
//crAnimal(0, 20, 20, 12)
crAnimal(1, 20, 200, 20)
crAnimal(0, 0, 250, 16)
//crPlant(1, 140, 220, false)
//crPlant(3, 170, 200, false)
//crPlant(4, 140, 180, false)
//crPlant(1, 70, 50)
//crAnimal(0, 150, 200, 18)
crPlant(0, 100, 750, true)
crPlant(1, 100, 710, false)
return world
}
<file_sep>/assets/config/webpack.config.prod.js
'use strict';
const webpackMerge = require('webpack-merge');
const ngw = require('@ngtools/webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const cssnano = require('cssnano');
const helpers = require('./helpers');
module.exports = {
mode: "production",
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx"]
},
output: {
path: helpers.root('public/js'),
publicPath: '/',
filename: '[name].bundle.js',
chunkFilename: '[id].chunk.js'
},
optimization: {
noEmitOnErrors: true,
splitChunks: {
chunks: 'all'
},
runtimeChunk: 'single',
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true
}),
new OptimizeCSSAssetsPlugin({
cssProcessor: cssnano,
cssProcessorOptions: {
discardComments: {
removeAll: true
}
},
canPrint: false
})
]
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
};<file_sep>/math/geom/line.go
package geom
import (
"agar-life/math/crd"
"errors"
"math"
)
type Point struct {
x float64
y float64
}
func NewPoint(x, y float64) Point {
return Point{x:x, y:y}
}
func (l Point) X() float64 {
return l.x
}
func (l Point) Y() float64 {
return l.y
}
type Line struct {
slope float64
y float64
}
func NewLine(a, b Point) Line {
var slope float64
if (b.x - a.x) == 0 {
b.x += 0.01
}
slope = (b.y - a.y) / (b.x - a.x)
y := a.y - slope*a.x
return Line{slope, y}
}
func NewLineCrd(a, b crd.Crd) Line {
var slope float64
ax, ay, bx, by := a.GetX(), a.GetY(), b.GetX(), b.GetY()
if (bx - ax) == 0 {
bx += 0.01
}
slope = (by - ay) / (bx - ax)
y := ay - slope*ax
return Line{slope, y}
}
func (l Line) evalX(x float64) float64 {
return l.slope*x + l.y
}
func (l Line) Intersection(l2 Line) (Point, error) {
if l.slope == l2.slope {
return Point{}, errors.New("the lines do not intersect")
}
x := (l2.y - l.y) / (l.slope - l2.slope)
y := l.evalX(x)
return Point{x, y}, nil
}
func LengthLine(a, b Point) float64 {
d1 := a.x - b.x
d2 := a.y - b.y
return math.Sqrt(
d1*d1 + d2*d2,
)
}
func AngleAxisX(a, b Point) float64 {
return math.Atan2(b.y- a.y, b.x- a.x)
}
<file_sep>/object/alive/animal/behavior/ai/bypass_test.go
package ai
import (
"agar-life/math/crd"
"agar-life/object/alive"
"agar-life/object/alive/animal/behavior"
"agar-life/object/alive/animal/species"
sp "agar-life/object/alive/plant/species"
gnt "agar-life/world/generate"
"strconv"
"testing"
)
var ()
func TestBypass(t *testing.T) {
el := species.NewBase()
gnt.Generate(el, gnt.WorldWH(behavior.w, behavior.h), gnt.Name("a"+strconv.Itoa(1)), gnt.Size(10), gnt.Crd(gnt.FixCrd(100, 100)))
direction := crd.NewCrd(200, 100)
poisons := make([]alive.Alive, 1)
el1 := sp.NewPoison()
gnt.Generate(el1, gnt.WorldWH(behavior.w, behavior.h), gnt.Name("a"+strconv.Itoa(1)), gnt.Size(41), gnt.Crd(gnt.FixCrd(150, 100)))
poisons[0] = el1
bypass(el, direction, poisons)
}
<file_sep>/world/frame/grid/string.go
package grid
import "strconv"
type stringGrid struct {
cellSize float64
data map[string][]int
}
func NewString(size float64, cap int) Grid {
return &stringGrid{
cellSize: size,
data: make(map[string][]int, cap),
}
}
func (g *stringGrid) Len() int {
return len(g.data)
}
func (g *stringGrid) Reset() {
}
func (g *stringGrid) Set(x, y, size float64, i int) {
xInt := int(x / g.cellSize)
yInt := int(y / g.cellSize)
key := stringKey(xInt, yInt)
if _, ok := g.data[key]; ok {
g.data[key] = append(g.data[key], i)
} else {
g.data[key] = []int{i}
}
}
func stringKey(xInt, yInt int) string {
return strconv.Itoa(xInt) +"x:"+ strconv.Itoa(yInt)+"y"
}
func (g *stringGrid) GetObjInRadius(x, y, radius float64, size float64, exclude int) ([]int, int) {
ltx, lty := int((x-radius)/g.cellSize), int((y-radius)/g.cellSize)
rdx, rdy := int((x+radius)/g.cellSize), int((y+radius)/g.cellSize)
var obj []int
for cx := ltx; cx <= rdx; cx++ {
for cy := lty; cy <= rdy; cy++ {
key := stringKey(cx, cy)
if ob, ok := g.data[key]; ok {
obj = append(obj, ob...)
}
}
}
return obj, 0
}<file_sep>/world/import.go
package world
import (
"agar-life/math/crd"
"agar-life/object/alive/animal"
"agar-life/object/alive/animal/behavior"
"agar-life/object/alive/animal/behavior/ai"
"agar-life/object/alive/animal/species"
"agar-life/object/alive/plant"
sp "agar-life/object/alive/plant/species"
_const "agar-life/world/const"
"agar-life/world/frame"
"agar-life/world/frame/grid"
"encoding/json"
"io"
)
type WorldJSON struct {
W float64 `json:"W"`
H float64 `json:"H"`
Cycle uint `json:"Cycle"`
Plants []Plant `json:"Plants"`
Animals []Animal `json:"Animals"`
CountPlant int `json:"CountPlant"`
CountAnimal int `json:"CountAnimal"`
}
type Plant struct {
Color string `json:"Color"`
Size float64 `json:"Size"`
ViewSize float64 `json:"ViewSize"`
GrowSize float64 `json:"GrowSize"`
Hidden bool `json:"Hidden"`
X float64 `json:"X"`
Y float64 `json:"Y"`
Deed bool `json:"Deed"`
Group string `json:"Group"`
ID int `json:"ID"`
Danger bool `json:"Danger"`
Edible bool `json:"Edible"`
}
type Animal struct {
Color string `json:"Color"`
Size float64 `json:"Size"`
ViewSize float64 `json:"ViewSize"`
GrowSize float64 `json:"GrowSize"`
Hidden bool `json:"Hidden"`
X float64 `json:"X"`
Y float64 `json:"Y"`
Deed bool `json:"Deed"`
Group string `json:"Group"`
ID int `json:"ID"`
Danger bool `json:"Danger"`
Edible bool `json:"Edible"`
ChCrd struct {
X float64 `json:"X"`
Y float64 `json:"Y"`
} `json:"ChCrd"`
OldDirection struct {
X float64 `json:"X"`
Y float64 `json:"Y"`
} `json:"OldDirection"`
OldDist float64 `json:"OldDist"`
Inertia struct {
Direction struct {
X float64 `json:"X"`
Y float64 `json:"Y"`
} `json:"Direction"`
Speed float64 `json:"Speed"`
Acceleration float64 `json:"Acceleration"`
} `json:"Inertia"`
Speed float64 `json:"Speed"`
Vision float64 `json:"Vision"`
CycleGlue uint `json:"CycleGlue"`
Children []Animal `json:"Children"`
Behavior struct {
Name string `json:"Name"`
} `json:"Behavior"`
Parent *int `json:"Parent"`
}
type export struct {
W, H float64
Cycle uint
Plants []plant.Plant
Animals []animal.Animal
CountPlant, CountAnimal uint
}
func NewWorldFromFile(reader io.Reader) World {
var data WorldJSON
err := json.NewDecoder(reader).Decode(&data)
if err != nil {
panic(err)
}
w, h := data.W, data.H
world := World{
w: w,
h: h,
gridPlant: grid.NewArray(_const.GridSize, w, h),
gridAnimal: grid.NewArray(_const.GridSize, w, h),
animal: frame.NewFrame(len(data.Animals), w, h),
plant: frame.NewFrame(len(data.Plants), w, h),
cycle: data.Cycle,
}
index := 0
for i := 0; i < len(data.Animals); i++ {
an := data.Animals[i]
if an.Parent != nil {
continue
}
el := createAnimalFromJSON(an, data.W, data.H, nil)
world.gridAnimal.Set(el.GetX(), el.GetY(), el.GetSize(), index)
world.animal.Set(index, el)
index++
if len(an.Children) > 0 {
for _, an := range an.Children {
el1 := createAnimalFromJSON(an, data.W, data.H, el)
world.gridAnimal.Set(el1.GetX(), el1.GetY(), el1.GetSize(), index)
world.animal.Set(index, el1)
index++
}
}
}
world.action = true
world.plant.SetUpdateState(true)
for i := 0; i < len(data.Plants); i++ {
el := createPlantFromJSON(data.Plants[i])
world.gridPlant.Set(el.GetX(), el.GetY(), el.GetSize(), i)
world.plant.Set(i, el)
}
return world
}
func (w *World) ExportWorld() string {
animalExport := w.animal.All()
animals := make([]animal.Animal, 0, len(animalExport))
for _, el := range animalExport {
if el == nil {
continue
}
animals = append(animals, el.(animal.Animal))
}
plantExport := w.plant.All()
plants := make([]plant.Plant, 0, len(plantExport))
for _, el := range plantExport {
if el == nil {
continue
}
plants = append(plants, el.(plant.Plant))
}
exp := export{
W: w.w,
H: w.h,
Cycle: w.cycle,
Plants: plants,
Animals: animals,
CountPlant: w.countPlant,
CountAnimal: w.countAnimal,
}
jData, err := json.MarshalIndent(exp, "", "\t")
if err != nil {
println(err)
}
return string(jData)
}
func createPlantFromJSON(an Plant) plant.Plant {
var el plant.Plant
if an.Danger {
el = sp.NewPoison()
} else {
el = sp.NewPlant()
}
el.SetColor(an.Color)
el.SetSize(an.Size)
el.SetViewSize(an.ViewSize)
el.Revive()
el.SetCrd(crd.NewCrd(an.X, an.Y))
el.SetGroup(an.Group)
el.SetID(an.ID)
el.SetDanger(an.Danger)
el.SetEdible(an.Edible)
return el
}
func createAnimalFromJSON(an Animal, w, h float64, parent animal.Animal) animal.Animal {
var el animal.Animal
if an.Behavior.Name == ai.AIV1Name {
el = species.NewBeast(ai.NewAiv1(w, h))
}
if an.Behavior.Name == behavior.FollowerName {
el = species.NewBeast(behavior.NewFollower())
}
if el == nil {
panic("unexpected behavior")
}
if parent != nil {
el.SetParent(parent)
}
el.SetColor(an.Color)
el.SetSize(an.Size)
el.SetViewSize(an.ViewSize)
el.Revive()
el.SetCrd(crd.NewCrd(an.X, an.Y))
el.SetGroup(an.Group)
el.SetID(an.ID)
el.SetDanger(an.Danger)
el.SetEdible(an.Edible)
el.SetSpeed(an.Speed)
el.SetVision(an.Vision)
el.SetGlueTime(an.CycleGlue)
el.SetInertiaImport(crd.NewCrd(an.Inertia.Direction.X, an.Inertia.Direction.Y), an.Inertia.Speed, an.Inertia.Acceleration)
return el
}
<file_sep>/object/alive/animal/behavior/checkangels/angel.go
package checkangels
import (
m2 "agar-life/math"
"agar-life/math/crd"
"agar-life/math/geom"
"agar-life/math/vector"
"agar-life/object/alive"
"agar-life/object/alive/animal"
"math"
)
type rangeAngels struct {
dangerous bool
dist float64
}
type keyRange struct {
start, finish int
}
type mapRange map[keyRange]rangeAngels
type Angels struct {
rangeAngels mapRange
angel int
first int
}
func (a Angels) Angel() int {
return a.angel
}
func (a *Angels) Check(angel, dist float64) (reachable, dangerous bool) {
if len(a.rangeAngels) == 0 {
return true, false
}
number := int(angel*100) / a.angel
if number == 0 {
number = a.first / a.angel
}
key := keyRange{number * a.angel, number*a.angel - a.angel}
if v, ok := a.rangeAngels[key]; ok {
return dist < v.dist, v.dangerous
}
return true, false
}
func (a *Angels) ClosestAvailable(angel float64) (newAngel float64) {
if len(a.rangeAngels) == 0 {
return angel
}
number := int(angel*100) / a.angel
if number == 0 {
number = a.first / a.angel
}
angelL := number*a.angel - a.angel
angelR := number*a.angel + a.angel
correct := func() {
if angelR > 628 {
angelR = 0
}
if angelL <= 0 {
angelL = a.first
}
}
correct()
for angelR != a.angel*number {
key := keyRange{angelR + a.angel, angelR}
if _, ok := a.rangeAngels[key]; !ok {
return float64(angelR+a.angel) / 100
}
key = keyRange{angelL, angelL - a.angel}
if _, ok := a.rangeAngels[key]; !ok {
return float64(angelL-a.angel) / 100
}
angelL -= a.angel
angelR += a.angel
correct()
}
return angel
}
func CheckAngels(el animal.Animal, obstacles []Obstacle) (ang Angels) {
if len(obstacles) == 0 {
return ang
}
count := int((el.GetVision() * math.Pi * 2) / el.GetSize())
for count%4 != 0 {
count++
}
addAngel := m2.Round(2.0 * math.Pi / float64(count))
addInrAngel := int(2.0 * math.Pi / float64(count) * 100)
addAngelD := addAngel * 2
angel := 0.0
sift := float64(count / 4.0)
shiftCorrect := 0.0
angelV := angel + addAngel*sift - shiftCorrect + addAngel
xd := el.GetX() + el.GetVision()*math.Cos(angelV)
yd := el.GetY() + el.GetVision()*math.Sin(angelV)
vec := vector.GetVectorByPoint(crd.NewCrd(el.GetX(), el.GetY()), crd.NewCrd(xd, yd))
dirAngel := int(geom.ModuleDegree(vec.GetAngle())*100) / addInrAngel
dirAngel = dirAngel * addInrAngel
rangAng := make(mapRange, len(obstacles))
first := dirAngel + addInrAngel
obsQuarters := make([]quarter, len(obstacles))
for k, v := range obstacles {
obsQuarters[k] = getQuarter(el, v)
}
var line1 geom.Segment
var line2 geom.Segment
var line3 geom.Segment
for i := 0; i < (count); i++ {
calculated := false
calculateLine := func() {
if calculated {
return
}
xs1 := el.GetX() + el.GetSize()*math.Cos(angel)
ys1 := el.GetY() + el.GetSize()*math.Sin(angel)
angel += math.Pi
xs2 := el.GetX() + el.GetSize()*math.Cos(angel)
ys2 := el.GetY() + el.GetSize()*math.Sin(angel)
angel -= math.Pi
angelV = angel + addAngel*sift - shiftCorrect
xf1 := el.GetX() + el.GetVision()*math.Cos(angelV)
yf1 := el.GetY() + el.GetVision()*math.Sin(angelV)
angelV += addAngelD
xf2 := el.GetX() + el.GetVision()*math.Cos(angelV)
yf2 := el.GetY() + el.GetVision()*math.Sin(angelV)
line1 = geom.NewSegment(crd.NewCrd(xs1, ys1), crd.NewCrd(xf1, yf1))
line2 = geom.NewSegment(crd.NewCrd(xf1, yf1), crd.NewCrd(xf2, yf2))
line3 = geom.NewSegment(crd.NewCrd(xs2, ys2), crd.NewCrd(xf2, yf2))
calculated = true
}
if dirAngel == 0 {
dirAngel = first
}
for k, v := range obstacles {
if !obsQuarters[k].check(dirAngel) {
continue
}
calculateLine()
if intersect, dist := v.check(el.GetCrd(), el.GetSize(), line1, line2, line3); intersect {
addToRange(rangAng, dirAngel, dirAngel - addInrAngel, dist, v.dangerous())
if dirAngel == first || dirAngel-addInrAngel == 0 {
addToRange(rangAng, first, first - addInrAngel, dist, v.dangerous())
}
//break
}
}
dirAngel -= addInrAngel
angel += addAngel
}
ang.angel = addInrAngel
ang.rangeAngels = rangAng
ang.first = first
return ang
}
func addToRange(m mapRange, start, end int, dist float64, dangerous bool) {
if v, ok := m[keyRange{start, end}]; ok {
if v.dist > dist {
m[keyRange{start, end}] = rangeAngels{
dangerous: dangerous,
dist: dist,
}
}
return
}
m[keyRange{start, end}] = rangeAngels{
dangerous: dangerous,
dist: dist,
}
}
type quarter struct {
intersect bool
parts []int8
}
func (q quarter) check(angel int) bool {
if q.intersect {
return true
}
quarter := int8(-1)
if angel >= 0 && angel < 157 {
quarter = 3
} else if angel >= 157 && angel < 314 {
quarter = 2
} else if angel >= 314 && angel < 471 {
quarter = 1
} else {
quarter = 4
}
for _, v := range q.parts {
if v == quarter {
return true
}
}
return false
}
func getQuarter(el alive.Alive, obs Obstacle) (q quarter) {
if !obs.isPoint() {
q.intersect = true
return
}
dist := geom.GetDistanceByCrd(el.GetCrd(), obs.center())
if dist < el.GetSize()+obs.size() {
q.intersect = true
return
}
if obs.center().GetX()+obs.size() >= el.GetX()-el.GetSize() && obs.center().GetY()+obs.size() >= el.GetY()-el.GetSize() {
q.parts = append(q.parts, 3)
}
if obs.center().GetX()+obs.size() >= el.GetX()-el.GetSize() && obs.center().GetY()-obs.size() <= el.GetY()+el.GetSize() {
q.parts = append(q.parts, 2)
}
if obs.center().GetX()-obs.size() <= el.GetX()+el.GetSize() && obs.center().GetY()-obs.size() <= el.GetY()+el.GetSize() {
q.parts = append(q.parts, 1)
}
if obs.center().GetX()-obs.size() <= el.GetX()+el.GetSize() && obs.center().GetY()+obs.size() >= el.GetY()-el.GetSize() {
q.parts = append(q.parts, 4)
}
return
}
type Obstacle interface {
check(center crd.Crd, size float64, lines ...geom.Segment) (bool, float64)
dangerous() bool
isPoint() bool
size() float64
center() crd.Crd
}
type point struct {
outer []geom.Segment
inner []geom.Segment
centerEl crd.Crd
sizeEL float64
}
func NewPoint(el alive.Alive) Obstacle {
p := point{
sizeEL: el.GetSize(),
centerEl: el.GetCrd(),
outer: []geom.Segment{
geom.NewSegment(crd.NewCrd(el.GetX()-el.GetSize(), el.GetY()), crd.NewCrd(el.GetX()+el.GetSize(), el.GetY())),
geom.NewSegment(crd.NewCrd(el.GetX(), el.GetY()-el.GetSize()), crd.NewCrd(el.GetX(), el.GetY()+el.GetSize())),
},
inner: []geom.Segment{
geom.NewSegment(crd.NewCrd(0, el.GetY()), crd.NewCrd(el.GetX()+9e+2, el.GetY())),
geom.NewSegment(crd.NewCrd(el.GetX(), 0), crd.NewCrd(el.GetX(), el.GetY()+9e+2)),
},
}
return &p
}
func (p point) dangerous() bool {
return true
}
func (p point) size() float64 {
return p.sizeEL
}
func (p point) center() crd.Crd {
return p.centerEl
}
func (p point) isPoint() bool {
return true
}
func (p *point) check(center crd.Crd, size float64, lines ...geom.Segment) (bool, float64) {
res := func() (bool, float64) {
dist := geom.GetDistanceByCrd(center, p.centerEl)
if dist > p.sizeEL+size {
dist -= p.sizeEL + size
} else {
dist = math.Max(dist-(p.sizeEL*0.3+size), 0)
}
return true, dist
}
for _, v := range p.outer {
for _, line := range lines {
if v.Intersection(line) {
return res()
}
}
}
countIntersect := 0
for _, v := range p.inner {
localCountIntersect := 0
for _, line := range lines {
if v.Intersection(line) {
localCountIntersect++
if localCountIntersect >= 2 {
break
}
}
}
countIntersect += localCountIntersect
if countIntersect < 1 {
break
}
}
if countIntersect >= 3 {
return res()
}
return false, 0
}
type line struct {
line geom.Segment
}
func NewLine(l geom.Segment) Obstacle {
return &line{
line: l,
}
}
func (l line) dangerous() bool {
return false
}
func (l line) isPoint() bool {
return false
}
func (l line) size() float64 {
return 0
}
func (l line) center() crd.Crd {
return l.line.Start()
}
func (l *line) check(center crd.Crd, size float64, lines ...geom.Segment) (bool, float64) {
line := geom.NewSegment(center, lines[1].MidPoint())
if l.line.Intersection(line) {
_, cr := l.line.IntersectionPoint(line)
return true, geom.GetDistanceByCrd(center, cr) - size
}
return false, 0
}
<file_sep>/object/alive/animal/behavior/testangel.go
package behavior
import (
"agar-life/math/crd"
"agar-life/object/alive"
"agar-life/object/alive/animal"
"math"
)
type testAngel struct {
direction crd.Crd
angel float64
t float64
}
func NewTestAngel(angel float64) animal.Behavior {
return &testAngel{angel: angel}
}
func (a *testAngel) Action(self animal.Animal, animals []alive.Alive, plants []alive.Alive, cycle uint) (crd.Crd, bool) {
//vec := vector.GetVectorByPoint(self.GetCrd(), crd.NewCrd(self.GetX()+self.GetVision(), self.GetY()))
//vec.SetAngle(a.angel)
//a.direction.SetCrd(vec.GetPointFromVector(self.GetCrd()))
cx := 400.0
cy := 200.0
r := 200.0
x:=cx+r * math.Cos(a.t)
y:=cy+r * math.Sin(a.t)
a.t++
a.direction.SetXY(x, y)
return a.direction, false
}
<file_sep>/object/alive/animal/interface.go
package animal
import (
"agar-life/math/crd"
"agar-life/object/alive"
)
type Parent interface {
GetParent() Animal
SetParent(Animal)
}
type Children interface {
Child(int) Animal
AddChild(Animal)
SetCountChildren(int)
DeleteChild(int)
GetChildren() []Animal
}
type Animal interface {
alive.Alive
Parent
Children
SetSpeed(float64)
GetSpeed() float64
SetVision(float64)
GetVision() float64
SetBehaviour(Behavior)
GetBehaviour() Behavior
Eat(a alive.Alive)
Action(animals []alive.Alive, plants []alive.Alive, cycle uint) (crd.Crd, bool)
Direction() crd.Crd
SetCrdByDirection(a alive.Alive, direction crd.Crd, dist float64, changeDirection bool)
GetInertia() (direction crd.Crd, speed float64)
SetInertia(direction crd.Crd)
SetInertiaImport(direction crd.Crd, speed, acceleration float64)
Count() int
}
func Remove(a []Animal, i int) []Animal {
a[i] = a[len(a)-1] // Copy last element to index i.
a[len(a)-1] = nil // Erase last element (write zero value).
a = a[:len(a)-1]
return a
}
<file_sep>/object/alive/plant/species/base.go
package species
import (
"agar-life/object/alive"
"agar-life/object/alive/plant"
)
type Base struct {
alive.Base
}
func NewBase() plant.Plant{
return &Base{}
}
<file_sep>/object/alive/animal/species/base.go
package species
import (
"agar-life/math/crd"
"agar-life/object/alive"
"agar-life/object/alive/animal"
_const "agar-life/world/const"
"agar-life/world/move"
"encoding/json"
"math"
)
type Base struct {
alive.Base
move.Move
Speed float64
Vision float64
CycleGlue uint
Parent animal.Animal `json:"-"`
Children []animal.Animal
Behavior animal.Behavior
}
type JsonBase struct {
Base
Parent *int
}
func (b *Base) MarshalJSON() ([]byte, error) {
returnObj := JsonBase{}
returnObj.Base = *b
if b.Parent != nil {
parentID := b.Parent.GetID()
returnObj.Parent = &parentID
}
return json.Marshal(returnObj)
}
func NewBase() animal.Animal {
return &Base{
Speed: 0,
Vision: 0,
}
}
func (b Base) Child(i int) animal.Animal {
if len(b.Children) > i {
return b.Children[i]
}
return nil
}
func (b *Base) AddChild(child animal.Animal) {
b.Children = append(b.Children, child)
}
func (b *Base) SetCountChildren(count int) {
b.Children = make([]animal.Animal, 0, count)
}
func (b *Base) SetBehaviour(behavior animal.Behavior) {
b.Behavior = behavior
}
func (b Base) GetBehaviour() animal.Behavior {
return b.Behavior
}
func (b Base) GetGlueTime() uint {
return b.CycleGlue
}
func (b Base) Count() int {
if len(b.GetChildren()) > 0 {
return len(b.GetChildren()) + 1
}
if parent := b.GetParent(); parent != nil {
return len(parent.GetChildren()) + 1
}
return 1
}
func (b *Base) SetGlueTime(cycle uint) {
b.CycleGlue = cycle + _const.GlueTime
}
func (b *Base) DeleteChild(id int) {
if index := getIndexByID(b.Children, id); index != -1 {
b.Children = animal.Remove(b.Children, index)
}
}
func getIndexByID(a []animal.Animal, id int) int {
for k, v := range a {
if id == v.GetID() {
return k
}
}
return -1
}
func (b Base) GetChildren() []animal.Animal {
return b.Children
}
func (b Base) GetParent() animal.Animal {
return b.Parent
}
func (b *Base) SetParent(a animal.Animal) {
b.Parent = a
}
func (b *Base) SetSize(size float64) {
b.Base.SetSize(size)
b.SetSpeed(reduce(size))
b.SetVision(_const.StartVision + b.GetSize()*(_const.VisionRatio-math.Log(b.GetSize())))
}
func reduce(i float64) float64 {
return (_const.StartSpeed - math.Log(i*_const.SpeedRatio)) / 10
}
func (b *Base) SetSpeed(speed float64) {
if speed <= 0 {
panic("Speed less than 0")
}
b.Speed = speed
}
func (b Base) GetSpeed() float64 {
return b.Speed
}
func (b *Base) SetVision(vision float64) {
b.Vision = vision
}
func (b Base) GetVision() float64 {
return b.Vision
}
func (b *Base) Action(animals []alive.Alive, plants []alive.Alive, cycle uint) (crd.Crd, bool) {
return crd.Crd{}, false
}
func (b *Base) Direction() crd.Crd {
return b.Move.GetDirection()
}
func (b *Base) Eat(el alive.Alive) {
if el.GetDead() {
return
}
eatRation := _const.EatIncreaseRation
if b.GetGroup() == el.GetGroup() {
eatRation = _const.EatSelfIncreaseRation
}
b.SetSize(b.GetSize() + (el.GetSize() * eatRation))
}
<file_sep>/object/alive/animal/behavior/simple.go
package behavior
import (
math2 "agar-life/math"
"agar-life/math/crd"
"agar-life/math/geom"
"agar-life/math/vector"
"agar-life/object/alive"
"agar-life/object/alive/animal"
"agar-life/object/alive/animal/behavior/checkangels"
"math"
)
type Simple struct {
w, h float64
direction crd.Crd
chCrd crd.Crd
changeDirection bool
}
func (s *Simple) SetSize(w, h float64) {
s.w, s.h = w, h
}
func (s *Simple) SetDir(direction crd.Crd) {
s.direction = direction
}
func (s *Simple) Dir() crd.Crd {
return s.direction
}
func (s *Simple) SetChangeDir(changeDirection bool) {
s.changeDirection = changeDirection
}
func (s Simple) W() float64 {
return s.w
}
func (s Simple) H() float64 {
return s.h
}
func NewSimple(w, h float64) Simple {
s := Simple{
w: w, h: h,
changeDirection: true,
}
return s
}
func (s *Simple) SetDirection(self animal.Animal, direction crd.Crd) {
s.direction = vector.GetCrdWithLength(self.GetCrd(), s.direction, self.GetVision())
}
func (s *Simple) Action(self animal.Animal, animals, plants []alive.Alive, cycle uint64, dAngeles checkangels.Angels) (crd.Crd, bool) {
if s.direction.GetX() == 0 && s.direction.GetY() == 0 {
//s.direction = crd.NewCrd(float64(math2.Random(0, int(s.w))), float64(math2.Random(0, int(s.h))))
}
vec := vector.GetVectorWithLength(self.GetCrd(), s.direction, self.GetVision())
if change() {
part := 6.0
addAngel := randomFloat(-1 * math.Pi / part, math.Pi / part)
vec.AddAngle(addAngel)
}
vecAngel := geom.ModuleDegree(vec.GetAngle())
reachable, _ := dAngeles.Check(vecAngel, vec.Len())
if !reachable {
angel := dAngeles.ClosestAvailable(vecAngel)
vec.SetAngle(angel)
}
return vec.GetPointFromVector(self.GetCrd()), false
}
func randomFloat(min, max float64) float64 {
minInt := int(min * 100)
maxInt := int(max * 100)
rand := math2.Random(minInt, maxInt)
return float64(rand) / 100
}
func change() bool {
return math2.Random(0, 100) > 90
}
<file_sep>/object/base.go
package object
import (
math2 "agar-life/math"
"agar-life/math/crd"
_const "agar-life/world/const"
)
//Base is basic realization on object interface
type Base struct {
Color string
Size float64
ViewSize float64
GrowSize float64
Hidden bool
crd.Crd
}
//GetColor return Color of point
func (p Base) GetColor() string {
return p.Color
}
//SetColor sets a Color for the point
func (p *Base) SetColor(color string) {
p.Color = color
}
//GetSize return Size of point
func (p Base) GetSize() float64 {
return p.Size
}
//SetSize sets a Size for the point
func (p *Base) SetSize(size float64) {
newSize := math2.Round(size)
p.GrowSize = (newSize - p.ViewSize) / _const.GrowTime
p.Size = newSize
}
//GetViewSize return ViewSize of point
func (p Base) GetViewSize() float64 {
return p.ViewSize
}
//GetGrowSize return GrowSize of point
func (p Base) GetGrowSize() float64 {
return p.GrowSize
}
//SetSize sets a Size for the point
func (p *Base) SetViewSize(size float64) {
if size <= 0 {
p.ViewSize = p.Size
} else {
p.ViewSize = size
}
}
//GetHidden return is Hidden the point
func (p *Base) GetHidden() bool {
return p.Hidden
}
//SetHidden set Hidden property
func (p *Base) SetHidden(isHidden bool) {
p.Hidden = isHidden
}
<file_sep>/world/frame/grid/interface.go
package grid
type Grid interface {
Set(x, y, size float64, i int)
GetObjInRadius(x, y, radius, size float64, exclude int) ([]int, int)
Len() int
Reset()
}
<file_sep>/canvas/canvas.go
package canvas
import (
math2 "agar-life/math"
"agar-life/math/crd"
"agar-life/math/geom"
"agar-life/math/vector"
"agar-life/object"
"agar-life/object/alive"
"agar-life/object/alive/animal"
"agar-life/world/const"
"fmt"
"math"
"strconv"
"syscall/js"
)
type WH struct{ w, h float64 }
type JS struct {
value int
window, doc, body, box js.Value
wh WH
}
func NewJsConnect() JS {
jc := JS{}
jc.window = js.Global()
jc.doc = jc.window.Get("document")
jc.body = jc.doc.Get("body")
jc.box = jc.doc.Call("getElementById", "box")
jc.wh.h = jc.window.Get("innerHeight").Float() - 10
jc.wh.w = jc.box.Get("offsetWidth").Float() - 20
return jc
}
func (j *JS) GetWindow() js.Value {
return j.window
}
func (j *JS) GetW() float64 {
return j.wh.w
}
func (j *JS) GetH() float64 {
return j.wh.h
}
type Canvas interface {
Save()
Restore()
Draw(obj1 object.Object)
Refresh()
Grid(step float64)
}
func (j *JS) NewCanvas(class string) *Base {
canvas := j.doc.Call("createElement", "canvas")
canvas.Set("className", fmt.Sprintf("canvas %s", class))
canvas.Set("height", j.wh.h)
canvas.Set("width", j.wh.w)
j.box.Call("appendChild", canvas)
ctx := canvas.Call("getContext", "2d")
img := j.window.Call("eval", "new Image()")
img.Set("src", "/img/thorn.png")
wait := make(chan struct{})
addImg := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
println("imag loaded")
wait <- struct{}{}
return nil
})
img.Call("addEventListener", "load", addImg)
<-wait
return &Base{canvas: canvas, ctx: ctx, img: img, wh: j.wh}
}
type Base struct {
canvas, ctx, img js.Value
wh WH
}
func (b *Base) Save() {
b.ctx.Call("save")
}
func (b *Base) Restore() {
b.ctx.Call("restore")
}
//js.Global().Set("add", js.NewCallback(add))
func (b *Base) Draw(obj1 object.Object) {
if obj1.GetHidden() {
println("hidden")
return
}
obj := obj1.(alive.Alive)
if obj.GetDanger() {
size := obj.GetViewSize() * 2.15
b.ctx.Call("drawImage", b.img, obj.GetX() - obj.GetViewSize(), obj.GetY()-obj.GetViewSize(), size, size)
} else {
b.ctx.Call("beginPath")
b.ctx.Call("arc", obj.GetX(), obj.GetY(), obj.GetViewSize(), 0, math.Pi*2, false)
b.ctx.Set("fillStyle", obj.GetColor())
b.ctx.Call("fill")
b.ctx.Call("closePath")
}
}
func (b *Base) Refresh() {
b.ctx.Set("fillStyle", "rgb(255, 255, 255)")
b.ctx.Call("fillRect", 0, 0, b.wh.w, b.wh.h)
b.Grid(_const.GridSize)
}
func (b *Base) Grid(step float64) {
b.ctx.Set("strokeStyle", "#cecaca")
for i := step; i < b.wh.w; i += step {
b.ctx.Call("beginPath")
b.ctx.Call("moveTo", i, 0)
b.ctx.Call("lineTo", i, b.wh.h)
b.ctx.Call("stroke")
}
for i := step; i < b.wh.h; i += step {
b.ctx.Call("beginPath")
b.ctx.Call("moveTo", 0, i)
b.ctx.Call("lineTo", b.wh.w, i)
b.ctx.Call("stroke")
}
}
type Animal struct {
Base
}
func (a *Animal) Draw(obj1 object.Object) {
if obj1.GetHidden() {
return
}
obj := obj1.(animal.Animal)
a.Base.Draw(obj)
a.DrawCircle(obj)
if parent := obj.GetParent(); parent == nil {
a.ctx.Call("beginPath")
a.ctx.Call("moveTo", obj.GetX(), obj.GetY())
a.ctx.Call("lineTo", obj.Direction().GetX(), obj.Direction().GetY())
a.ctx.Call("stroke")
}
a.ctx.Set("fillStyle", "#000")
a.ctx.Set("font", "bold 12px Arial")
a.ctx.Call("fillText", strconv.Itoa(obj.Count())+"/"+strconv.Itoa(int(obj.GetSize())), obj.GetX()-obj.GetViewSize(), obj.GetY())
}
func (a *Animal) DrawCircle(obj animal.Animal) {
a.ctx.Call("beginPath")
a.ctx.Set("strokeStyle", "#335dbb")
a.ctx.Call("arc", obj.GetX(), obj.GetY(), obj.GetVision(), 0, math.Pi*2, false)
a.ctx.Call("stroke")
a.ctx.Call("closePath")
}
func (a *Animal) DrawRectangle(obj animal.Animal) {
a.ctx.Call("beginPath")
a.ctx.Call("rect", obj.GetX()-obj.GetVision(), obj.GetY()-obj.GetVision(), 2*obj.GetVision(), 2*obj.GetVision())
a.ctx.Set("strokeStyle", "#335dbb")
a.ctx.Call("stroke")
a.ctx.Set("setLineDash", "[5, 5]")
a.ctx.Call("closePath")
}
func (a *Animal) Draw1(obj1 object.Object) {
el := obj1.(animal.Animal)
a.ctx.Call("beginPath")
a.ctx.Call("arc", el.GetX(), el.GetY(), 2, 0, math.Pi*2, false)
a.ctx.Call("stroke")
count := int((el.GetVision() * math.Pi * 2) / el.GetViewSize())
for count%4 != 0 {
count++
}
addAngel := 2.0 * math.Pi / float64(count)
addAngelV := 2.0 * math.Pi / float64(count) * 2
angel := 0.0
//angel := math.Pi - addAngel
//angel := math.Pi / 2 - addAngel
//angel := math.Pi / 2 * -1 - addAngel
sift := float64(count / 4.0)
shiftCorrect := 0.0
//xs1 := el.GetX() + el.GetViewSize()*math.Cos(angel)
//angelV := angel + addAngel*sift - shiftCorrect
//xf1 := el.GetX() + el.GetVision()*math.Cos(angelV)
//for math.Abs(xf1 - xs1) > 10 {
// shiftCorrect += 0.01
// angelV = angel + addAngel*sift - shiftCorrect
// xf1 = el.GetX() + el.GetVision()*math.Cos(angelV)
//}
//diff := angel + addAngel*sift - addAngel
angelV := 0.0
fmt.Printf("size - %f, count - %f\r\n", el.GetViewSize(), float64(count))
expectedDir := -1.0
for i := 0.0; i < float64(count/4); i++ {
//a.Refresh()
a.ctx.Set("strokeStyle", getRandomColor())
xs1 := el.GetX() + el.GetViewSize()*math.Cos(angel)
ys1 := el.GetY() + el.GetViewSize()*math.Sin(angel)
a.ctx.Call("beginPath")
a.ctx.Call("arc", xs1, ys1, 2, 0, math.Pi*2, false)
a.ctx.Call("stroke")
angel += math.Pi
xs2 := el.GetX() + el.GetViewSize()*math.Cos(angel)
ys2 := el.GetY() + el.GetViewSize()*math.Sin(angel)
a.ctx.Call("beginPath")
a.ctx.Call("arc", xs2, ys2, 2, 0, math.Pi*2, false)
a.ctx.Call("stroke")
angel -= math.Pi
angelV = angel + addAngel*sift - shiftCorrect
xf1 := el.GetX() + el.GetVision()*math.Cos(angelV)
yf1 := el.GetY() + el.GetVision()*math.Sin(angelV)
a.ctx.Call("beginPath")
a.ctx.Call("arc", xf1, yf1, 2, 0, math.Pi*2, false)
a.ctx.Call("stroke")
angelV += addAngelV
xf2 := el.GetX() + el.GetVision()*math.Cos(angelV)
yf2 := el.GetY() + el.GetVision()*math.Sin(angelV)
a.ctx.Call("beginPath")
a.ctx.Call("arc", xf2, yf2, 2, 0, math.Pi*2, false)
a.ctx.Call("stroke")
a.ctx.Call("beginPath")
a.ctx.Call("moveTo", xs1, ys1)
a.ctx.Call("lineTo", xf1, yf1)
a.ctx.Call("stroke")
a.ctx.Call("beginPath")
a.ctx.Call("moveTo", xs2, ys2)
a.ctx.Call("lineTo", xf2, yf2)
a.ctx.Call("stroke")
angelV -= addAngel
xd := el.GetX() + el.GetVision()*math.Cos(angelV)
yd := el.GetY() + el.GetVision()*math.Sin(angelV)
//a.ctx.Call("beginPath")
//a.ctx.Call("moveTo", el.GetX(), el.GetY())
//a.ctx.Call("lineTo", xd, yd)
//a.ctx.Call("stroke")
vec := vector.GetVectorByPoint(crd.NewCrd(el.GetX(), el.GetY()), crd.NewCrd(xd, yd))
fmt.Println(geom.ModuleDegree(vec.GetAngle()))
if expectedDir == -1 {
expectedDir = geom.ModuleDegree(vec.GetAngle())
fmt.Println(expectedDir)
fmt.Println(angel)
} else {
//a.ctx.Set("strokeStyle", "#000")
//vec := vector.GetVectorByPoint(crd.NewCrd(el.GetX(), el.GetY()), crd.NewCrd(el.GetX()+el.GetVision(), el.GetY()))
//fmt.Println(expectedDir - addAngel*i)
//vec.SetAngle(expectedDir - addAngel*i)
//c := vec.GetPointFromVector(crd.NewCrd(el.GetX(), el.GetY()))
//a.ctx.Call("beginPath")
//a.ctx.Call("moveTo", el.GetX(), el.GetY())
//a.ctx.Call("lineTo", c.GetX(), c.GetY())
//a.ctx.Call("stroke")
}
//break
angel += addAngel
}
}
func getRandomColor() string {
r := strconv.FormatInt(int64(math2.Random(80, 255)), 16)
g := strconv.FormatInt(int64(math2.Random(20, 180)), 16)
b := strconv.FormatInt(int64(math2.Random(30, 180)), 16)
return "#" + r + g + b
}
func (a *Animal) Refresh() {
a.ctx.Call("clearRect", 0, 0, a.wh.w, a.wh.h)
}
<file_sep>/object/alive/animal/behavior/simple_test.go
package behavior
import (
"agar-life/object/alive/animal/species"
gnt "agar-life/world/generate"
"testing"
)
var (
w, h = 100.0, 100.0
)
func TestSetDirection(t *testing.T) {
sb := NewSimple(w, h)
animal2 := species.NewBase()
gnt.Generate(animal2, gnt.WorldWH(w, h), gnt.Name("a"), gnt.Size(6))
animal2.SetXY(0, 0)
sb.Action(animal2, nil, nil, 0)
_ = 4
}<file_sep>/object/alive/interface.go
package alive
import "agar-life/object"
type Alive interface {
object.Object
Die()
Revive()
GetDead() bool
Grow()
Decrease()
GetGroup() string
SetGroup(string)
GetID() int
SetID(int)
GetGlueTime() uint
SetGlueTime(uint)
GetDanger() bool
SetDanger(bool)
GetEdible() bool
SetEdible(bool)
}
func Remove(a []Alive, i int) []Alive {
a[i] = a[len(a)-1] // Copy last element to index i.
a[len(a)-1] = nil // Erase last element (write zero value).
a = a[:len(a)-1]
return a
} | 9449d5fa55a7b5cb76cc2e464924e8f0d127134d | [
"JavaScript",
"Go",
"TypeScript",
"Go Module",
"Dockerfile"
] | 56 | Go | sereg/agar-live | 92e7c76b17baccaba4ef6ae440147684e3244329 | 960943d6f874e6acffbb48d36a73a8de08ecf813 |
refs/heads/master | <file_sep>spike-angular-and-elasticsearch
===============================
download : https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-version.tar.gz
start : ELASTICSEARCH_HOME/bin/elasticsearch
default url : http://localhost:9200
health check : http://localhost:9200/_cat/health?v
list all indexes : http://localhost:9200/_cat/indices?v
-------------------------------------------------
create index:
curl -XPUT http://localhost:9200/customer
create document:
curl -XPUT http://localhost:9200/customer/external/_mapping -d '{
"external": {
"properties": {
"name": {"type": "string", "analyzer": "thai"}
}
}
}'
test word wrap:
http://localhost:9200/customer/_analyze?analyzer=thai&text=ประเทศไทย&pretty
insert data via REST Console [PUT]:
-------------------------------------------------
http://localhost:9200/customer/external/1?pretty
{
"name": "รักไทย"
}
http://localhost:9200/customer/external/2?pretty
{
"name": "ไทยรัฐ"
}
http://localhost:9200/customer/external/3?pretty
{
"name": "สมรัก"
}
http://localhost:9200/customer/external/3?pretty
{
"name": "สมไทย"
}
-------------------------------------------------
or insert data via CURL:
curl -XPUT http://localhost:9200/customer/external/1?pretty -d '{
"name": "รักไทย"
}'
curl -XPUT http://localhost:9200/customer/external/2?pretty -d '{
"name": "ไทยรัฐ"
}'
curl -XPUT http://localhost:9200/customer/external/3?pretty -d '{
"name": "สมรัก"
}'
curl -XPUT http://localhost:9200/customer/external/4?pretty -d '{
"name": "สมไทย"
}'
-------------------------------------------------
search with POST:
http://localhost:9200/customer/_search?pretty
{"query":{"match":{"name": "ไทย"}}}
http://localhost:9200/customer/_search?pretty
{"query":{"match":{"name": "สม"}}}
search with GET:
http://localhost:9200/_search?q=name:ไทย&pretty=true
http://localhost:9200/_search?q=name:สม&pretty=true
<file_sep>var searchApp;
searchApp = angular.module('searchApp', []);
wireSearchApplication(searchApp);
function wireSearchApplication(app) {
app.service('SearchService', SearchService);
app.controller('SearchController', ['$scope', 'SearchService', SearchController]);
}
function SearchController($scope, SearchService) {
$scope.items = [];
$scope.init = function() {
};
$scope.jsonToItems = function(result) {
$scope.items = [];
angular.forEach(result.hits.hits, function(value, key){
$scope.items.push(new Item(value._source.name));
});
}
$scope.getItemLength = function() {
return $scope.items.length;
};
$scope.getItem = function(order) {
var index = order - 1;
return $scope.items[index];
};
$scope.addItem = function(description) {
var newItem = new Item(description, false);
$scope.items.push(newItem);
}
$scope.formSubmitted = function() {
if($scope.keyword == '') {
$scope.items = [];
} else {
SearchService.get($scope.keyword, $scope.jsonToItems);
}
}
};
function SearchService($http) {
this.get = function(keyword, callback) {
$http.get('http://localhost:9200/_search?q=name:'+keyword).success(callback);
};
};
function Item(description) {
this.description = description;
}
| ba72dfc86ccbce81e226a8ac8073af27e34b82fd | [
"Markdown",
"JavaScript"
] | 2 | Markdown | boyone/spike-angular-and-elasticsearch | 74f701142bb431b21b63b9c44d33f6dfa4dc81b7 | 6660a381234c373815e6510d3cd107c0ab03c9ae |
refs/heads/master | <repo_name>evettetelyas/koroibos<file_sep>/app/helpers/importHelper.js
const fetchHelper = require('../../app/helpers/fetchHelper')
function formatNa(data) {
switch (data) {
case "NA":
return null
default:
return data
}
};
async function formatter(data) {
var array = []
fetchHelper.asyncForEach(data, async (olympian) => {
let obj = {
name: olympian.Name,
sex: olympian.Sex,
age: formatNa(olympian.Age),
height: formatNa(olympian.Height),
weight: formatNa(olympian.Weight),
team: olympian.Team,
games: olympian.Games,
sport: olympian.Sport,
event: olympian.Event,
medal: formatNa(olympian.Medal),
}
array.push(obj)
})
return array;
};
module.exports = {
formatNa,
formatter,
}<file_sep>/app/models/olympian.js
const environment = process.env.NODE_ENV || 'development';
const configuration = require('../../knexfile')[environment];
const database = require('knex')(configuration);
const all = () => database('olympians')
.select()
const totalMedals = (olympian) => database('olympians')
.select()
.where({name: olympian.name})
.whereNotNull('medal')
.then(total => total.length)
.catch(error => error)
const fetchByAge = (type) => database('olympians')
.select()
.orderBy('age', type)
.limit(1)
.then(total => total)
.catch(error => error)
const totalCompeting = () => database('olympians')
.pluck('name')
.distinct()
.then(total => total.length)
.catch(error => error)
const avgWeight = (gender) => database('olympians')
.select()
.avg('weight')
.where({sex: gender})
.then(total => parseFloat((total[0].avg) || 0).toFixed(2))
.catch(error => error)
const avgAge = () => database('olympians')
.select()
.avg('age')
.then(total => parseFloat(total[0].avg || 0).toFixed(2))
.catch(error => error)
const sportEvents = (sport) => database('olympians')
.select()
.where({sport: sport})
.pluck('event')
.distinct()
const sports = () => database('olympians')
.select()
.pluck('sport')
.distinct()
const events = () => database('olympians')
.select()
.pluck('event')
.distinct()
const eventMedals = (event) => database('olympians')
.select()
.where({event: event})
.whereNotNull('medal')
.then(total => total.length)
.catch(error => error)
const getMedalists = async (id) => database('olympians')
.join('events', 'events.event_name', '=', 'olympians.event')
.where('events.id', id)
.whereNotNull('medal')
.orderBy('olympians.event')
.then(result => result)
.catch(error => error)
module.exports = {
all,
totalMedals,
fetchByAge,
totalCompeting,
avgWeight,
avgAge,
sportEvents,
sports,
events,
eventMedals,
getMedalists
}<file_sep>/app/helpers/formatHelper.js
const Olympian = require('../models/olympian')
const fetchHelper = require('../helpers/fetchHelper')
async function olympianIndex(data) {
let olympianView = []
await fetchHelper.asyncForEach(data, async (olympian) => {
let obj = {
name: olympian.name,
team: olympian.team,
age: olympian.age,
sport: olympian.sport,
total_medals_won: await Olympian.totalMedals(olympian).then(num => num)
}
olympianView.push(obj);
});
return olympianView;
}
async function olympianStats() {
let obj = {
olympian_stats: {
total_competing_olympians: await Olympian.totalCompeting().then(num => num),
average_weight: {
unit: "kg",
male_olympians: await Olympian.avgWeight('M').then(num => num),
female_olympians: await Olympian.avgWeight('F').then(num => num)
},
average_age: await Olympian.avgAge().then(num => num)
}
}
return obj;
}
async function events(sportData) {
let sportAry = []
await fetchHelper.asyncForEach(sportData, async (sport) => {
let obj = {
sport: sport,
events: await Olympian.sportEvents(sport)
}
sportAry.push(obj);
});
return sportAry;
}
async function eventMedalists(data) {
let medalistAry = []
await fetchHelper.asyncForEach(data, async (medalist) => {
let obj = {
name: medalist.name,
team: medalist.team,
age: medalist.age,
medal: medalist.medal
}
medalistAry.push(obj);
});
return medalistAry;
}
async function medalists(data) {
let obj = {
event: data[0].event_name,
medalists: await eventMedalists(data)
}
return obj;
}
module.exports = {
olympianIndex,
olympianStats,
events,
medalists
}<file_sep>/tests/olympian_stats.spec.js
var shell = require('shelljs');
var request = require("supertest");
var app = require('../app');
const environment = process.env.NODE_ENV || 'test';
const configuration = require('../knexfile')[environment];
const database = require('knex')(configuration);
describe('Test the olympians path', () => {
beforeEach(async () => {
await database.raw('truncate table olympians cascade');
let olympians = [
{
name: '<NAME>',
sex: 'F',
age: 30,
height: 100,
weight: 100,
team: 'United States of Evette',
games: '2020 Summer',
sport: 'Cheerleading',
event: 'Cheerleading at 5,000 meters',
medal: 'Gold',
},
{
name: '<NAME>',
sex: 'F',
age: 90,
height: 100,
weight: 100,
team: 'United States of Evette',
games: '2020 Summer',
sport: 'Cheerleading',
event: 'Cheerleading at 5,000 meters',
medal: "Gold",
},
{
name: '<NAME>',
sex: 'F',
age: 10,
height: 100,
weight: 100,
team: 'United States of Evette',
games: '2020 Summer',
sport: 'Cheerleading',
event: 'Cheerleading at 5,000 meters',
medal: "Gold",
},
];
await database('olympians').insert(olympians, 'id');
});
afterEach(() => {
database.raw('truncate table olympians cascade');
});
describe('test olympian_stats GET', () => {
it('happy path', async () => {
const res = await request(app)
.get("/api/v1/olympian_stats");
expect(res.statusCode).toBe(200);
expect(res.body["olympian_stats"]).toHaveProperty('total_competing_olympians');
expect(res.body["olympian_stats"]["total_competing_olympians"]).toBe(3);
expect(res.body["olympian_stats"]).toHaveProperty('average_weight');
expect(res.body["olympian_stats"]["average_weight"]["unit"]).toBe("kg");
expect(res.body["olympian_stats"]["average_weight"]["male_olympians"]).toBe("0.00");
expect(res.body["olympian_stats"]["average_weight"]["female_olympians"]).toBe("100.00");
expect(res.body["olympian_stats"]).toHaveProperty('average_age');
expect(res.body["olympian_stats"]["average_age"]).toBe("43.33");
})
})
});<file_sep>/db/seeds/b_events.js
const Olympian = require('../../app/models/olympian')
async function formatEvents() {
let events = await Olympian.events()
let eventArray = []
for(let i=0; i<events.length;i++){
let obj = {
event_name: events[i],
number_of_medalists: await Olympian.eventMedals(events[i])
}
eventArray.push(obj)
}
return eventArray;
}
exports.seed = function(knex) {
return knex('events').del()
.then(async () => {
const formattedEvents = await formatEvents()
return Promise.all([
knex('events').insert(formattedEvents)
.then(() => console.log('Seeding complete!'))
.catch(error => console.log(`Error seeding data: ${error}`))
])
})
.catch(error => console.log(`Error seeding data: ${error}`));
};
<file_sep>/README.md
# koroibos
BE4 final
## Production URL: https://koroiboss.herokuapp.com/
### Tech Stack
- Node.js
- Express.js
- Knex
- Jest
### To run locally:
- clone down repo
- `$ npm install`
- `$ psql`
- `$ CREATE DATABASE <db name>;`
- `$ \q`
- `$ knex migrate:latest`
- `$ knex seed:run`
### Testing Suite
- `$ psql`
- `$ CREATE DATABASE <db name_test>;`
- `$ \q`
- `$ npm test`
- Coverage

### Endpoints
### [](https://app.getpostman.com/run-collection/3928eb753f59d2d66b31)
#### - `GET /api/v1/olympians`
response:
```
[
{
"name": "<NAME>",
"team": "Romania",
"age": 22,
"sport": "Weightlifting",
"total_medals_won": 0
},
{
"name": "<NAME>",
"team": "Spain",
"age": 23,
"sport": "Gymnastics",
"total_medals_won": 0
},
{ ... }
]
```
#### - `GET /api/v1/olympians?age=(oldest/youngest)`
response:
```
[
{
"name": "<NAME>",
"team": "Romania",
"age": 13,
"sport": "Swimming",
"total_medals_won": 0
}
]
```
#### - `GET /api/v1/olympian_stats`
response:
```
{
"olympian_stats": {
"total_competing_olympians": 2845,
"average_weight": {
"unit": "kg",
"male_olympians": "78.55",
"female_olympians": "61.94"
},
"average_age": "26.23"
}
}
```
#### - `GET /api/v1/events`
response:
```
[
{
"sport": "Archery",
"events": [
"Archery Men's Individual",
"Archery Men's Team",
"Archery Women's Individual",
"Archery Women's Team"
]
},
{
"sport": "Gymnastics",
"events": [
"Gymnastics Men's Pommelled Horse",
"Gymnastics Women's Balance Beam",
"Gymnastics Women's Team All-Around",
"Gymnastics Men's Horse Vault",
"Gymnastics Men's Floor Exercise",
"Gymnastics Women's Uneven Bars",
"Gymnastics Men's Team All-Around",
"Gymnastics Men's Parallel Bars",
"Gymnastics Women's Floor Exercise",
"Gymnastics Men's Horizontal Bar",
"Gymnastics Men's Individual All-Around",
"Gymnastics Women's Horse Vault",
"Gymnastics Women's Individual All-Around",
"Gymnastics Men's Rings"
]
},
{ ... }
]
```
#### - `GET /api/v1/events/:id/medalists`
response:
```
{
"event": "Wrestling Men's Welterweight, Greco-Roman",
"medalists": [
{
"name": "<NAME>",
"team": "Armenia",
"age": 27,
"medal": "Silver"
},
{
"name": "<NAME>",
"team": "Georgia",
"age": 22,
"medal": "Bronze"
},
{ ... }
]
```
### Contributors
- <NAME> (@evettetelyas)
<file_sep>/tests/events.spec.js
var shell = require('shelljs');
var request = require("supertest");
var app = require('../app');
const environment = process.env.NODE_ENV || 'test';
const configuration = require('../knexfile')[environment];
const database = require('knex')(configuration);
describe('Test the olympians path', () => {
beforeEach(async () => {
await database.raw('truncate table olympians cascade');
await database.raw('truncate table events cascade');
let olympians = [
{
name: '<NAME>',
sex: 'F',
age: 30,
height: 100,
weight: 100,
team: 'United States of Evette',
games: '2020 Summer',
sport: 'Cheerleading',
event: 'Cheerleading at 5,000 meters',
medal: 'Gold',
},
{
name: '<NAME>',
sex: 'F',
age: 90,
height: 100,
weight: 100,
team: 'United States of Evette',
games: '2020 Summer',
sport: 'Cheerleading',
event: 'Cheerleading at 10,000 meters',
medal: "Gold",
},
{
name: '<NAME>',
sex: 'F',
age: 10,
height: 100,
weight: 100,
team: 'United States of Evette',
games: '2020 Summer',
sport: 'Cheerleading',
event: 'Cheerleading at 15,000 meters',
medal: "Gold",
},
];
let event = {
event_name: 'Cheerleading at 15,000 meters',
number_of_medalists: 1
}
await database('olympians').insert(olympians, 'id');
await database('events').insert(event, 'id')
});
afterEach(() => {
database.raw('truncate table olympians cascade');
database.raw('truncate table events cascade');
});
describe('test events GET', () => {
it('happy path', async () => {
const res = await request(app)
.get("/api/v1/events");
expect(res.statusCode).toBe(200);
expect(res.body[0]).toHaveProperty('sport');
expect(res.body[0]["sport"]).toBe("Cheerleading");
expect(res.body[0]["events"].length).toBe(3);
})
})
describe('test show events medalists GET', () => {
it('happy path', async () => {
const id = await database('events').where({event_name: 'Cheerleading at 15,000 meters'}).then(result => result[0].id)
const res = await request(app)
.get(`/api/v1/events/${id}/medalists`);
expect(res.statusCode).toBe(200);
expect(res.body).toHaveProperty('event');
expect(res.body).toHaveProperty('medalists');
expect(res.body["medalists"].length).toBe(1);
})
})
describe('test events GET', () => {
it('sad path', async () => {
const res = await request(app)
.get("/api/v1/events/900/medalists");
expect(res.statusCode).toBe(200);
expect(res.body["message"]).toBe("no medalists exist for event id 900");
})
})
}); | 51d511803e66a82fe3da0f5e8693ee62731db5cf | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | evettetelyas/koroibos | 69d3337f876e817bf69ca6bfbec9610f7ed58ded | 5cb1b48e5e7b028343f0a561ae19de9803199258 |
refs/heads/main | <file_sep>const Constraint = Matter.Constraint
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
var stone, boy;
var tree;
var mango1, mango2, mango3, mango4, mango5, mango6, mango7, mango8;
function setup() {
createCanvas(1300, 600);
engine = Engine.create();
world = engine.world;
//Create the Bodies Here.
mango1 = new Mango(1100, 100, 30);
mango2 = new Mango(1010, 140, 30);
mango3 = new Mango(1000, 70, 30);
mango4 = new Mango(1100, 70, 30);
mango5 = new Mango(900, 230, 40);
mango6 = new Mango(1100, 230, 40);
mango7 = new Mango(1200, 200, 40);
mango8 = new Mango(1200, 50, 40);
Engine.run(engine);
}
function draw() {
rectMode(CENTER);
background(0);
//mouseDragged();
//mouseReleased();
mango1.display();
mango2.display();
mango3.display();
mango4.display();
mango5.display();
mango6.display();
mango7.display();
mango8.display();
drawSprites();
}
/*function mouseDragged() {
Matter.Body.setPosition(boy.body, {x: mouseX, y: mouseY});
}
function mouseReleased() {
boy.fly();
}*/
| f9b3411de8b6d0ab52cc7dd15c63e722f3da14a9 | [
"JavaScript"
] | 1 | JavaScript | Pratham12345678/Mango | e450d1e68d5cbaffe9aba1edfdc30dfb840adc49 | c2d8f21aa2f22ce3e102a8977057264c2cafa5e1 |
refs/heads/master | <repo_name>shinhf/TutorialM3Binding<file_sep>/Tutorial_M3_Binding_Hamburger/ViewModels/AnimalsViewModel.cs
using System.Collections.ObjectModel;
using Tutorial_M3_Binding_Hamburger.Models;
using Tutorial_M3_Binding_Hamburger.ViewModels.Commands;
namespace Tutorial_M3_Binding_Hamburger.ViewModels
{
public class AnimalsViewModel
{
public ObservableCollection<AnimalViewModel> CollectionOfAllAnimals { get; set; }
public ViewCommands ViewCommand { get; set; }
public AnimalsViewModel()
{
CollectionOfAllAnimals =
new ObservableCollection<AnimalViewModel>();
this.ViewCommand = new ViewCommands(this);
var animals = new Animals();
foreach (var temp in animals.AnimalsList)
{
CollectionOfAllAnimals.Add(new AnimalViewModel(temp));
}
}
public void AddData1()
{
// AnimalsList.Add(new Animal() { ID = 4, CommonName = "Pigeon" });
// CollectionOfAllAnimals.Add(
// new AnimalViewModel() { ID = 4, CommonName = "Pigeon" }
// );
}
public void AddData(int id, string commonName)
{
CollectionOfAllAnimals.Add(
new AnimalViewModel() { ID = id, CommonName = commonName }
);
}
}
}
<file_sep>/Tutorial_M3_Binding_Hamburger/Models/Animals.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tutorial_M3_Binding_Hamburger.Models
{
public class Animals
{
public List<Animal> AnimalsList;
public Animals()
{
AnimalsList = new List<Animal>();
//pregenerated data, can be done in Data layer
Add(new Animal { ID = 1, CommonName = "Dog" });
Add(new Animal { ID = 2, CommonName = "Cat" });
Add(new Animal { ID = 3, CommonName = "Horse" });
}
public void Add(Animal animal)
{
AnimalsList.Add(animal);
}
}
}
<file_sep>/Tutorial_M3_Binding_Hamburger/ViewModels/Commands/ViewCommands.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Tutorial_M3_Binding_Hamburger.ViewModels.Commands
{
public class ViewCommands : ICommand
{
public event EventHandler CanExecuteChanged;
public AnimalsViewModel ViewModel { get; set; }
public ViewCommands(AnimalsViewModel ViewModel)
{
this.ViewModel = ViewModel;
}
public bool CanExecute(object send)
{
return false;
}
public void Execute(object send)
{
this.ViewModel.AddData1();
}
}
}
<file_sep>/Tutorial_M3_Binding_Hamburger/ViewModels/AnimalViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tutorial_M3_Binding_Hamburger.Models;
namespace Tutorial_M3_Binding_Hamburger.ViewModels
{
public class AnimalViewModel : Animal
{
public AnimalViewModel()
{
}
public AnimalViewModel(Animal animal)
{
this.ID = animal.ID;
this.CommonName = animal.CommonName;
}
}
}
<file_sep>/Tutorial_M3_Binding_Hamburger/Views/M3Practice3Binding.xaml.cs
using Tutorial_M3_Binding_Hamburger.ViewModels;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace Tutorial_M3_Binding_Hamburger.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class M3Practice3Binding : Page
{
public M3Practice3Binding()
{
this.InitializeComponent();
Animals = new AnimalsViewModel();
}
public AnimalsViewModel Animals { get; set; }
}
}
| 88a2d9da99b06eefe1c74daa1423bc26dc7e1346 | [
"C#"
] | 5 | C# | shinhf/TutorialM3Binding | a5e9dc72331d04ba7eafb43f1cfe6881b4d7fd4f | 3a09c15b8d60fd02c1fa256cba6057311a47a0fe |
refs/heads/master | <repo_name>jsilgado/personal<file_sep>/spring-aop-timer/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>es.java.jsilgado</groupId>
<artifactId>spring-aop-timer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-aop-timer</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<!-- Necesario para Spring AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.3</version>
</dependency>
<!-- Dependencia para la inicializacion del contexto Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<!-- Para ejecutar tests de Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.8.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- Junit para probar nuestro proyecto -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<file_sep>/spring-helloworld/src/main/java/jsilgado/spring/AutowiredBeanExample.java
package jsilgado.spring;
import org.springframework.beans.factory.annotation.Autowired;
public class AutowiredBeanExample {
@Autowired
private AutowiredBean autowiredBean;
public void setAutowiredBean(AutowiredBean AutowiredBean) {
this.autowiredBean = AutowiredBean;
}
public AutowiredBean getAutowiredBean() {
return autowiredBean;
}
public void method() {
autowiredBean.launch();
}
}<file_sep>/spring-aop-timer/src/main/java/es/jsilgado/spring_aop_timer/FooAspect.java
package es.jsilgado.spring_aop_timer;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.util.StopWatch;
/*Lo primero que vemos en la clase es la anotacion
@Aspect que indica que la clase controla aspectos.
El unico metodo que hemos definido measureMethod tiene una anotacion, @Around.
Esta anotacion sirve para decirle que queremos que este metodo se ejecute “alrededor” de nuestro metodo,
es decir, que tenemos el control del metodo antes de su ejecucion y podemos ejecutarlo cuando queramos
o incluso no ejecutarlo, ademas de poder devolver otro valor en vez de el que nos devuelve la ejecucion de nuestro metodo
*/
@Aspect
public class FooAspect {
@Around("execution(* es.jsilgado.spring_aop_timer.Foo.*(..))")
public Object measureMethod(ProceedingJoinPoint pjp) throws Throwable
{
StopWatch sw = new StopWatch();
Object retVal;
try
{
sw.start(pjp.getTarget()+"."+pjp.getSignature());
retVal = pjp.proceed();
}
catch (Throwable e)
{
throw e;
}
finally
{
sw.stop();
System.out.println(sw.prettyPrint());
}
return retVal;
}
}
<file_sep>/spring-helloworld/src/main/java/jsilgado/spring/AutowiredBean.java
package jsilgado.spring;
public class AutowiredBean {
public AutowiredBean() {
System.out.println("Inside AutowiredBean constructor.");
}
public void launch() {
System.out.println("Inside launch.");
}
} | bf78b61aba76ccedcc542919c62f7b32cfac2b48 | [
"Java",
"Maven POM"
] | 4 | Maven POM | jsilgado/personal | 85cb1453647073743550a1d129ee4c880d79ad4b | fed0c549762350f9f34ee33a2322a628fefd0b04 |
refs/heads/master | <repo_name>amarunko/laravel-echo-ios<file_sep>/README.md
# Laravel Echo IOS
This is a project by [Bubbleflat : find your perfect roommate and flatsharing](https://bubbleflat.com)
This project is wrapper to use [Laravel Echo](https://github.com/laravel/echo) in Swift IOS project
This only work for **socket.io**, NOT FOR PUSHER yet !
## Installation
This module can be imported with CocoaPods
```
pod 'LaravelEchoIOS'
```
## Example
First, you need to import the framework :
```Swift
import LaravelEchoIOS
```
Then you can use it like in javascript ( but you need to wait for the socket to be connected )
```Swift
let token = "Auth <PASSWORD>"
let e : Echo = Echo(options: ["host":"http://localhost:6001", "auth": ["headers": ["Authorization": "Bearer " + token]]])
e.connected(){ data, ack in
print("CONNECTED")
e.join(channel: "conversation.243").listen(event: ".NewMessage", callback: { data, ack in
print(data)
})
}
```
## Documentation
See [full Echo documentation](https://laravel.com/docs/5.5/broadcasting) for all available methods
All callback must been use like this :
```Swift
e.connected(){ data, ack in
// Do something when call
}
```
Or with a function like this
```Swift
func listener(data: [Any], ack: SocketAckEmitter)
```
**here, joining, leaving are not available yet**
<file_sep>/LaravelEchoIOS/channel/SocketIOPresenceChannel.swift
//
// Created by <NAME> on 09/10/2017.
//
import Foundation
import SocketIO
/// This class represents a Socket.io presence channel.
public class SocketIOPresenceChannel: SocketIoChannel, IPresenceChannel {
/// Create a new class instance.
///
/// - Parameters:
/// - socket: the socket instance
/// - name: the channel name
/// - options: options for the channel
public override init(socket: SocketIOClient, name: String, options: [String: Any]){
super.init(socket: socket, name: name, options: options)
}
/// Register a callback to be called anytime the member list changes. TODO
///
/// - Parameter callback: callback
/// - Returns: the presence channel itself
public func here(callback: NormalCallback) -> IPresenceChannel {
return self
}
/// Listen for someone joining the channel. TODO
///
/// - Parameter callback: callback
/// - Returns: the presence channel itself
public func joining(callback: NormalCallback) -> IPresenceChannel {
return self
}
/// Listen for someone leaving the channel. TODO
///
/// - Parameter callback: callback
/// - Returns: the presence channel itself
public func leaving(callback: NormalCallback) -> IPresenceChannel {
return self
}
}
<file_sep>/LaravelEchoIOS/connector/IConnector.swift
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
import SocketIO
/// Connector protocol
public protocol IConnector{
/// Create a fresh connection.
func connect()
/// Set an event handler
///
/// - Parameters:
/// - event: event name
/// - callback: callback
func on(event: String, callback: @escaping NormalCallback)
/// Get a channel instance by name.
///
/// - Parameter name: channel name
/// - Returns: the channel
func channel(name: String) -> IChannel
/// Listen an event on a channel
///
/// - Parameters:
/// - name: channel name
/// - event: event name
/// - callback: callback
/// - Returns: the channel
func listen(name : String, event: String, callback: @escaping NormalCallback) -> IChannel
/// Get a private channel instance by name.
///
/// - Parameter name: channel name
/// - Returns: the private channel
func privateChannel(name: String) -> IPrivateChannel
/// Get a presence channel instance by name.
///
/// - Parameter name: channel name
/// - Returns: the presence channel
func presenceChannel(name: String) -> IPresenceChannel
/// Leave the given channel.
///
/// - Parameter name: channel name
func leave(name : String)
/// Get the socket_id of the connection.
///
/// - Returns: the socket id
func socketId() -> String
/// Disconnect from the Echo server.
func disconnect()
}
<file_sep>/LaravelEchoIOS/utils/EventFormatter.swift
//
// EventFormatter.swift
// laravel-echo-ios
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
/// Event name formatter
public class EventFormatter {
/// Event namespace.
public var namespace = ""
/// Create a new class instance.
///
/// - Parameter namespace: namespce
public init(namespace: String? = ""){
self.setNamespace(value: namespace!)
}
/// Format the given event name.
///
/// - Parameter event: event name
/// - Returns: formated event name
public func format(event: String) -> String {
var e : String = event
if(!(event.hasPrefix("\\") || event.hasPrefix("."))){
e = self.namespace + "." + event
} else {
let index = event.index(event.startIndex, offsetBy: 1)
return String(event[index...])
}
return e.replacingOccurrences(of: ".", with: "\\")
}
/// Set the event namespace.
///
/// - Parameter value: namespace
public func setNamespace(value: String? = "") {
if let wrap = value {
self.namespace = wrap
}
}
}
<file_sep>/LaravelEchoIOS/channel/SocketIOChannel.swift
//
// SocketIOChannel.swift
// laravel-echo-ios
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
import SocketIO
/// This class represents a Socket.io channel.
public class SocketIoChannel: Channel {
/// The Socket.io client instance.
public var socket: SocketIOClient
/// The name of the channel.
public var name: String
/// Channel auth options.
public var auth: [String: Any]
/// The event formatter.
public var eventFormatter: EventFormatter
/// The event callbacks applied to the channel.
public var events : [String: [NormalCallback]]
/// Create a new class instance.
///
/// - Parameters:
/// - socket: the socket instance
/// - name: the channel name
/// - options: options for the channel
public init(socket: SocketIOClient, name: String, options: [String: Any]){
self.name = name
self.socket = socket
self.events = [:]
var namespace = ""
if let wrapperNamespace = options["namespace"] as? String{
namespace = wrapperNamespace
}
self.auth = [:]
if let wrapperAuth = options["auth"] as? [String: Any]{
self.auth = wrapperAuth
}
self.eventFormatter = EventFormatter(namespace: namespace)
super.init(options: options)
self.subscribe()
self.configureReconnector()
}
/// Subscribe to a Socket.io channel.
public override func subscribe(){
let data = [["channel": self.name, "auth": self.auth]]
self.socket.emit("subscribe", with : data)
}
/// Unsubscribe from channel and ubind event callbacks.
public override func unsubscribe(){
self.unbind()
let data = [["channel": self.name, "auth": self.auth]]
self.socket.emit("unsubscribe", with: data)
}
/// Listen for an event on the channel instance.
///
/// - Parameters:
/// - event: event name
/// - callback: callback
/// - Returns: the channel itself
public override func listen(event: String, callback: @escaping NormalCallback) -> IChannel{
self.on(event: self.eventFormatter.format(event: event), callback: callback)
return self
}
/// Bind the channel's socket to an event and store the callback.
///
/// - Parameters:
/// - event: event name
/// - callback: callback
public func on(event: String, callback: @escaping NormalCallback){
func listener(data: [Any], ack: SocketAckEmitter){
if let channel = data[0] as? String {
if(self.name == channel){
callback(data, ack)
}
}
}
self.socket.on(event, callback: listener)
self.bind(event: event, callback: listener)
}
/// Attach a 'reconnect' listener and bind the event.
public func configureReconnector(){
func listener(event: [Any], _ack: SocketAckEmitter){
self.subscribe()
}
self.socket.on("reconnect", callback: listener)
self.bind(event: "reconnect", callback: listener)
}
/// Bind the channel's socket to an event and store the callback.
///
/// - Parameters:
/// - event: event name
/// - callback: callback
public func bind(event: String, callback: @escaping NormalCallback){
if(self.events[event] == nil){
self.events[event] = []
}
self.events[event]!.append(callback)
}
/// Unbind the channel's socket from all stored event callbacks.
public func unbind(){
for (key, _) in self.events {
self.events[key] = nil
}
self.socket.removeAllHandlers()
}
}
<file_sep>/Podfile
use_frameworks!
inhibit_all_warnings!
platform :ios, '9.0'
target 'LaravelEchoIOS' do
pod 'Socket.IO-Client-Swift', '~> 15.1.0'
end
<file_sep>/LaravelEchoIOS/channel/IChannel.swift
//
// IChannel.swift
// laravel-echo-ios
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
import SocketIO
/// This class represents a basic channel protocol.
public protocol IChannel {
/// Listen for an event on the channel instance.
///
/// - Parameters:
/// - event: event name
/// - callback: callback
/// - Returns: the channel itself
func listen(event: String, callback: @escaping NormalCallback) -> IChannel
/// Listen for an event on the channel instance.
///
/// - Parameter callback: callback
/// - Returns: the channel itself
func notification(callback: @escaping NormalCallback) -> IChannel
/// Listen for a whisper event on the channel instance.
///
/// - Parameters:
/// - event: event name
/// - callback: callback
/// - Returns: the channel itself
func listenForWhisper(event: String, callback: @escaping NormalCallback) -> IChannel
/// Unsubscribe from channel and ubind event callbacks.
func unsubscribe()
/// Subscribe to a Socket.io channel.
func subscribe()
}
<file_sep>/LaravelEchoIOS/channel/SocketIOPrivateChannel.swift
//
// Created by <NAME> on 09/10/2017.
//
import Foundation
import SocketIO
/**
* This class represents a Socket.io private channel.
*/
public class SocketIOPrivateChannel: SocketIoChannel, IPrivateChannel {
/// Create a new class instance.
///
/// - Parameters:
/// - socket: the socket instance
/// - name: the channel name
/// - options: options for the channel
override init(socket: SocketIOClient, name: String, options: [String: Any]){
super.init(socket: socket, name: name, options: options)
}
/// Trigger client event on the channel.
///
/// - Parameters:
/// - eventName: event name
/// - data: data send
/// - Returns: the private channel itself
public func whisper(eventName: String, data: [AnyObject]) -> IPrivateChannel{
self.socket.emit("client event", [
"channel": self.name,
"event": "client-" + eventName,
"data" : data
])
return self
}
}
<file_sep>/LaravelEchoIOS/channel/IPrivateChannel.swift
//
// Created by <NAME> on 21/07/2017.
// Copyright (c) 2017 Bubbleflat. All rights reserved.
//
import Foundation
import SocketIO
/// This protocol represents a private channel.
public protocol IPrivateChannel: IChannel{
/// Trigger client event on the channel.
///
/// - Parameters:
/// - eventName: event name
/// - data: data send
/// - Returns: the private channel itself
func whisper(eventName: String, data: [AnyObject]) -> IPrivateChannel
}
<file_sep>/LaravelEchoIOS/channel/Channel.swift
//
// Channel.swift
// laravel-echo-ios
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
import SocketIO
/// This class represents a basic channel.
public class Channel: IChannel {
/// The Echo options.
public var options: [String: Any]
/// Create new Channel
///
/// - Parameter options: options
public init (options: [String: Any]){
self.options = options
}
/// Listen for an event on the channel instance.
///
/// - Parameters:
/// - event: event name
/// - callback: callback
/// - Returns: the channel itself
@discardableResult public func listen(event: String, callback: @escaping NormalCallback) -> IChannel {
return self
}
/// Listen for an event on the channel instance.
///
/// - Parameter callback: callback
/// - Returns: the channel itself
public func notification(callback: @escaping NormalCallback) -> IChannel {
return self.listen(event: ".Illuminate.Notifications.Events.BroadcastNotificationCreated", callback: callback)
}
/// Listen for a whisper event on the channel instance.
///
/// - Parameters:
/// - event: event name
/// - callback: callback
/// - Returns: the channel itself
public func listenForWhisper(event: String, callback: @escaping NormalCallback) -> IChannel {
return self.listen(event: ".client-" + event, callback: callback)
}
/// Unsubscribe from channel and ubind event callbacks.
public func unsubscribe(){
}
/// Subscribe to a Socket.io channel.
public func subscribe(){
}
}
<file_sep>/LaravelEchoIOS/channel/IPresenceChannel.swift
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
import SocketIO
/// This protocol represents a presence channel.
public protocol IPresenceChannel: IChannel{
/// Register a callback to be called anytime the member list changes.
///
/// - Parameter callback: callback
/// - Returns: the presence channel itself
func here(callback: NormalCallback) -> IPresenceChannel
/// Listen for someone joining the channel.
///
/// - Parameter callback: callback
/// - Returns: the presence channel itself
func joining(callback: NormalCallback) -> IPresenceChannel
/// Listen for someone leaving the channel.
///
/// - Parameter callback: callback
/// - Returns: the presence channel itself
func leaving(callback: NormalCallback) -> IPresenceChannel
}
<file_sep>/LaravelEchoIOS/connector/SocketIOConnector.swift
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
import SocketIO
/// This class creates a connnector to a Socket.io server.
public class SocketIOConnector: IConnector {
private var manager: SocketManager?
/// The Socket.io connection instance.
public var socket: SocketIOClient?
/// Default connector options.
public var _defaultOptions: [String: Any] = [ "auth": ["headers": []], "authEndpoint": "/broadcasting/auth", "broadcaster": "socket.io", "host": "", "key": "", "namespace": "App.Events"]
/// Connector options.
public var options: [String: Any]
/// All of the subscribed channels.
public var channels: [String: IChannel]
public var onDisconnect: (() -> Void)?
/// Create a new class instance.
///
/// - Parameter options: options
public init(options: [String: Any], onDisconnect: (() -> Void)? = .none){
self.socket = nil
self.options = options
self.channels = [:]
self.onDisconnect = onDisconnect
self.connect()
}
/// Merge the custom options with the defaults.
///
/// - Parameter options: options
public func setOptions(options: [String: Any]){
self.options = self.mergeOptions(options: options)
}
/// Create a fresh Socket.io connection.
public func connect(){
if let url = self.options["host"] as? String {
let nurl: URL! = URL(string: url)
let socketConfig: SocketIOClientConfiguration = [.log(true)]
self.manager = SocketManager(socketURL: nurl, config: socketConfig)
self.socket = manager?.defaultSocket
self.socket?.connect(timeoutAfter: 5, withHandler: { [weak self] in
print("ERROR socket connection - try to check parameeters")
self?.onDisconnect?()
})
}
}
/// Add other handler type
///
/// - Parameters:
/// - event: event name
/// - callback: callback
public func on(event: String, callback: @escaping NormalCallback){
self.socket!.on(event, callback: callback)
}
/// Listen for an event on a channel instance.
///
/// - Parameters:
/// - name: channel name
/// - event: event name
/// - callback: callback
/// - Returns: the channel
public func listen(name : String, event: String, callback: @escaping NormalCallback) -> IChannel{
return self.channel(name: name).listen(event: event, callback: callback)
}
/// Get a channel instance by name.
///
/// - Parameter name: channel name
/// - Returns: the channel
public func channel(name: String) -> IChannel{
if(self.channels[name] == nil){
let socket: SocketIOClient! = self.socket
self.channels[name] = SocketIoChannel(
socket: socket, name: name, options: self.options
)
}
return self.channels[name]!
}
/// Get a private channel instance by name.
///
/// - Parameter name: channel name
/// - Returns: the private channel
public func privateChannel(name: String) -> IPrivateChannel{
if(self.channels["private-" + name] == nil){
let socket: SocketIOClient! = self.socket
self.channels["private-" + name] = SocketIOPrivateChannel(
socket: socket, name: "private-" + name, options: self.options
)
}
return self.channels["private-" + name]! as! IPrivateChannel
}
/// Get a presence channel instance by name.
///
/// - Parameter name: channel name
/// - Returns: the presence channel
public func presenceChannel(name: String) -> IPresenceChannel{
if(self.channels["presence-" + name] == nil){
let socket: SocketIOClient! = self.socket
self.channels["presence-" + name] = SocketIOPresenceChannel(
socket: socket, name: "presence-" + name, options: self.options
)
}
return self.channels["presence-" + name]! as! IPresenceChannel
}
/// Leave the given channel.
///
/// - Parameter name: channel name
public func leave(name : String){
let channels: [String] = [name, "private-" + name, "presence-" + name]
for(name) in channels{
if let c = self.channels[name] {
c.unsubscribe()
self.channels[name] = nil
}
}
}
/// Get the socket_id of the connection.
///
/// - Returns: the socket id
public func socketId() -> String {
if let socket: SocketIOClient = self.socket{
return socket.sid
}
return ""
}
/// Disconnect from the Echo server.
public func disconnect(){
let socket: SocketIOClient! = self.socket
socket.disconnect()
}
/// Merge options with default
///
/// - Parameter options: the options
/// - Returns: merged options
public func mergeOptions(options : [String: Any]) -> [String: Any]{
var def = self._defaultOptions
for (k, v) in options{
def[k] = v
}
return def
}
}
<file_sep>/LaravelEchoIOS/Echo.swift
//
// Echo.swift
// laravel-echo-ios
//
// Created by <NAME> on 21/07/2017.
//
import Foundation
import SocketIO
/// This class is the primary API for interacting with broadcasting.
public class Echo {
/// The broadcasting connector.
public var connector: IConnector
/// The Echo options.
public var options: [String: Any]
public var onDisconnect: (() -> Void)?
/// Create a new class instance.
///
/// - Parameter options: optionsb
public init(options: [String: Any], onDisconnect: (() -> Void)? = .none){
self.options = options
//No Pusher support
self.connector = SocketIOConnector(options: self.options, onDisconnect: onDisconnect)
}
/// when connected to the socket
///
/// - Parameter callback: callback
public func connected(callback: @escaping NormalCallback){
return self.on(event: "connect", callback: callback)
}
/// Catch an event
///
/// - Parameters:
/// - event: event name
/// - callback: callback
public func on(event: String, callback: @escaping NormalCallback){
return self.connector.on(event: event, callback: callback)
}
/// Listen for an event on a channel instance.
///
/// - Parameters:
/// - channel: channel name
/// - event: event name
/// - callback: callback
/// - Returns: the channel listened
public func listen(channel: String, event: String, callback: @escaping NormalCallback) -> IChannel{
return self.connector.listen(name: channel, event: event, callback: callback)
}
/// Get a channel instance by name.
///
/// - Parameter channel: channel name
/// - Returns: the channel
public func channel(channel: String) -> IChannel {
return self.connector.channel(name: channel)
}
/// Get a private channel instance by name.
///
/// - Parameter channel: channel name
/// - Returns: the private channel
public func privateChannel(channel: String) -> IChannel{
return self.connector.privateChannel(name:channel)
}
/// Get a presence channel instance by name.
///
/// - Parameter channel: channel name
/// - Returns: the private channel
public func join(channel: String) -> IPresenceChannel {
return self.connector.presenceChannel(name:channel)
}
/// Leave the given channel.
///
/// - Parameter channel: the channel name
public func leave(channel: String) {
self.connector.leave(name: channel)
}
/// Get the Socket ID for the connection.
///
/// - Returns: the socket id
public func socketId() -> String {
return self.connector.socketId()
}
/// Disconnect from the Echo server.
public func disconnect(){
self.connector.disconnect()
}
}
| 0bc0475fdd399f39b87f47416e79a8175f5134f1 | [
"Markdown",
"Ruby",
"Swift"
] | 13 | Markdown | amarunko/laravel-echo-ios | d312396aa8d0eab884eec4d17af0508117a61983 | 008e793547af7fa1701779737e2d4523e4f9de17 |
refs/heads/master | <file_sep>// Sempre que comçar um projeto node rode no terminal um npm init para
// gerar um package.json. Importante para guardar versões de libs que
// pode ser usado no projeto.
// Exemplo: underscore
const underscore = require('underscore')
// Importante aqui: quando importamos uma lib nesse formato, Node assume
// que esse importe vem do core do Node.
// Se chamo dessa formar require('./underscore') Ele vai buscar um arquivo
// com esse nome e um index.js. O que não é o caso.
// Por último, ele busca se é alguma função do node_modules que veio com
// npm init.
// Vamos usar a function contains dessa lib
const results = underscore.contains([1, 2, 3], 3)
console.log(results)
// ver vídeo exemplo mongoose na udemy
// Semantic Version
// "mongoose": "^5.7.1", // MajorVersion.MinorVersion.Patch
// "mongoose": "5.x", mesmo que o de cima
// "mongoose": "~5.7.1", todas as versões de 5 que foi lancada até agora
// "mongoose": "5.7.1 é seguro fazer sem nada
// criar .gitignore para não subir arquivos node_modules
// npm list
// npm list--depth=0
// npm view mongoose // package.json do mongoose
// npm view mongoose dependencies
// npm view mongoose versions
// npm i mongoose@version // para fazer um upgrade ou downgrade de package
// npm outdated
// npm i -g npm-check-updates // para ver todas as versões não updates
// npm i jshint --save-dev// um pacote que verifica onde pode ter uma possível
// falah no código em geral
// npm unisntall pacote // para deinstalar um package
<file_sep>const mongoose = require('mongoose')
const movieSchema = require('../validations/mongoMovieValidator')
const Movies = mongoose.model('Movies', movieSchema)
module.exports = Movies<file_sep>const barroso = async () => {
if (Math.random() < 0.5){
throw new Error('quebrou')
}
return 1
}
const barroso = () => {
return new Promise((resolve, reject) => {
if (Math.random() < 0.5) {
reject(new Error('quebrou'))
}
resolve(1)
})
}
const vellone = async () => {
const barrosoResult = await barroso()
return barrosoResult + 1
}
const ivan = async () => {
try {
const velloneResult = await vellone()
const barrosoResult = await barroso()
return velloneResult * 2 * barrosoResult
} catch (erro) {
console.log('erro no ivan')
console.log(erro)
}
return 0
}
ivan().then(console.log)
// barroso()
// .catch((erro) => {
// console.log('deu erro!!!')
// })
// try {
// barroso()
// } catch(err) {
// console.log('deu erro!!!')
// }<file_sep>const mongoose = require('mongoose')
const express = require('express')
const app = express()
const helmet = require('helmet')
const morgan = require('morgan')
const movies = require('./routes/movies')
const genres = require('./routes/genres')
const logger = require('./middlewares/logger')
const authenticator = require('./middlewares/authenticator')
mongoose.connect('mongodb://localhost:27017/exercises')
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err))
app.use(express.json())
app.use(helmet())
app.use(morgan('tiny'))
app.use(logger)
app.use(authenticator)
app.use('/movies', movies)
app.use('/genres/movies', genres)
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))
<file_sep>// Intro Mongo
// Instalando o Mongo-Compass e docker na máquina
// Rodando o docker na porta desejada
// Iniciando...
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/playground') // returns a Promise
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err))
const courseSchema = new mongoose.Schema({ // schema de entrada de dados no meu DB
name: String,
author: String,
tags: [ String ],
date: {
type: Date,
default: Date.now
},
isPublished: Boolean
})
const Course = mongoose.model('Course', courseSchema) // criando um model
// Num model a gente diz onde queremos guardar os dados e como (os dois parametros dentro de model)
const createCourse = async () => {
const course = new Course({ // schemaLess
name: 'Angular Course',
author: '<NAME>',
tags: ['angular', 'frontend'],
isPublished: true
})
const result = await course.save()
console.log(result)
}
const getCourses = async () => { // commandos que podemos aplicar para retornar
// os itens da minha db
// Comparrison Operators
// eq equal
// ne not equal
// gt greater than
// gte greater or equal to
// lt less than
// lte lass than or equal to
// in
// nin not in
// Logical Operators
// or
// and
//Pagination
const pageNumber = 2
const pageSize = 10
// /api/courses?pageNumber=2&pageSize=10
const courses = await Course
// .find() // returns DocumentQueryObj
.find({ author: '<NAME>', isPublished: true })
.skip((pageNumber -1) * pageSize)
// .filter
// .find ({ price: { $gt: 10, $lte: 20 } }) // greater than 10 dollars
// .find( {price: { $in: [10, 15, 20]}})
// .find()
// .or([ { author: '<NAME>' }, { isPublished: true } ]) // and igual
// .find({ author: /^Guilherme/ }) // Regex para achar Guulherme tb
// .find({ author: /Barroso$/i })
// .find({ author: /.*Guilherme.*/i })
.limit(pageSize)
.sort({ name: 1 }) // 1 = assending -1 = dessending
.count()
// .select({ name: 1, tags: 1 })
console.log(courses)
}
// createCourse()
getCourses()<file_sep>// Transformando o código de callbacks no uso das Promises
console.log('Eu venho antes...')
getUser()
.then(user => {
console.log('1', user)
return getRepositories(user.gitHubUsername)
})
.then(repos => {
console.log('2', repos)
return getCommits(repos)
})
.then(result => {
console.log('3', result)
})
.catch(error => {
console.log('Error 404. Try again later', error.message)
})
console.log('Eu venho depois...')
function getUser(id) {
if (id === undefined) {
return new Promise((resolve, reject) => {
reject(new Error("id can't be undefined"))
})
}
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Reading a user from a database...')
resolve({
id: id,
gitHubUsername: 'gmbarroso'
})
}, 2000)
})
}
function getRepositories(user) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Getting user repositories')
resolve(['repo1', 'repo2', 'repo3'])
}, 2000)
})
}
function getCommits(repo) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Getting repositorie commits...')
resolve(['commit1', 'commit2'])
}, 2000)
})
}<file_sep>const xavierMutants = [
{
id: 1,
name: "Cyclops"
},
{
id: 2,
name: "Iceman",
},
{
id: 3,
name: "Dazzler",
},
{
id: 4,
name: "Strom",
}
]
module.exports = xavierMutants<file_sep>const mongoose = require('mongoose')
const courseSchema = new mongoose.Schema({
// Por mais que eu insira uma nova chave no meu obj na hora do Post
// o registro será somente de nome, pois é que o model dele está
name: String,
// agora não mais
author: {
type: mongoose.Schema.Types.ObjectId, // forma como dizemos que o tipo de entrada de dado é do proprio mongoose
ref: "Authors" // Passar qual collectio estamos fazendo referencia
}
})
// {
// "name": "React Course",
// "author": "<PASSWORD>"
// }
const Courses = mongoose.model('Courses', courseSchema)
module.exports = Courses<file_sep>const express = require('express')
const router = express.Router
router.get('/', (req, res) => {
res.send('index', { title: 'The Uncanny X-men', message: 'To me my X-men!!!'})
}
)
module.exports = router<file_sep>const mongoose = require('mongoose')
const authorSchema = new mongoose.Schema({
name: String,
bio: String,
website: String
})
const Authors = mongoose.model('Authors', authorSchema)
module.exports.Authors = Authors
module.exports.authorSchema = authorSchema<file_sep>const sagitarius = require('sagitarius-lib')
const resultSum = sagitarius.sum(3, 5)
const resultMult = sagitarius.multiply(3, 5)
console.log(resultSum, resultMult)<file_sep>const EventEmitter = require('events')
const users = [
{
id: 1,
name: '<NAME>',
address: 'Rua Clodomiro Amazonas',
number: '960',
},
{
id: 2,
name: '<NAME>',
address: 'Rua Clodomiro Amazonas',
number: '960',
},
{
id: 3,
name: '<NAME>',
address: 'Rua Clodomiro Amazonas',
number: '960',
}
]
class Logger extends EventEmitter {
// Fazendo com que Logger tenha todos os métodos de EventEmitter
log(message) { // Criando um método dentro de Logger
console.log(message)
this.emit('messageLogged', users)
}
}
module.exports = Logger
<file_sep>const fs = require('fs') // chamando o módulo do Node
// Quase todas as operações de fs. vem em duas formas: síncrona ou blocking
// e assíncrono ou non-blocking. Devemos usar sempre assíncrono, justamente
// por ser non-blocking. Construindo um servidor, por exemplo, em Node,
// Podemos querer permitir o acesso de diversos clientes na api de uma vez,
// e usando métodos assíncronos não permitiremos ou servidor ocupado.
// Primeiro um método síncrono
// const files = fs.readdirSync('./') // mostra todos os arquivos na raiz
// console.log(files)
// Usando método Assíncrono
// todo método assíncrono recebe uma função como argumento final
// Node chama essa função quando essa operação assíncrona estiver
// completa. Isso é chamado de callback
fs.readdir('./', function(err, files){
// fs.readdir('$', function(err, files){ // simulando um erro
if (err) console.log('Error', err)
else console.log('Result', files)
})<file_sep>// Em JSON, nodeJS quano o código é executado, ele 'wraps' (transpila),
// através de uma função, é convertido em uma function abaixo,
// (function (exports, require, module, __filename, __dirname) {
// ... // todo o código vem aqui para dentro
// é chamado de module expression ou if
// })
// Essa function acima é chamada de Module Wraps Exports
console.log(__filename)
console.log(__dirname)
const path = require('path') // passando './path' node assume que é um arquivo.
// sem './' node entende que estamos chamando um módulo dele.
const pathObj = path.parse(__filename) // usaremos um método do JS para transformar a
// resposta em um objeto
console.log(pathObj)<file_sep>const express = require('express')
const app = express()
const helmet = require('helmet')
const morgan = require('morgan')
const movies = require('./routes/movies')
const genres = require('./routes/genres')
const logger = require('./middlewares/logger')
const authenticator = require('./middlewares/authenticator')
app.use(express.json())
app.use(helmet())
app.use(morgan('tiny'))
app.use(logger)
app.use(authenticator)
app.use('/movies', movies)
app.use('/genres/movies', genres)
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))
<file_sep>// Pegando informação do Sistema Operacional - Método OS
const os = require('os')
const totalMemory = os.totalmem()
const freeMemory = os.freemem()
console.log(`Total Memory: ${totalMemory}`)
console.log(`Free Memory: ${freeMemory}`)
// loga o tanto de memória que está sendo usado e o quanto ainda temos livre
// Antes do Node, não era possível ver essa informação no terminal
// JS se resumia somente ao browser.
<file_sep>// Reestruturando a aplicação em Node
// Fazendo um refactor e separando em arquivos partes do código
const helmet = require('helmet')
const morgan = require('morgan')
const express = require('express')
const app = express()
const mutants = require('./routes/mutants') // importando minhas rotas de outro módulo
// const xmen = require('./routes/x-men')
app.use(express.json())
app.use(helmet())
app.use(morgan('tiny'))
// Agora as rotas funcionam como um middleware
// Precismos passar dois paramtros para ele
// O primeiro é o path
// e o segundo é a variável que usamos para importar as rotas
app.use('/x-men/mutants', mutants) // Estamos dizendo aqui que toda rota que usar /x-men/mutants
// vem da variável mutants
// app.use('/', xmen)
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))
<file_sep>// Node module System
console.log() // this is a global object
// temos muitas outras functions que são globais. Ex:
setTimeout()
clearTimeout()
setInterval()
clearInterval()
// Nos browsers temos como acessar todas essas functions declaradas no escopo global
window // window object
window.console.log // por exemplo
window.setTimeout
const message = '';
window.message
// Acontece que em Node não temos window.object
// Para acessar declarações no contexto global em Node a gente usa o global
global
global.console.log
global.setTimeout // etc
// No entanto
const message = ''
// não é acessível pelo contexto global
console.log(global.message) // sai undefined
// Ao rodar node intro.js o resultado será undefined
// isso acontece pq {message} é acessível somente no contexto deste arquivo, intro.js
// Modules
// Em Node, cada aqrquivo é considerado um módulo e todas as variáveis
// e funções declaradas dentro desse arquivo estão no escopo somente
// do arquivo onde essa função/variável foi declarada.
console.log(module) // Vejamos oq ue aparece ao rodarmos esse console no terminal
// Module {
// id: '.',
// exports: {},
// parent: null,
// filename:
// '/home/gmbarroso/Desktop/mosh_hamedani/learning_node/intro.js',
// loaded: false,
// children: [],
// paths:
// [ '/home/gmbarroso/Desktop/mosh_hamedani/learning_node/node_modules',
// '/home/gmbarroso/Desktop/mosh_hamedani/node_modules',
// '/home/gmbarroso/Desktop/node_modules',
// '/home/gmbarroso/node_modules',
// '/home/node_modules',
// '/node_modules' ] }
<file_sep>const Joi = require('joi')
const validateMovieObj = (req, res) => {
const schema = {
title: Joi.string().min(3).required(),
year: Joi.number().required(),
cast: Joi.array(),
genres: Joi.array().min(1).required()
}
return Joi.validate(req.body, schema, { abortEarly: false })
}
module.exports = validateMovieObj<file_sep>// No mundo real nós precisamos saber qual o ambiente em qe estamos rodando
// o nosso código: desenvolvimento, produção, etc...
// Talvez seja necessário habilitar ou não algumas features baseadas
// em qual ambiente estamos codando
// =========
// Ver este comentário por último
// É importante, no mundo real, setarmos as configurações da aplicação
// e como alterar o valor dessas configurações para cada ambiente de trabalho
// Por exemplo, no ambiente de desenvolvimento vamos usar um database diferente
// ou um serviços de e-mail diferente de cada ambiente
// =========
const Joi = require('joi')
// =========
const config = require('config') // para pegar as diferentes configurações que eu setei
// criar um arquivo chamado config
// =========
const helmet = require('helmet')
const morgan = require('morgan')
const express = require('express')
const app = express()
// process object é uma variável global em node. O env que dá acesso ao
// processo atual que o ambiente está sendo rodado
// NODE_env é um ambiente default. Quando não setado vem em undefined
// development
// testing
// staging
// production
console.log(`NODE_env: ${process.env.NODE_env}`)
// temos tb um outro jeito de pegar o ambiente que o nosso código está rodando
// através do express
console.log(`app: ${app.get('env')}`) // faz o que o console.log acima está fazendo, mas se não
// estiver setado, retorna 'development' como default
app.use(express.json())
app.use(express.static('catalogue'))
app.use(helmet()) // ???
// =========
// Configuration
console.log(`Application Name: ${config.get('name')}`)
console.log(`Mail Server: ${config.get('mail.host')}`)
// Nunca devemos guardar coisas importantes nos arquivos de configurações
// como por exemplo password, api_key, cvv, etc
// para isso devemos guardar essas informações em variáveis de ambient ou
// environment variables
console.log(`Mail Password: ${config.get('mail.password')}`)
// =========
// Por exemplo, não é legal colocar os logs do morgan em ambiente de produção
// então. Faz sentido que habilitemos o log do morgan somente no ambiente de
// desenvolvimento, então...
if (app.get('env') === 'development') {
app.use(morgan('tiny'))
console.log('Morgan enabled...')
}
// experimentar setar para production no terminal
// set ou export NODE_ENV=production
const mutants = [
{
id: 1,
name: "Cyclops"
},
{
id: 2,
name: "Iceman",
},
{
id: 3,
name: "Dazzler",
},
{
id: 4,
name: "Strom",
}
]
const getMutant = (req, res) => {
const mutant = mutants.find( m => {
return (
m.id === parseInt(req.params.id)
)
})
return mutant
}
const validateMutantName = (req, res) => {
const schema = {
name: Joi.string().min(3).required()
}
return result = Joi.validate(req.body, schema)
}
app.get('/x-men/mutants',
(req, res) => {
res.send(mutants)
}
)
app.get('/x-men/mutants/:id', (req, res) => {
const mutant = getMutant(req, res)
if (!mutant) (
res.status(404).send('This mutant is not register in our database.')
)
res.send(mutant)
})
app.post('/x-men/mutants', (req, res) => {
const result = validateMutantName(req, res)
if (result.error) {
return res.status(400).send(result.error.details[0].message)
}
const mutant = {
id: mutants.length + 1,
name: req.body.name
}
mutants.push(mutant)
res.send(mutant)
})
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))
<file_sep>const Courses = require('../models/courseModel')
const express = require('express')
const router = express.Router()
// const validateCustomerObj = require('../validations/customerValidation')
router.get('/', async (req, res) => {
const courses = await Courses
.find()
.populate('author', 'name -_id') // para puxar os dados de uma collection e por em outra (visual)
// Como o id que está lá é um id que está numa outra collection, ele consegue
// fazer as associações
// Como segundo parametro no populate a gente coloca o que queremos visualizar e tirar de visualização.
// .populate('author', 'name -_id') // Posso por quntos populate quiser para puxar dados de outras collections tb
.sort('name')
res.send(courses)
})
router.post('/', async (req, res) => {
// const result = validateCustomerObj(req, res)
// if (result.error) return res.status(400).send()
let course = new Courses({
name: req.body.name,
author: req.body.author
})
course = await course.save()
res.send(course)
})
module.exports = router<file_sep>const EventEmitter = require('events')
const emitter = new EventEmitter()
const users = [
{
id: 1,
name: '<NAME>',
address: 'Rua Clodomiro Amazonas',
number: '960',
},
{
id: 2,
name: '<NAME>',
address: 'Rua Clodomiro Amazonas',
number: '960',
},
{
id: 3,
name: '<NAME>',
address: 'Rua Clodomiro Amazonas',
number: '960',
}
]
const handleUserLog = (user) => (
user.name
)
emitter.on('Log', e => {
console.log(e)
})
emitter.emit('Log', handleUserLog(users[2]))<file_sep>// RESTful api
// Arquitetura:
// Client é o app itself
// como back temos um Server
// A comunicação acontece com um HTTP entre eles.
// REST - Representational State Transfer - http services
// Create Reade Update Delete - CRUD Operations
// HETTP Methods: GET, POST, PUT, DELETE
const Joi = require('joi') // importando um validador
// queremos a classe Joi
// Intro
// Express
// um framework para facilitar na construção de uma api e suas rotas
const express = require('express') // importando o express
const app = express() // colocando tudo o que o express traz em uma variável
app.use(express.json()) // importanto um middleware to express
// ele aceita formatos json que estamos usando em post
const mutants = [
{
id: 1,
name: "Cyclops"
},
{
id: 2,
name: "Iceman",
},
{
id: 3,
name: "Dazzler",
},
{
id: 4,
name: "Strom",
}
]
app.get('/', (req, res) => { // criando uma rota
res.send('Hello World!!!')
})
app.get('/x-men/mutants', (req, res) => {
res.send(mutants)
})
app.get('/x-men/:mutant/:power', (req, res) => { // definindo parametros
// para a minha rota. qualquer nome que eu passar ele vai printar num
// objeto
// Route parameters, usado quando valores unicos são requisitados
res.send(req.params)
})
app.get('/mutants/:group', (req, res) => {
// query string parameters - usado para adicionar novos dados
// ao meu serviço backend e para tudo que é opcional
// res.send(req.params)
res.send(req.query)
// query parameters são dados salvos e alocados em objetos
})
app.get('/mutants/x-men/:id', (req, res) => {
const mutant = mutants.find( m => { // .find é uma função do JS
return (
m.id === parseInt(req.params.id)
)
})
if (!mutant) (
res.status(404).send('This mutant is not register in our database.')
// 404 é uma convenção de referencia quando um dado não é achado
)
res.send(mutant)
})
app.post('/x-men/mutants', (req, res) => { // adicionar um novo item na minha rota
// Nunca, jamais devemos confiar nos dados que os clientes estão mandando
// para a nossa api. Por isso é preciso validar os dados que estão entrando.
// Sendo assim, fazemos uma validação
// if (!req.body.name || req.body.name.length < 3) {
// // Acontece que aqui eu estou fazendo duas validações diferentes
// res.status(400).send('Name is required and need to have at least 3 caracters')
// return
// }
// Talvez seja melhor usar um framework que garanta o tipo de dado
// que está entrando e faz esse trabalho de manipular as mensagens de rro
// para mim
// Para isso temos o JOI
const schema = {
name: Joi.string().min(3).required()
}
const result = Joi.validate(req.body, schema) // validando o tipo de dado que eu defini
// que eu quero que entre. Função com dois parametros. O body da requisição
// e o schema que eu montei. Tudo centro de uma variável pois ele
// me retornará um objeto com um monte de informações.
// console.log(result)
// No resultado a gente consegue ver que é uma msg gigante que ele retorna para o usuário
// podemos simplificar
if (result.error) {
res.status(400).send(result.error.details[0].message)
return
}
const mutant = {
id: mutants.length + 1,
name: req.body.name
} // definindo que o meu novo item será um objeto, pois ele fará parte
// de um array que já existe.
mutants.push(mutant) // adicionando ao array
res.send(mutant) // printando na tela
})
// levantando um listener
const port = process.env.PORT || 3001 // dando uma porta para a minha
// aplicação node. Se nada estiver definido eu uso a 3001
// no terminal rodar: export PORT=5000 - Porta que eu estou dando para
// essa aplicação
app.listen(port, () => console.log(`Listening on port ${port}...`))
// app.listen(3001, () => console.log('Listening on port 3001...'))<file_sep>// HTTP Modoule é um dos módulos mais poderosos do Node
// Ele pode ser usado para criar aplicações de conexões com web server
// Por exemplo, podemos criar um web Server que escula um http request numa
// porta qualquer. Criando, facilmente um backend para uma aplicação qualquer.
const http = require('http')
// const server = http.createServer()
// Acontece quem um http.createServer é um Event Emitter e ele vai
// carregar tudo o que um Event Emitter tem
// server.on
// server.addListener
// server.emit
// etc
// Ler depois de const server e server.on
const server = http.createServer((req, res) => {
if (req.url === '/'){ // criando um endreço na minha app
res.write('Hello World') // escrevendo na tela
res.end() // terminando a minha conexão
}
if (req.url === '/x-man/mutants'){
const mutants = [
{
mutant: "Cyclops",
name: "<NAME>",
power: "Rajada ocular"
},
{
mutant: "Iceman",
name: "Bob",
power: "Assumir forma de gelo"
},
{
mutant: "Dazzler",
name: "Alexis",
power: "Emissão de luz através do som"
},
{
mutant: "Strom",
name: "Ororo",
power: "Controladora do tempo"
}
]
res.write(JSON.stringify(mutants))
res.end()
}
})
// ler depois de listen
// server.on('connection', (socket) => {
// console.log('New connection...')
// }) //nome do listener é connection, que pode ser visto
// na documentação
// socket é o segundo parametro desse listening que irá guardar e avisar
// sempre que houver uma conexão no meu servidor.
// Em Real world não se faz dessa forma. Isso é muito low level
server.listen(3001) // dando uma porta para a minha aplicação rodar local
// Só que antes de um listen, é bom registrarmos um listener, como visto
// acima com server.on
console.log('Listening to port 3001...')<file_sep>const mongoose = require('mongoose')
const express = require('express')
const app = express()
const morgan = require('morgan')
const courses = require('./routes/courses')
const authors = require('./routes/authors')
mongoose.connect('mongodb://localhost:27017/population', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err))
app.use(express.json())
app.use(morgan('tiny'))
app.use('/courses', courses)
app.use('/authors', authors)
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))<file_sep>// Uma outra forma de trabalharmos com Promises é usando o async/await
// Async/await é como se fosse uma outra forma de trabalhar com promises
// vejamos o código que fizemos anteriormente
console.log('Eu venho antes...')
// Promise approach
// getUser(1)
// .then(user => {
// return getRepositories(user.gitHubUsername)
// })
// .then(repos => {
// return getCommits(repos[0])
// })
// .then(commits => {
// console.log('Commits', commits)
// })
// .catch(err => {
// console.log('Error', err.message)
// })
// Async/await approach
// tem uma forma específica de escrever
async function displayCommits() {
try {
const user = await getUser(1)
const repos = await getRepositories(user.gitHubUsername)
const commits = await getCommits(repos[0])
console.log(commits)
}
catch(err) { // Para caso houver algum reject da Promise
console.log('Error', err.message)
}
}
displayCommits() // executando a função async/await
console.log('Eu venho depois...')
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Reading a user from a database...')
resolve({
id: id,
gitHubUsername: 'gmbarroso'
})
}, 2000);
})
}
function getRepositories(user) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`Getting ${user} repositories`)
resolve(['repo1', 'repo2', 'repo3'])
}, 2000);
})
}
function getCommits(repos) {
return new Promise((resolve, reject) => {
console.log(repos)
setTimeout(() => {
console.log(`Getting ${repos} commits`)
resolve(['commit1', 'commit2'])
}, 2000);
})
}<file_sep>// Middleware
// Middleware functions é, basicamente uma function que pega uma
// request (req) e retorna, ou uma response (res) para o client ou um
// outro middleware como resposta.
// No exemplo dos X-men podemos ver diversos usos de diferentes middlewares
const Joi = require('joi')
const helmet = require('helmet')
const morgan = require('morgan')
const logger = require('./logger')
const authenticator = require('./authenticator')
const express = require('express')
const app = express()
app.use(express.json()) // middleware
// A cada request que for um json, ele passará por aqui para transformar
// esse request em um json legível para o node. (popula o req.body)
// como funciona?
// Todo request passa por um Request Processing Pipeline (RPP)
// Nesse pipeline teremos um ou mais middleware functions. E cada middleware
// vai retornar uma respose obj ou passa controle para outro middleware,
// tipo uma cadeia (exemplo logger e authenticator)
// Built-in middlewares
app.use(express.urlencoded({ exended: true })) // esse middleware usamos para que o meu
// possa compreeender requests sendo enviadas com diversas 'keys', por
// exemplo de um objeto. Usamos o 'extended: true' para que ele entenda
// requests complexas vindas de um form (arrays, objetos, etc). testar
// um post usando a oppção urlencoded no postman
app.use(express.static('catalogue')) // um outro middleware do express que
// usa arquivos estáticos para retornarem uma resposta ao cliente.
// ele cria uma rota usando o nome do arquivo criado dentro da pasta
// 'catalogue'. é usado apra arquivos de imagens, texto, etc
// Third-party middlewares
// atntar-se ao que usaremos pois cada import e app.use, consome o meu
// aplicativo
app.use(helmet()) // Middleware que protege contra alguns ataques básicos
app.use(morgan('tiny')) // log as requests no terminal
// app.use((req, res, next) => {
// console.log('Logging...')
// next() // next é o parametro passado para um middleware que diz: quando
// // acabar o que você fez nessa função, passe a diante no RPP
// // sem ele, nossa request fica presa.
// }) // É uma boa prática colocar todo middleware em um arquivo separado,
// conforme linha 30
app.use(logger)
// app.use((req, res, next) => {
// console.log('Authenticating...')
// next()
// })
app.use(authenticator)
const mutants = [
{
id: 1,
name: "Cyclops"
},
{
id: 2,
name: "Iceman",
},
{
id: 3,
name: "Dazzler",
},
{
id: 4,
name: "Strom",
}
]
const getMutant = (req, res) => {
const mutant = mutants.find( m => {
return (
m.id === parseInt(req.params.id)
)
})
return mutant
}
const validateMutantName = (req, res) => {
const schema = {
name: Joi.string().min(3).required()
}
return result = Joi.validate(req.body, schema)
}
// rotas
app.get('/x-men/mutants',
(req, res) => { // middleware
res.send(mutants)
}
// Nesta rota, por exemplo, o RPP tem duas middlewares:
// uma é o parse para json() (linha 12) que quando termina passa por uma
// rota (route()). essa rota retorna uma lista (response) para o cliente.
)
app.get('/x-men/mutants/:id', (req, res) => {
const mutant = getMutant(req, res)
if (!mutant) (
res.status(404).send('This mutant is not register in our database.')
)
res.send(mutant)
})
// então, basicamente, em toda definição de rotas teremos middlewares
// pois todos pegam uma request e retorna uma resposta para o cliente
// como está sendo o exemplo dos dois GET's acima.
app.post('/x-men/mutants', (req, res) => {
const result = validateMutantName(req, res)
if (result.error) {
return res.status(400).send(result.error.details[0].message)
}
const mutant = {
id: mutants.length + 1,
name: req.body.name
}
mutants.push(mutant)
res.send(mutant)
})
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))
<file_sep>const Joi = require('joi')
const validateMutantName = (req, res) => {
const schema = {
name: Joi.string().min(3).required()
}
return result = Joi.validate(req.body, schema)
}
module.exports = validateMutantName<file_sep>// Muitas vezes, ao debugarmos nosso código, não queremos deixar
// console.log espalhados no código
// uma solução para isso é usar o debug package do node
// dessa forma, podemos setar quando que queremos logs na nossa aplicação e assim
// não precisa espalhar console.log no código nem se preocupar em apagá-los
// const startupDebug = require('debug')('app:startup')
// const dbDebug = require('debug')('app:db')
const debug = require('debug')
const morgan = require('morgan')
const express = require('express')
const app = express()
if (app.get('env') === 'development') {
app.use(morgan('tiny'))
// console.log('Morgan enabled...')
debug('Morgan enabled...')
}
// Talvez, em algum da nossa aplicação queremos saber quando
// de há algum acesso a um database
// dbDebug('connected to the database...') // console.log
// mudando no terminal que logs queremos ver
// export DEBUG=app:startup
// export DEBUG=app:startup,app:db
// export DEBUG=app:*
// esport DEBUG=
// DEBUG=app:db npm start
// Nesse demo eu criei dois logs de debug, mas no mundo real não funciona assim
//
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))<file_sep>const Movies = require('../models/models')
const express = require('express')
const router = express.Router()
const validateMovieObj = require('../validations/movieValidator')
// const getMovieById = (req, res) => {
// const movie = Movies.find( m => {
// return (
// m.id === parseInt(req.params.id)
// )
// })
// if (!movie) (
// res.status(404).send('This movie is not register in our database.')
// )
// return movie
// }
router.get('/', async (req, res) => {
const movies = await Movies.find().sort('title')
res.send(movies)
})
router.get('/:id', async (req, res) => {
const movie = await Movies.findById(req.params.id)
if (!movie) (
res.status(404).send('This movie is not register in our database...')
)
res.send(movie)
})
router.post('/', async (req, res) => {
console.log('req', req)
const result = validateMovieObj(req, res)
console.log('result', result)
if (result.error) {
const resultTransformed = result.error.details.map((err) => {
return ({
parameter: err.path[0],
message: err.message
})
})
return res.status(400).send({
error: true,
validationErrors: resultTransformed
})
}
let movie = new Movies({
title: req.body.title,
year: req.body.year,
cast: req.body.cast,
genres: req.body.genres,
})
console.log('movie1', movie)
movie = await movie.save()
console.log('movie2', movie)
res.send(movie)
})
router.put('/:id', async (req, res) => {
const { error } = validateMovieObj(req, res)
if (error) {
return res.status(400).send(error.details)
}
const movieId = await Movies.findByIdAndUpdate(
req.params.id,
{
title: req.body.title,
year: req.body.year,
cast: req.body.cast,
genres: req.body.genres,
},
{ new: true }
)
if (!movieId) {
return res.status(404).send('This Movie Id does not exist...')
}
res.send(movieId)
})
router.delete('/:id', async (req, res) => {
const movie = await Movies.findByIdAndRemove(req.params.id)
if (!movie) {
return res.status(404).send('This Movie Id does not exist...')
}
res.send(movie)
})
module.exports = router<file_sep>// Fazendo um listener e manipulando os logs que ele apresenta.
const Logger = require('./logger')
const logger = new Logger()
logger.on('messageLogged', e => {
console.log('Listener called', e)
})
logger.log('message')<file_sep>// Muitas vezes queremos que que algumas operações assíncronas aconteçam
// ao mesmo tempo em paralelo, e quando elas são finalizadas, você quer
// retornar uma única resposta.
// Por exemplo: Podemos querer acessar a api do facebook e depois do
// instagram, e dai queremos um único resultado quando essas operações
// em paralelo tiverem sido resolvidas.
// Segue exemplo
const promise1 = new Promise((resolve) => { // pedindo entrada de só um
// parametro. Não precisamos do reject se não usarmos
setTimeout(() => {
console.log(('Async operation 1...'))
resolve(1)
}, 2000);
})
const promise2 = new Promise((resolve) => {
setTimeout(() => {
console.log(('Async operation 2...'))
resolve(2)
}, 2000);
})
// Promise.race([promise1, promise2])
// .then(console.log)
Promise.all([promise1, promise2])
// .then(console.log)
.then(result => console.log(result))
.catch(err => console.log('Error', err.message))<file_sep>const mongoose = require('mongoose')
const { authorSchema } = require('../models/authorModel')
const courseSchema = new mongoose.Schema({
name: String,
// No esquema Embedding é um pouco diferente. A collecgtion vai direto dentro dele
author: authorSchema
})
const Courses = mongoose.model('Courses', courseSchema)
module.exports.Courses = Courses
<file_sep>// Trade off between query performance vs consistency
// é preciso pensar, na sua aplicação, qual o melhor tipo
// de relações entre dados eu vou querer. Ex: cursos
// Relações Using References (Normalization) -> CONSISTENCY
let author = {
name: '<NAME>'
}
let course = {
author: 'id', // usando uma referência
}
// Aqui Temos diferentes collections que vamos utilizar suas propriedades
// para relacionarem-se
// Relações Using Embedded Documents (Denormalization) -> PERFORMANCE
let course = {
author: { // incorporando uma coleção dentro da outra
name: '<NAME>'
}
}
// Hybrid
// Aqui é uma mistura de PERFORMANCE com CONSISTENCY
// Nessa abordagem a gente consegue rapidamente acessar o obj de course juntamente com
// o author para otimizar o desempenho da consulta. No entanto, não precisamos armazenar
// todas as propriedades de um author dentro de um course. Essa abrdagem é perfeita
// se queremos acessar instantaneamente os dados do meu banco num determinado momento
let author = {
name: 'Guilherme'
// 50 outras propriedades
}
let course = {
author: {
id: 'referencia',
name: 'Guilherme'
}
}
<file_sep>const Joi = require('joi')
const express = require('express')
const app = express()
const movies = require('./movies.json')
app.use(express.json())
const validateMovieObj = (req, res) => {
const schema = {
title: Joi.string().min(3).required(),
year: Joi.number().required(),
cast: Joi.array(),
genres: Joi.array().min(1).required()
}
return result = Joi.validate(req.body, schema)
}
const getMovieById = (req, res) => {
const movie = movies.find( m => {
console.log(req.params)
return (
m.id === parseInt(req.params.id)
)
})
if (!movie) (
res.status(404).send('This movie is not register in our database.')
)
return movie
}
const getMovieByGenreOrName = (req, res) => {
const movie = movies.filter( m => {
// m.title === req.params.title
// m.genres === req.params.genres
// if (req.params.genres === 'Action') {
// return m.genres.includes('Action')
// }
// if (req.params.genres === 'Drama') {
// return m.genres.includes('Drama')
// }
// if (req.params.genres === 'Biography') {
// return m.genres.includes('Biography')
// }
return m.genres.includes(req.params.genres)
})
// includes
// filter
// find
// contains
// Não misturar responsabilidade
// if (movie.length === 0) { // Cannot set headers after they are sent to the client
// return ( // Converting circular structure to JSON
// res.status(404).send('This movie genre is not register in our database.')
// )
// }
return movie
}
app.get('/movies', (req, res) => {
res.send(movies)
})
app.get('/movies/:id', (req, res) => {
const movie = getMovieById(req, res)
res.send(movie)
})
app.get('/movies/:genres', (req, res) => {
const movie = getMovieByGenreOrName(req, res)
if (movie.length === 0) {
return (
res.status(404).send('This movie genre is not register in our database.')
)
}
res.send(movie)
})
app.post('/movies', (req, res) => {
const result = validateMovieObj(req, res)
if (result.error) {
return res.status(400).send(result.error.details[0].message)
}
const movie = {
id: movies.length + 1,
title: req.body.title,
year: req.body.year,
cast: req.body.cast,
genres: req.body.genres,
}
movies.push(movie)
res.send(movie)
})
app.put('/movies/:id', (req, res) => {
const movieId = getMovieById(req, res)
const { error } = validateMovieObj(req, res)
if (error) {
return res.status(400).send(result.error.details[0].message)
}
movieId.title = req.body.title
movieId.year = req.body.year
movieId.cast = req.body.cast
movieId.genres = req.body.genres
res.send(movieId)
})
app.delete('/movies/:id', (req, res) => {
const movie = getMovieById(req, res)
const index = movies.indexOf(movie)
movies.splice(index, 1)
res.send(movie)
})
const port = process.env.PORT || 3001
app.listen(port, () => console.log(`Listening on port ${port}...`))
// Não é boa prática instalar nodemon global
<file_sep>// Promises
// Uma Promise é um objeto que contém o resultado final de uma operação assíncrona
// Portanto, quando uma operação assíncrona termina ele pode me retornar um valor
// ou um erro.
// Uma primise pode estar em três estados. Pending, Fulfilled (resolve) ou Rejected
// (reject)
// Exemplo
const promise = new Promise((resolve, reject) => {
// Iniciando uma operação assíncrona (acessar um database por exemplo,
// ou um webservice, ou uma api)
// ...
// Se completar teremos um valor ou um erro
// Passando uma operação assíncrona para dentro da Promise
setTimeout(() => {
// resolve(1)
reject(new Error('message'))
}, 2000)
// completado
// resolve(1)
// rejeitado
// reject(new Error('message'))
})
// Temos que consumir essa Promise de alguma forma (.then ou .catch)
// promise.then // para pegar o valor da operação
// promise.catch // para pegar o erro da operação
promise
.then(result => {
console.log('Result', result)
})
.catch(err => {
console.log('Error', err.message)
})
<file_sep>const Courses = require('../models/courseModel')
const { Authors } = require('../models/authorModel')
const express = require('express')
const router = express.Router()
// const validateCustomerObj = require('../validations/customerValidation')
router.get('/', async (req, res) => {
const courses = await Courses
.find()
.populate('author', 'name -_id')
.sort('name')
res.send(courses)
})
router.post('/', async (req, res) => {
// const result = validateCustomerObj(req, res)
// if (result.error) return res.status(400).send()
let course = new Courses({
name: req.body.name,
author: new Authors({ name: 'Guilherme' })
})
course = await course.save()
res.send(course)
})
module.exports = router | 3c47d8f7ade3285314fd5497a83556e1d5f11f85 | [
"JavaScript"
] | 37 | JavaScript | gmbarroso/learning-nodejs | 9e8e2814a9476c3f032fc36b41d10ce8de5f6a62 | f856fa982951729b4d473c4849354593731cc3bb |
refs/heads/master | <repo_name>achmadrizkin/flutter_calendar<file_sep>/android/app/src/main/kotlin/com/example/todolist_app/MainActivity.kt
package com.example.todolist_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 37091f83a189db163f1e462ba830e96b01348f5f | [
"Kotlin"
] | 1 | Kotlin | achmadrizkin/flutter_calendar | 831b73b00aeae0e52103eb343eca2d7d668f6661 | cea6df1d7d1a99b316b7794fb918f22c61e3e37d |
refs/heads/main | <file_sep>//#include <stdio.h>
//
//int main()
//{
// //prob1-1
// printf("花城 将英\n");
//
// //prob1-2
// printf("123\n456\n789\n");
//
// //prob1-3
// printf("%d + %d = %d\n", 1, 1, 1 + 1);
// printf("%d + %d = %d\n", 2, 3, 2 + 3);
//
// //prob1-4
// printf("%d + %d + %d = %d\n", 1, 2, 3, 1 + 2 + 3);
//
// //prob2-1
// int a, b;
// printf("a = ");
// scanf("%d", &a);
// printf("b = ");
// scanf("%d", &b);
//
// printf("a + b = %d\n", a + b);
// printf("a - b = %d\n", a - b);
// printf("a * b = %d\n", a * b);
// printf("a / b = %d\n", a / b);
// printf("a % b = %d\n", a % b);
//
// //prob2-2
// int width = 0;
// int height = 0;
// int area = 0;
//
// printf("長方形の幅:");
// scanf("%d", &width);
//
// printf("長方形の高さ:");
// scanf("%d", &height);
//
// area = width * height;
//
// printf("長方形の面積は、%dm2です。",area);
//
// return 0;
//} | 49a4c6c511cc1a66cdcca72d9e020f655403d5c1 | [
"C++"
] | 1 | C++ | Hanashiro-Shoei-20/SubeSubeGani | 4e0ff44988c99428cb3591ef33ae372dfd7becb2 | db50aba049ea52cf0176570d42d4ec20474ee951 |
refs/heads/master | <repo_name>Zerixx/Ronin<file_sep>/src/ronin-world/Client Communications/Packet Handlers/TradeHandler.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::SendTradeStatus(uint32 TradeStatus)
{
OutPacket(SMSG_TRADE_STATUS, 4, &TradeStatus);
};
void WorldSession::HandleInitiateTrade(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN();
uint64 guid;
recv_data >> guid;
PlayerTradeStatus tradeStatus = TRADE_STATUS_BEGIN_TRADE;
Player* pTarget = _player->GetMapInstance()->GetPlayer((uint32)guid);
if(pTarget == NULL || !pTarget->IsInWorld())
tradeStatus = TRADE_STATUS_NO_TARGET;
else if(_player->isDead())
tradeStatus = TRADE_STATUS_YOU_ARE_DEAD;
else if(pTarget->isDead())
tradeStatus = TRADE_STATUS_TARGET_IS_DEAD;
else if(_player->IsStunned())
tradeStatus = TRADE_STATUS_YOU_ARE_STUNNED;
else if(pTarget->IsStunned())
tradeStatus = TRADE_STATUS_TARGET_IS_STUNNED;
else if(pTarget->m_tradeData)
tradeStatus = TRADE_STATUS_TARGET_IS_BUSY;
else if(pTarget->GetTeam() != _player->GetTeam() && GetPermissionCount() == 0)
tradeStatus = TRADE_STATUS_TARGET_WRONG_FACTION;
else if(pTarget->m_ignores.find(_player->GetGUID()) != pTarget->m_ignores.end())
tradeStatus = TRADE_STATUS_TARGET_IGNORING_YOU;
else if(_player->GetDistanceSq(pTarget) > 100.0f) // This needs to be checked
tradeStatus = TRADE_STATUS_TARGET_TOO_FAR;
else if(pTarget->m_session == NULL || pTarget->m_session->GetSocket() == NULL)
tradeStatus = TRADE_STATUS_TARGET_LOGGING_OUT;
else
{
pTarget->CreateNewTrade(_player->GetGUID());
_player->CreateNewTrade(pTarget->GetGUID());
pTarget->SendTradeUpdate(false, tradeStatus);
return;
}
_player->SendTradeUpdate(false, tradeStatus);
_player->ResetTradeVariables(); // Clear our trade data
}
void WorldSession::HandleBeginTrade(WorldPacket & recv_data)
{
}
void WorldSession::HandleBusyTrade(WorldPacket & recv_data)
{
}
void WorldSession::HandleIgnoreTrade(WorldPacket & recv_data)
{
}
void WorldSession::HandleCancelTrade(WorldPacket & recv_data)
{
}
void WorldSession::HandleUnacceptTrade(WorldPacket & recv_data)
{
}
void WorldSession::HandleSetTradeItem(WorldPacket & recv_data)
{
}
void WorldSession::HandleSetTradeGold(WorldPacket & recv_data)
{
}
void WorldSession::HandleClearTradeItem(WorldPacket & recv_data)
{
}
void WorldSession::HandleAcceptTrade(WorldPacket & recv_data)
{
}
<file_sep>/src/ronin-world/Map System/Map Managers/InstanceManager.h
/*
* Sandshroud Project Ronin
* Copyright (C) 2015-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
extern const uint32 MapInstanceUpdatePeriod;
class MapInstanceContainer;
class InstanceData;
// Each instance has it's own instance data linked to unique IDs
typedef std::map<uint32, InstanceData*> InstanceDataMap;
class SERVER_DECL InstanceManager
{
public:
InstanceManager();
~InstanceManager();
void Destruct();
void Launch();
void Prepare();
// Quick storage of map data for checking instance allocation later
void AddMapData(MapEntry *entry, Map *map) { mapDataLock.Acquire(); m_mapData.insert(std::make_pair(entry->MapID, map)); mapDataLock.Release(); }
// Grab that instance stuff
MapInstance *GetInstanceForObject(WorldObject *obj);
// Pre teleport check for instance creation
uint32 PreTeleportInstanceCheck(uint64 guid, uint32 mapId, uint32 instanceId, bool canCreate = true);
uint32 AllocateCreatureGuid() { counterLock.Acquire(); uint32 ret = ++m_creatureGUIDCounter; counterLock.Release(); return ret; };
uint32 AllocateGameObjectGuid() { counterLock.Acquire(); uint32 ret = ++m_gameObjectGUIDCounter; counterLock.Release(); return ret; };
private:
Map *GetMapData(uint32 mapId) { Map *ret = NULL; mapDataLock.Acquire(); ret = m_mapData.find(mapId) == m_mapData.end() ? NULL : m_mapData.at(mapId); mapDataLock.Release(); return ret; }
void _AddInstance(uint32 instanceId, MapInstance *instance);
MapInstance *_LoadInstance(uint32 mapId, uint32 instanceId);
friend class InstanceManagerSlave;
void HandleUpdateRequests(InstanceManagerSlave *slaveThis);
// Processing queue lock
Mutex instancePoolLock, instanceStorageLock;
std::deque<MapInstanceContainer*> mInstancePool;
// First is instance id, second is pointer
std::map<uint32, std::pair<MapInstanceContainer*, MapInstance*>> mInstanceStorage;
Mutex counterLock;
// Counter
uint32 m_instanceCounter;
// Creature guids
uint32 m_creatureGUIDCounter;
// Gameobject guids
uint32 m_gameObjectGUIDCounter;
// instance data storage
InstanceDataMap m_instanceData;
// Map data storage
Mutex mapDataLock;
std::map<uint32, Map*> m_mapData;
};
extern SERVER_DECL InstanceManager sInstanceMgr;
class MapInstanceContainer
{
public:
MapInstanceContainer(MapInstance *instance) : _lastUpdateTimer(0), _instance(instance) {}
void Invalidate() { _instance = NULL; _lastUpdateTimer = 0; }
MapInstance *Get() { return _instance; }
bool Validate(uint32 msTime, uint32 &diff)
{
// Calculate diff between last update and now
diff = getMSTimeDiff(msTime, _lastUpdateTimer);
// Profile diff and update timout if needed
if(diff > MapInstanceUpdatePeriod)
return true;
return false;
}
void ResetTimer(uint32 msTime) { _lastUpdateTimer = msTime; }
private:
uint32 _lastUpdateTimer;
MapInstance *_instance;
};
class InstanceManagerSlave : public ThreadContext
{
public: // Just make calls into instance management, then return true for auto deletion.
bool run() { sInstanceMgr.HandleUpdateRequests(this); return true; }
};
class InstanceData
{
public:
void LoadFromDB(Field * fields);
void SaveToDB();
void DeleteFromDB();
uint32 GetInstanceId() { return m_instanceId; }
uint32 GetMapId() { return m_mapId; }
WoWGuid getCreatorGuid() { return m_creatorGuid; }
uint32 getCreatorGroupID() { return m_creatorGroup; }
time_t getCreationTime() { return m_creation; }
uint32 getDifficulty() { return m_difficulty; }
time_t getExpirationTime() { return m_expiration; }
bool isBattleground() { return m_isBattleground; }
void AcquireSaveLock() { m_savedLock.Acquire(); }
void ReleaseSaveLock() { m_savedLock.Release(); }
void AddKilledNPC(uint32 counter) { m_killedNpcs.insert(counter); }
void AddSavedPlayer(uint32 counter) { m_SavedPlayers.insert(counter); }
void AddEnteredPlayer(uint32 counter) { m_EnteredPlayers.insert(counter); }
bool HasKilledNPC(uint32 counter) { return m_killedNpcs.find(counter) != m_killedNpcs.end(); }
bool HasSavedPlayer(uint32 counter) { return m_SavedPlayers.find(counter) != m_SavedPlayers.end(); }
bool HasEnteredPlayer(uint32 counter) { return m_EnteredPlayers.find(counter) != m_EnteredPlayers.end(); }
private:
uint32 m_instanceId;
uint32 m_mapId;
WoWGuid m_creatorGuid;
uint32 m_creatorGroup;
time_t m_creation;
uint32 m_difficulty;
time_t m_expiration;
bool m_isBattleground;
Mutex m_savedLock;
std::set<uint32> m_killedNpcs;
std::set<uint32> m_SavedPlayers;
std::set<uint32> m_EnteredPlayers;
};
<file_sep>/src/ronin-world/Unit Systems/UnitPathSystem.cpp
#include "StdAfx.h"
float UnitPathSystem::fInfinite = std::numeric_limits<float>::infinity();
UnitPathSystem::UnitPathSystem(Unit *unit) : m_Unit(unit), m_autoPath(false), _waypointPath(NULL), m_autoPathDelay(0), m_pendingAutoPathDelay(0), m_pathCounter(0), m_pathStartTime(0), m_pathLength(0), srcPoint(), _destX(fInfinite), _destY(fInfinite), _destZ(0.f), _destO(0.f), m_lastMSTimeUpdate(0), m_lastPositionUpdate(0), pathPoolId(0xFF)
{
}
UnitPathSystem::~UnitPathSystem()
{
_CleanupPath();
}
bool UnitPathSystem::IsActiveObject()
{
return m_Unit->IsActiveObject();
}
bool UnitPathSystem::IsActivated()
{
return m_Unit->IsActivated();
}
void UnitPathSystem::InactiveUpdate(uint32 msTime, uint32 uiDiff)
{
// Dunno, we don't need to process this atm
}
bool UnitPathSystem::Update(uint32 msTime, uint32 uiDiff, bool fromMovement)
{
// If it's the same mstime(same world tick), return
if(m_lastMSTimeUpdate >= msTime)
{
if(fromMovement && hasDestination()) // Update our current position to our previously calculated update point
{ // Note that only movement cares what our return value is
m_Unit->GetMovementInterface()->MoveClientPosition(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z, lastUpdatePoint.orientationOverride);
return false;
}
return true;
}
// Update ms timer
m_lastMSTimeUpdate = msTime;
if(m_autoPathDelay > uiDiff)
m_autoPathDelay -= uiDiff;
else m_autoPathDelay = 0;
// Calculate our new position if we have a destination
if(hasDestination())
{
if(msTime <= m_pathStartTime)
return false;
uint32 timeWalked = msTime-m_pathStartTime;
if(timeWalked >= m_pathLength || m_movementPoints.empty())
{
m_Unit->GetMovementInterface()->MoveClientPosition(_destX,_destY,_destZ,_destO);
_CleanupPath();
}
else
{
// Move towards destination
MovementPoint *lastPoint = &srcPoint, *nextPoint = m_movementPoints.front();
if(timeWalked >= nextPoint->timeStamp && m_movementPoints.size() != 1)
{
lastPoint = nextPoint;
while(m_movementPoints.size() >= 2)
{
if((nextPoint = m_movementPoints.at(1))->timeStamp >= timeWalked)
{
if(nextPoint->timeStamp == timeWalked)
{ //
m_Unit->GetMovementInterface()->MoveClientPosition(nextPoint->pos.x, nextPoint->pos.y, nextPoint->pos.z, m_Unit->GetOrientation());
return false;
}
break;
}
// Remove the last point since we don't need it
m_movementPoints.pop_front();
delete lastPoint;
// Get the new last point
lastPoint = nextPoint;
nextPoint = NULL;
}
}
if(nextPoint == NULL) // No next point means we've cleared up our movement path
{
m_Unit->GetMovementInterface()->MoveClientPosition(_destX,_destY,_destZ,_destO);
_CleanupPath();
return true;
}
// Calculate the time percentage of movement between our two points that we've moved so far
uint32 moveDiff = nextPoint->timeStamp-lastPoint->timeStamp, moveDiff2 = timeWalked-lastPoint->timeStamp, timeLeft = moveDiff-moveDiff2;
float p = float(timeLeft)/float(moveDiff), x = lastPoint->pos.x, y = lastPoint->pos.y, z = lastPoint->pos.z, x2 = nextPoint->pos.x, y2 = nextPoint->pos.y, z2 = nextPoint->pos.z;
// Update our last update point
lastUpdatePoint.timeStamp = timeWalked;
lastUpdatePoint.pos.x = x2-((x2-x)*p);
lastUpdatePoint.pos.y = y2-((y2-y)*p);
lastUpdatePoint.pos.z = z2-((z2-z)*p);
lastUpdatePoint.orientationOverride = m_Unit->calcRadAngle(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, x2, y2);
// If we're from our movement interface, then pop to our new position
if(fromMovement) // Update unit client position, post update heartbeat will reset unit position for us
m_Unit->GetMovementInterface()->MoveClientPosition(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z, lastUpdatePoint.orientationOverride);
return false;
}
}
if(m_autoPath)
{ //Process next steps of path
if(m_autoPathDelay)
return false;
else if(m_autoPathDelay = m_pendingAutoPathDelay)
{
m_pendingAutoPathDelay = 0;
return false;
}
if(_waypointPath && !_waypointPath->empty())
{
if(pathIterator == _waypointPath->end() || ++pathIterator == _waypointPath->end())
pathIterator = _waypointPath->begin();
CreatureWaypoint *point = pathIterator->second;
switch(point->moveType)
{
case 0: SetSpeed(MOVE_SPEED_WALK); break;
case 1: SetSpeed(MOVE_SPEED_RUN); break;
case 2: SetSpeed(MOVE_SPEED_FLIGHT); break;
}
float x = point->x, y = point->y, z = point->z, o = point->o;
uint32 delay = point->delay;
// Grab next point
WaypointStorage::iterator itr = pathIterator;
if(itr == _waypointPath->end() || ++itr == _waypointPath->end())
itr = _waypointPath->begin();
point = itr->second;
if(delay <= 500) // Calculate a new angle
o = m_Unit->calcRadAngle(x, y, point->x, point->y);
MoveToPoint(x, y, z, o);
m_pendingAutoPathDelay = delay;
}
}
return true;
}
void UnitPathSystem::EnterEvade()
{
m_autoPath = false;
if(_waypointPath == NULL)
{
MoveToPoint(m_Unit->GetSpawnX(), m_Unit->GetSpawnY(), m_Unit->GetSpawnZ(), m_Unit->GetSpawnO());
return;
}
}
void UnitPathSystem::SetAutoPath(WaypointStorage *storage)
{
if(storage == NULL || storage->empty())
return;
m_autoPath = true;
pathIterator = (_waypointPath = storage)->begin();
}
bool UnitPathSystem::hasDestination() { return !(_destX == fInfinite && _destY == fInfinite); }
bool UnitPathSystem::GetDestination(float &x, float &y, float *z)
{
if(!hasDestination())
return false;
x = _destX;
y = _destY;
if(z) *z = _destZ;
return true;
}
bool UnitPathSystem::closeToDestination(uint32 msTime)
{ // Creatures update every 400ms, should be changed to be within the 500ms block creation
if(((msTime-m_pathStartTime) + 400) >= m_pathLength)
return true;
return false;
}
void UnitPathSystem::SetSpeed(MovementSpeedTypes speedType)
{
_moveSpeed = speedType;
}
void UnitPathSystem::_CleanupPath()
{
_destX = _destY = fInfinite;
while(!m_movementPoints.empty())
{
MovementPoint *point = m_movementPoints.front();
m_movementPoints.pop_front();
delete point;
}
lastUpdatePoint.timeStamp = 0; // Clean up our last update point
lastUpdatePoint.pos.x = lastUpdatePoint.pos.y = lastUpdatePoint.pos.z = fInfinite;
}
uint32 UnitPathSystem::buildMonsterMoveFlags(uint8 packetSendFlags)
{
if(packetSendFlags & MOVEBCFLAG_UNCOMP)
return 0x00400000;
// No monster flags required
return 0;
}
void UnitPathSystem::SetFollowTarget(Unit *target, float distance)
{
}
void UnitPathSystem::MoveToPoint(float x, float y, float z, float o)
{
if((_destX == x && _destY == y) || (m_Unit->GetPositionX() == x && m_Unit->GetPositionY() == y))
return;
// Clean up any existing paths
_CleanupPath();
m_pathCounter++;
m_lastMSTimeUpdate = m_pathStartTime = getMSTime();
m_Unit->GetPosition(srcPoint.pos.x, srcPoint.pos.y, srcPoint.pos.z);
// Set our last update point data to our source with no move time
lastUpdatePoint.timeStamp = 0;
m_Unit->GetPosition(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z);
_destX = x, _destY = y, _destZ = z, _destO = o;
if(sNavMeshInterface.IsNavmeshLoadedAtPosition(m_Unit->GetMapId(), x, y) && sNavMeshInterface.IsNavmeshLoadedAtPosition(m_Unit->GetMapId(), srcPoint.pos.x, srcPoint.pos.y))
sNavMeshInterface.BuildFullPath(m_Unit, m_Unit->GetMapId(), srcPoint.pos.x, srcPoint.pos.y, srcPoint.pos.z, x, y, z, true);
else
{
MapInstance *instance = m_Unit->GetMapInstance();
float speed = m_Unit->GetMoveSpeed(_moveSpeed), dist = sqrtf(m_Unit->GetDistanceSq(x, y, z));
MovementPoint *lastPoint = &srcPoint; // Store our starting position
m_pathLength = (dist/speed)*1000.f;
if(m_pathLength > 800)
{
bool ignoreTerrainHeight = m_Unit->canFly();
float maxZ = std::max<float>(srcPoint.pos.z, _destZ);
float terrainHeight = m_Unit->GetGroundHeight(), targetTHeight = instance->GetWalkableHeight(m_Unit, _destX, _destY, _destZ), posToAdd = 0.f;
if(ignoreTerrainHeight)
posToAdd = ((_destZ-srcPoint.pos.z)/(((float)m_pathLength)/500.f));
else posToAdd = ((targetTHeight-terrainHeight)/(((float)m_pathLength)/500.f));
float lastCalcPoint = lastPoint->pos.z;// Path calculation
uint32 timeToMove = 500;
while((m_pathLength-timeToMove) > 500)
{
timeToMove += 500;
lastCalcPoint += posToAdd;
float p = float(timeToMove)/float(m_pathLength), px = srcPoint.pos.x-((srcPoint.pos.x-_destX)*p), py = srcPoint.pos.y-((srcPoint.pos.y-_destY)*p);
float targetZ = instance->GetWalkableHeight(m_Unit, px, py, maxZ);
if(ignoreTerrainHeight && lastCalcPoint > targetZ)
targetZ = lastCalcPoint;
m_movementPoints.push_back(lastPoint = new MovementPoint(timeToMove, px, py, targetZ));
}
}
m_movementPoints.push_back(new MovementPoint(m_pathLength, _destX, _destY, _destZ));
}
BroadcastMovementPacket();
}
void UnitPathSystem::UpdateOrientation(Unit *unitTarget)
{
float angle = NormAngle(m_Unit->GetAngle(unitTarget));
if((m_Unit->GetPositionX() == _destX && m_Unit->GetPositionY() == _destY) || (_destX == fInfinite && _destY == fInfinite) || (lastUpdatePoint.timeStamp >= m_pathLength))
{
SetOrientation(angle);
return;
}
_destO = angle;
// Broadcast a movement change
WorldPacket data(SMSG_MONSTER_MOVE, 100);
data << m_Unit->GetGUID().asPacked();
data << uint8(0);
data.appendvector(LocationVector(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z), false);
// If we are at our destination, or have no destination, broadcast a stop packet
if((m_Unit->GetPositionX() == _destX && m_Unit->GetPositionY() == _destY) || (_destX == fInfinite && _destY == fInfinite))
data << uint32(0) << uint8(5) << float( _destO );
else
{
data << uint32(m_pathCounter);
data << uint8(4) << float( _destO );
data << uint32(0x00400000);
data << uint32(m_pathLength - lastUpdatePoint.timeStamp);
uint32 counter = 0;
size_t counterPos = data.wpos();
data << uint32(0); // movement point counter
for(uint32 i = 0; i < m_movementPoints.size(); i++)
{
if(MovementPoint *path = m_movementPoints[i])
{
if(path->timeStamp <= lastUpdatePoint.timeStamp)
continue;
data << path->pos.x << path->pos.y << path->pos.z;
counter++;
}
}
data.put<uint32>(counterPos, counter);
}
m_Unit->SendMessageToSet( &data, false );
}
void UnitPathSystem::SetOrientation(float orientation)
{
// Only update if we need to
if(RONIN_UTIL::fuzzyEq(orientation, m_Unit->GetOrientation()))
return;
m_pathCounter++;
m_Unit->SetOrientation(orientation);
LocationVector *pos = m_Unit->GetPositionV();
WorldPacket data(SMSG_MONSTER_MOVE, 100);
data << m_Unit->GetGUID().asPacked();
data << uint8(0);
data.appendvector(*pos);
data << uint32(m_pathCounter);
data << uint8(4) << float( m_Unit->GetOrientation() );
data << uint32(0x00400000) << uint32(0) << uint32(1);
data.appendvector(*pos);
m_Unit->SendMessageToSet( &data, false );
}
void UnitPathSystem::StopMoving()
{
_CleanupPath();
// Set destX/Y to infinite, zero out destZ and Orientation
_destX = _destY = fInfinite; _destZ = _destO = 0.f;
BroadcastMovementPacket();
}
void UnitPathSystem::BroadcastMovementPacket(uint8 packetSendFlags)
{
// Grab our destination point data
MovementPoint *lastPoint = m_movementPoints.empty() ? NULL : m_movementPoints[m_movementPoints.size()-1];
if(lastPoint == NULL)
return;
// Grab our start point data
LocationVector startPoint(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z);
// If we have no path data but are broadcasting, check validity of last update point
if(lastUpdatePoint.pos.x == fInfinite || lastUpdatePoint.pos.y == fInfinite)
startPoint = *m_Unit->GetPositionV();
WorldPacket data(SMSG_MONSTER_MOVE, 100);
data << m_Unit->GetGUID().asPacked();
data << uint8(0);
// We need to append our start vector here, but need to use it later for compressed movement
data.appendvector(startPoint, false);
// If we are at our destination, or have no destination, broadcast a stop packet
if((lastUpdatePoint.pos.x == _destX && lastUpdatePoint.pos.y == _destY) || (_destX == fInfinite && _destY == fInfinite))
data << uint32(0) << uint8(1);
else
{
data << uint32(m_pathCounter);
if(_destO == fInfinite) data << uint8(0);
else data << uint8(4) << float( _destO );
data << uint32(buildMonsterMoveFlags(packetSendFlags));
data << uint32(m_pathLength);
uint32 counter = 1;
size_t counterPos = data.wpos();
data << uint32(counter);
// Append uncompressed buffer
if(packetSendFlags & MOVEBCFLAG_UNCOMP)
{
for(uint32 i = 0; i < m_movementPoints.size()-1; i++)
{
if(MovementPoint *path = m_movementPoints[i])
{
if(path->timeStamp <= lastUpdatePoint.timeStamp)
continue;
data << path->pos.x << path->pos.y << path->pos.z;
counter++;
}
}
}
// Append our last point, could use _dest if we wanted to
data << lastPoint->pos.x << lastPoint->pos.y << lastPoint->pos.z;
// Append compressed buffer here
if((packetSendFlags & MOVEBCFLAG_UNCOMP) == 0)
{
LocationVector middle(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z);
middle.x = (middle.x+lastPoint->pos.x)/2.f;
middle.y = (middle.y+lastPoint->pos.y)/2.f;
middle.z = (middle.z+lastPoint->pos.z)/2.f;
for(uint32 i = 0; i < m_movementPoints.size()-1; i++)
{
if(MovementPoint *path = m_movementPoints[i])
{
if(path->timeStamp <= lastUpdatePoint.timeStamp)
continue;
data << RONIN_UTIL::CompressMovementPoint(middle.x - path->pos.x, middle.y - path->pos.y, middle.z - path->pos.z);
counter++;
}
}
}
data.put<uint32>(counterPos, counter);
}
m_Unit->SendMessageToSet( &data, false );
}
void UnitPathSystem::SendMovementPacket(Player *plr, uint8 packetSendFlags)
{
if((m_Unit->GetPositionX() == _destX && m_Unit->GetPositionY() == _destY) || (_destX == fInfinite && _destY == fInfinite) || (lastUpdatePoint.timeStamp >= m_pathLength))
return;
MovementPoint *lastPoint = m_movementPoints.empty() ? NULL : m_movementPoints[m_movementPoints.size()-1];
if(lastPoint == NULL)
return;
WorldPacket data(SMSG_MONSTER_MOVE, 100);
data << m_Unit->GetGUID().asPacked();
data << uint8(0);
data.appendvector(LocationVector(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z), false);
data << uint32(m_pathCounter);
if(_destO == fInfinite) data << uint8(0);
else data << uint8(4) << float( _destO );
data << uint32(buildMonsterMoveFlags(packetSendFlags));
data << uint32(m_pathLength - lastUpdatePoint.timeStamp);
uint32 counter = 1;
size_t counterPos = data.wpos();
data << uint32(counter);
// Append uncompressed buffer
if(packetSendFlags & MOVEBCFLAG_UNCOMP)
{
for(uint32 i = 0; i < m_movementPoints.size()-1; i++)
{
if(MovementPoint *path = m_movementPoints[i])
{
if(path->timeStamp <= lastUpdatePoint.timeStamp)
continue;
data << path->pos.x << path->pos.y << path->pos.z;
counter++;
}
}
}
// Append our last point, could use _dest if we wanted to
data << lastPoint->pos.x << lastPoint->pos.y << lastPoint->pos.z;
// Append compressed buffer here
if((packetSendFlags & MOVEBCFLAG_UNCOMP) == 0)
{
LocationVector middle(lastUpdatePoint.pos.x, lastUpdatePoint.pos.y, lastUpdatePoint.pos.z);
middle.x = (middle.x+lastPoint->pos.x)/2.f;
middle.y = (middle.y+lastPoint->pos.y)/2.f;
middle.z = (middle.z+lastPoint->pos.z)/2.f;
for(uint32 i = 0; i < m_movementPoints.size()-1; i++)
{
if(MovementPoint *path = m_movementPoints[i])
{
if(path->timeStamp <= lastUpdatePoint.timeStamp)
continue;
data << RONIN_UTIL::CompressMovementPoint(middle.x - path->pos.x, middle.y - path->pos.y, middle.z - path->pos.z);
counter++;
}
}
}
data.put<uint32>(counterPos, counter);
plr->PushPacket(&data);
}
<file_sep>/src/ronin-world/Client Communications/Packet Handlers/LfgHandler.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleLFDPlrLockOpcode( WorldPacket& recv_data )
{
CHECK_INWORLD_RETURN();
DungeonSet::iterator itr;
DungeonSet randomDungeonSet;
LFGDungeonsEntry* dungeonEntry = NULL;
uint32 level = _player->getLevel();
DungeonSet LevelDungeonSet = sLfgMgr.GetLevelSet(level);
for (itr = LevelDungeonSet.begin(); itr != LevelDungeonSet.end(); itr++)
{
dungeonEntry = dbcLFGDungeons.LookupEntry(*itr);
if (dungeonEntry != NULL && dungeonEntry->LFGType == LFG_RANDOM
&& dungeonEntry->reqExpansion <= GetHighestExpansion()
&& dungeonEntry->minLevel <= level && level <= dungeonEntry->maxLevel)
randomDungeonSet.insert(dungeonEntry->Id);
dungeonEntry = NULL;
}
// Crow: Confirmed structure below
WorldPacket data(SMSG_LFG_PLAYER_INFO, 400);
uint8 randomsize = (uint8)randomDungeonSet.size();
data << randomsize;
for(itr = randomDungeonSet.begin(); itr != randomDungeonSet.end(); itr++)
{
dungeonEntry = dbcLFGDungeons.LookupEntry(*itr);
data << uint32(dungeonEntry->GetUniqueID());
uint8 done = 0;
Quest* QuestReward = NULL;
LfgReward* reward = sLfgMgr.GetLFGReward(*itr);
if(reward)
{
QuestReward = sQuestMgr.GetQuestPointer(reward->reward[0].QuestId);
if(QuestReward)
{
done = _player->HasFinishedQuest(reward->reward[0].QuestId);
if(!done)
done = _player->HasFinishedDailyQuest(reward->reward[0].QuestId);
if (done)
QuestReward = sQuestMgr.GetQuestPointer(reward->reward[1].QuestId);
}
}
if (QuestReward)
{
data << uint8(done);
data << uint32(sQuestMgr.GenerateRewardMoney(_player, QuestReward));
data << uint32(sQuestMgr.GenerateQuestXP(_player, QuestReward)*sWorld.getRate(RATE_QUESTXP));
data << uint32(reward->reward[done].MoneyReward);
data << uint32(reward->reward[done].XPReward);
data << uint8(QuestReward->count_reward_item);
if (QuestReward->count_reward_item)
{
ItemPrototype* proto = NULL;
for (uint8 i = 0; i < 4; i++)
{
if (!QuestReward->reward_item[i])
continue;
proto = sItemMgr.LookupEntry(QuestReward->reward_item[i]);
data << uint32(QuestReward->reward_item[i]);
data << uint32(proto ? proto->DisplayInfoID : 0);
data << uint32(QuestReward->reward_itemcount[i]);
}
}
}
else
{
data << uint8(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint8(0);
}
}
SendPacket(&data);
}
void WorldSession::HandleLFDPartyLockOpcode( WorldPacket& recv_data )
{
WorldPacket data(SMSG_LFG_PARTY_INFO, 400);
uint8 cnt = 0;
data << uint8(cnt);
for(uint8 i = 0; i < cnt; i++)
{
data << uint64(0);
uint32 count = 0;
data << count;
for(uint32 i = 0; i < count; i++)
{
data << uint32(0);
data << uint32(0);
}
}
SendPacket(&data);
}
<file_sep>/src/ronin-world/Map System/Map Managers/ContinentManager.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2015-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
ContinentManager::ContinentManager(MapEntry *mapEntry, Map *map) : ThreadContext(), m_mapEntry(mapEntry), m_mapId(mapEntry->MapID), m_mapData(map)
{
SetThreadState(THREADSTATE_PAUSED);
}
ContinentManager::~ContinentManager()
{
m_mapData = NULL;
}
bool ContinentManager::Initialize()
{
sLog.Notice("ContinentManager", "Creating continent %u(%s).", m_mapId, m_mapEntry->name);
if(m_continent = new MapInstance(m_mapData, m_mapId, 0))
return true;
return false;
}
bool ContinentManager::run()
{
// Preload all needed spawns etc
m_continent->Preload();
// Wait for our thread to be activated
while(GetThreadState() == THREADSTATE_PAUSED)
Delay(50);
sWorldMgr.MapLoaded(m_mapId);
// Initialize the base continent timers
uint32 mstime = getMSTime();
m_continent->Init(mstime);
// Initialize our counter at 0 and our last update time for diff calculations
uint32 counter = 0, lastUpdate = mstime;
do
{
if(!SetThreadState(THREADSTATE_BUSY))
break;
mstime = getMSTime();
int32 diff = std::min<uint32>(500, mstime - lastUpdate);
lastUpdate = mstime;
// Update our collision system via singular map system
sVMapInterface.UpdateSingleMap(m_mapId, diff);
// Process all pending removals in sequence
m_continent->_PerformPlayerRemovals();
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Process all pending inputs in sequence
m_continent->_ProcessInputQueue();
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all combat state updates before any unit updates
m_continent->_PerformCombatUpdates(mstime, diff);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all delayed spell updates before object updates
m_continent->_PerformDelayedSpellUpdates(mstime, diff);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all unit path updates in sequence
m_continent->_PerformUnitPathUpdates(mstime, diff);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all player updates in sequence
m_continent->_PerformPlayerUpdates(mstime, diff);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all dynamic object updates in sequence
m_continent->_PerformDynamicObjectUpdates(mstime, diff);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all creature updates in sequence
m_continent->_PerformCreatureUpdates(mstime, diff);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all object updates in sequence
m_continent->_PerformObjectUpdates(mstime, diff);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all movement updates in sequence without player data
m_continent->_PerformMovementUpdates(false);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all session updates in sequence
m_continent->_PerformSessionUpdates();
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all movement updates in sequence with player data
m_continent->_PerformMovementUpdates(true);
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Process secondary pending removals in sequence
m_continent->_PerformPlayerRemovals();
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Perform all pending object updates in sequence
m_continent->_PerformPendingUpdates();
if(!SetThreadState(THREADSTATE_BUSY))
break;
// Set the thread to sleep to prevent thread overrun and wasted cycles
if(!SetThreadState(THREADSTATE_SLEEPING))
break;
Delay(std::max<int32>(5, MapInstanceUpdatePeriod-(getMSTime()-lastUpdate)));
counter++;
}while(true);
sLog.Notice("ContinentManager", "Cleaning up continent %u (%s)", m_mapId, m_mapData->GetName());
// Remove us from content map
sWorldMgr.ContinentUnloaded(m_mapId);
// Clean up continent map instance
m_continent->Destruct();
m_continent = NULL;
// Unload all terrain
if(sWorld.ServerPreloading >= 1)
m_mapData->UnloadAllTerrain(true);
sLog.Debug("MapInstance", "Map %u shut down. (%s)", m_mapId, m_mapData->GetName());
return true;
}
<file_sep>/src/ronin-world/Spell/Spell.h
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
enum SpellEffectTargetFlags
{
EFF_TARGET_FLAGS_NONE = 0,
EFF_TARGET_FLAGS_GAMEOBJ = 1,
EFF_TARGET_FLAGS_UNIT = 2,
EFF_TARGET_FLAGS_PLAYER = 3
};
#define GO_FISHING_BOBBER 35591
#define SPELL_SPELL_CHANNEL_UPDATE_INTERVAL 1000
// Spell instance
class SERVER_DECL Spell : public SpellEffectClass
{
public:
Spell( Unit* Caster, SpellEntry *info, uint8 castNumber = 0, WoWGuid itemCaster = 0, Aura* aur = NULL);
~Spell();
virtual void Destruct();
void GetSpellDestination(LocationVector &dest)
{
SpellEffectClass::GetSpellDestination(dest);
if((m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) == 0)
return;
dest = m_targets.m_dest;
}
// Fills specified targets at the area of effect
void FillSpecifiedTargetsInArea(float srcx,float srcy,float srcz,uint32 ind, uint32 specification);
// Fills specified targets at the area of effect. We suppose we already inited this spell and know the details
void FillSpecifiedTargetsInArea(uint32 i,float srcx,float srcy,float srcz, float range, uint32 specification);
// Fills the targets at the area of effect
void FillAllTargetsInArea(uint32 i, float srcx,float srcy,float srcz, float range, bool includegameobjects = false);
// Fills the targets at the area of effect. We suppose we already inited this spell and know the details
void FillAllTargetsInArea(float srcx,float srcy,float srcz,uint32 ind);
// Fills the targets at the area of effect. We suppose we already inited this spell and know the details
void FillAllTargetsInArea(LocationVector & location,uint32 ind);
// Fills the targets at the area of effect. We suppose we already inited this spell and know the details
void FillAllFriendlyInArea(uint32 i, float srcx,float srcy,float srcz, float range);
// Fills the gameobject targets at the area of effect
void FillAllGameObjectTargetsInArea(uint32 i, float srcx,float srcy,float srcz, float range);
//get single Enemy as target
uint64 GetSinglePossibleEnemy(uint32 i, float prange=0);
//get single Enemy as target
uint64 GetSinglePossibleFriend(uint32 i, float prange=0);
//generate possible target list for a spell. Use as last resort since it is not acurate
bool GenerateTargets(SpellCastTargets *);
// Fills the target map of the spell effects
void FillTargetMap(bool fromDelayed);
// Prepares the spell thats going to cast to targets
uint8 prepare(SpellCastTargets *targets, bool triggered);
// Cancels the current spell
void cancel();
// Update spell state based on time difference
void Update(uint32 difftime);
// Checks against the cast position and cancels if we've moved
bool updatePosition(float x, float y, float z);
// Updates our channel based data for triggers etc
void _UpdateChanneledSpell(uint32 difftime);
// Updates delayed targets, calls finish() as well
bool UpdateDelayedTargetEffects(MapInstance *instance, uint32 diffTime);
// Casts the spell
void cast(bool);
// Finishes the casted spell
void finish();
// Take Power from the caster based on spell power usage
bool TakePower();
// Has power?
bool HasPower();
// Calculate power to take
int32 CalculateCost(int32 &powerField);
// Checks the caster is ready for cast
uint8 CanCast(bool tolerate);
// Removes reagents, ammo, and items/charges
void RemoveItems();
// Determines how much skill caster going to gain
void DetermineSkillUp();
// Increases cast time of the spell
void AddTime(uint32 type);
// Get Target Type
uint32 GetTargetType(uint32 implicittarget, uint32 i);
void AddCooldown();
void AddStartCooldown();
bool Reflect(Unit* refunit);
RONIN_INLINE uint32 getState() { return m_spellState; }
RONIN_INLINE SpellEntry *GetSpellProto() { return m_spellInfo; }
void CreateItem(uint32 itemId);
// Spell Targets
void HandleTargetNoObject();
bool AddTarget(uint32 i, uint32 TargetType, WorldObject* obj);
void AddAOETargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddPartyTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddRaidTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets, bool partylimit = false);
void AddChainTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddConeTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
void AddScriptedOrSpellFocusTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets);
uint64 static FindLowestHealthRaidMember(Player* Target, uint32 dist);
bool SpellEffectUpdateQuest(uint32 questid);
// 15007 = resurecting sickness
// This returns SPELL_ENTRY_Spell_Dmg_Type where 0 = SPELL_DMG_TYPE_NONE, 1 = SPELL_DMG_TYPE_MAGIC, 2 = SPELL_DMG_TYPE_MELEE, 3 = SPELL_DMG_TYPE_RANGED
// It should NOT be used for weapon_damage_type which needs: 0 = MELEE, 1 = OFFHAND, 2 = RANGED
RONIN_INLINE uint32 GetType() { return ( GetSpellProto()->Spell_Dmg_Type == SPELL_DMG_TYPE_NONE ? SPELL_DMG_TYPE_MAGIC : GetSpellProto()->Spell_Dmg_Type ); }
int32 chaindamage;
// -------------------------------------------
static bool IsBinary(SpellEntry * sp);
RONIN_INLINE static bool HasMechanic(SpellEntry * sp, uint32 MechanicsType)
{
if(sp->MechanicsType == MechanicsType)
return true;
for(uint8 i = 0; i < 3; i++)
if(sp->EffectMechanic[i] == MechanicsType)
return true;
return false;
}
RONIN_INLINE static uint32 GetMechanic(SpellEntry * sp)
{
if(sp->MechanicsType)
return sp->MechanicsType;
if(sp->EffectMechanic[2])
return sp->EffectMechanic[2];
if(sp->EffectMechanic[1])
return sp->EffectMechanic[1];
if(sp->EffectMechanic[0])
return sp->EffectMechanic[0];
return 0;
}
RONIN_INLINE static uint32 GetMechanicOfEffect(SpellEntry * sp, uint32 i)
{
if(sp->EffectMechanic[i])
return sp->EffectMechanic[i];
if(sp->MechanicsType)
return sp->MechanicsType;
return 0;
}
bool IsAuraApplyingSpell();
bool IsStealthSpell();
bool IsInvisibilitySpell();
bool CanEffectTargetGameObjects(uint32 i);
int32 damage;
Aura* m_triggeredByAura;
bool m_triggeredSpell;
bool m_AreaAura;
//uint32 TriggerSpellId; // used to set next spell to use
//uint64 TriggerSpellTarget; // used to set next spell target
float m_castPositionX;
float m_castPositionY;
float m_castPositionZ;
int32 damageToHit;
uint32 castedItemId;
uint32 m_pushbackCount;
bool duelSpell;
RONIN_INLINE void safe_cancel()
{
m_cancelled = true;
}
Spell* m_reflectedParent;
// Returns true iff spellEffect's effectNum effect affects testSpell based on EffectSpellClassMask
RONIN_INLINE static bool EffectAffectsSpell(SpellEntry* spellEffect, uint32 effectNum, SpellEntry* testSpell)
{
return ((testSpell->SpellGroupType[0] && (spellEffect->EffectSpellClassMask[effectNum][0] & testSpell->SpellGroupType[0])) ||
(testSpell->SpellGroupType[1] && (spellEffect->EffectSpellClassMask[effectNum][1] & testSpell->SpellGroupType[1])) ||
(testSpell->SpellGroupType[2] && (spellEffect->EffectSpellClassMask[effectNum][2] & testSpell->SpellGroupType[2])));
}
RONIN_INLINE uint32 GetDifficultySpell(SpellEntry * sp, uint32 difficulty)
{
uint32 spellid = 0;
SpellDifficultyEntry * sd = dbcSpellDifficulty.LookupEntry(sp->SpellDifficulty);
if(sd != NULL && sd->SpellId[difficulty] != 0 )
if(dbcSpell.LookupEntry(sd->SpellId[difficulty]) != NULL)
spellid = sd->SpellId[difficulty];
return spellid;
}
protected:
/// Spell state's
bool m_usesMana;
bool m_Delayed;
bool m_ForceConsumption;
// Current Targets to be used in effect handler
WoWGuid objTargetGuid, itemTargetGuid, m_magnetTarget;
uint8 m_canCastResult;
bool m_cancelled;
void DamageGosAround(uint32 i);
bool UseMissileDelay();
bool HasSpellEffect( uint32 effect )
{
for( uint32 i = 0; i < 3; ++i )
if( GetSpellProto()->Effect[ i ] == effect )
return true;
return false;
}
private:
// adds a target to the list, performing DidHit checks on units
void _AddTarget(WorldObject* target, const uint32 effIndex);
AuraApplicationResult CheckAuraApplication(Unit *target);
// didhit checker
uint8 _DidHit(Unit* target, float *resistOut = NULL, uint8 *reflectout = NULL);
public:
static std::map<uint8, uint32> m_implicitTargetFlags;
};
void ApplyDiminishingReturnTimer(int32 * Duration, Unit* Target, SpellEntry * spell);
void UnapplyDiminishingReturnTimer(Unit* Target, SpellEntry * spell);
uint32 GetDiminishingGroup(uint32 NameHash);
<file_sep>/src/ronin-world/Mainframe/Management/LfgMgr.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
initialiseSingleton( LfgMgr );
LfgMgr::LfgMgr()
{
MaxDungeonID = 0;
}
LfgMgr::~LfgMgr()
{
}
void LfgMgr::LoadRandomDungeonRewards()
{
uint32 count = 0;
QueryResult* result = WorldDatabase.Query("SELECT * FROM lfd_rewards ORDER BY dungeonid");
if(result != NULL)
{
do
{
Field* fields = result->Fetch();
uint32 dungeonid = fields[0].GetUInt32();
if(GetLFGReward(dungeonid))
continue;
uint32 questid[2], moneyreward[2], XPreward[2];
// First Reward
questid[0] = fields[2].GetUInt32();
moneyreward[0] = fields[3].GetUInt32();
XPreward[0] = fields[4].GetUInt32();
// Second reward
questid[1] = fields[5].GetUInt32();
moneyreward[1] = fields[6].GetUInt32();
XPreward[1] = fields[7].GetUInt32();
DungeonRewards[dungeonid] = new LfgReward(questid[0], moneyreward[0], XPreward[0], questid[1], moneyreward[1], XPreward[1]);
count++;
}while(result->NextRow());
}
sLog.Notice("LfgMgr", "%u LFD rewards loaded.", count);
}
bool LfgMgr::AttemptLfgJoin(Player* pl, uint32 LfgDungeonId)
{
return false;
}
uint32 LfgMgr::GetPlayerLevelGroup(uint32 level)
{
if(level > 80)
return LFG_LEVELGROUP_80_UP;
else if(level == 80)
return LFG_LEVELGROUP_80;
else if(level >= 70)
return LFG_LEVELGROUP_70_UP;
else if(level >= 60)
return LFG_LEVELGROUP_60_UP;
else if(level >= 50)
return LFG_LEVELGROUP_50_UP;
else if(level >= 40)
return LFG_LEVELGROUP_40_UP;
else if(level >= 30)
return LFG_LEVELGROUP_30_UP;
else if(level >= 20)
return LFG_LEVELGROUP_20_UP;
else if(level >= 10)
return LFG_LEVELGROUP_10_UP;
return LFG_LEVELGROUP_NONE;
}
void LfgMgr::SetPlayerInLFGqueue(Player* pl,uint32 LfgDungeonId)
{
}
void LfgMgr::RemovePlayerFromLfgQueues(Player* pl)
{
}
void LfgMgr::RemovePlayerFromLfgQueue( Player* plr, uint32 LfgDungeonId )
{
}
void LfgMgr::UpdateLfgQueue(uint32 LfgDungeonId)
{
}
void LfgMgr::SendLfgList( Player* plr, uint32 Dungeon )
{
}
void LfgMgr::SetPlayerInLfmList(Player* pl, uint32 LfgDungeonId)
{
}
void LfgMgr::RemovePlayerFromLfmList(Player* pl, uint32 LfmDungeonId)
{
}
<file_sep>/src/ronin-world/Mainframe/Management/LfgMgr.h
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
enum LFGTypes
{
LFG_NONE = 0,
LFG_DUNGEON = 1,
LFG_RAID = 2,
LFG_QUEST = 3,
LFG_ZONE = 4,
LFG_HEROIC_DUNGEON = 5,
LFG_RANDOM = 6,
LFG_DAILY_DUNGEON = 7,
LFG_DAILY_HEROIC_DUNGEON = 8,
LFG_MAX_TYPES = 9
};
enum LFGLevelGroups
{
LFG_LEVELGROUP_NONE = 0,
LFG_LEVELGROUP_10_UP = 1,
LFG_LEVELGROUP_20_UP = 2,
LFG_LEVELGROUP_30_UP = 3,
LFG_LEVELGROUP_40_UP = 4,
LFG_LEVELGROUP_50_UP = 5,
LFG_LEVELGROUP_60_UP = 6,
LFG_LEVELGROUP_70_UP = 7,
LFG_LEVELGROUP_80 = 8,
LFG_LEVELGROUP_80_UP = 9,
NUM_LEVELGROUP = 10
};
struct LfgRewardInternal
{
uint32 QuestId;
uint32 MoneyReward;
uint32 XPReward;
};
/// Reward info
struct LfgReward
{
LfgReward(uint32 firstQuest = 0, uint32 firstVarMoney = 0, uint32 firstVarXp = 0, uint32 otherQuest = 0, uint32 otherVarMoney = 0, uint32 otherVarXp = 0)
{
reward[0].QuestId = firstQuest;
reward[0].MoneyReward = firstVarMoney;
reward[0].XPReward = firstVarXp;
reward[1].QuestId = otherQuest;
reward[1].MoneyReward = otherVarMoney;
reward[1].XPReward = otherVarXp;
}
LfgRewardInternal reward[2];
};
#define MAX_LFG_QUEUE_ID 3
#define LFG_MATCH_TIMEOUT 30 // in seconds
typedef std::set<uint32> DungeonSet;
class LfgMatch;
class LfgMgr : public Singleton < LfgMgr >
{
public:
typedef std::list<Player*> LfgPlayerList;
LfgMgr();
~LfgMgr();
void LoadRandomDungeonRewards();
LfgReward* GetLFGReward(uint32 dungeon) { return DungeonRewards[dungeon]; };
bool AttemptLfgJoin(Player* pl, uint32 LfgDungeonId);
void SetPlayerInLFGqueue(Player* pl,uint32 LfgDungeonId);
void SetPlayerInLfmList(Player* pl, uint32 LfgDungeonId);
void RemovePlayerFromLfgQueue(Player* pl,uint32 LfgDungeonId);
void RemovePlayerFromLfgQueues(Player* pl);
void RemovePlayerFromLfmList(Player* pl, uint32 LfmDungeonId);
void UpdateLfgQueue(uint32 LfgDungeonId);
void SendLfgList(Player* plr, uint32 Dungeon);
void EventMatchTimeout(LfgMatch * pMatch);
uint32 GetPlayerLevelGroup(uint32 level);
DungeonSet GetLevelSet(uint32 level) { return DungeonsByLevel[GetPlayerLevelGroup(level)]; };
int32 event_GetInstanceId() { return -1; }
protected:
uint32 MaxDungeonID;
DungeonSet DungeonsByLevel[NUM_LEVELGROUP];
std::map< uint32, LfgReward* > DungeonRewards;
std::map< uint32, LfgPlayerList > m_lookingForGroup, m_lookingForMore;
Mutex m_lock;
};
class LfgMatch
{
public:
std::set<Player* > PendingPlayers, AcceptedPlayers;
Mutex lock;
uint32 DungeonId;
Group * pGroup;
LfgMatch(uint32 did) : DungeonId(did),pGroup(NULL) { }
};
#define sLfgMgr LfgMgr::getSingleton()
<file_sep>/src/ronin-world/Objects/DynamicObject.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
DynamicObject::DynamicObject(uint32 high, uint32 low, uint32 fieldCount) : WorldObject(MAKE_NEW_GUID(low, 0, high), fieldCount)
{
SetTypeFlags(TYPEMASK_TYPE_DYNAMICOBJECT);
m_objType = TYPEID_DYNAMICOBJECT;
m_updateFlags |= UPDATEFLAG_STATIONARY_POS;
m_dynamicobjectPool = 0xFF;
m_aliveDuration = 0;
m_spellProto = NULL;
}
DynamicObject::~DynamicObject()
{
}
void DynamicObject::Init()
{
WorldObject::Init();
}
void DynamicObject::Destruct()
{
m_aliveDuration = 0;
m_spellProto = 0;
WorldObject::Destruct();
}
void DynamicObject::Create(WorldObject* caster, BaseSpell* pSpell, float x, float y, float z, int32 duration, float radius)
{
// Call the object create function
WorldObject::_Create(caster->GetMapId(), x, y, z, 0.0f);
casterLevel = caster->getLevel();
casterGuid = caster->GetGUID();
m_spellProto = pSpell->GetSpellProto();
m_position.ChangeCoords(x, y, z);
SetUInt32Value(OBJECT_FIELD_ENTRY, m_spellProto->Id);
SetUInt64Value(DYNAMICOBJECT_CASTER, casterGuid);
SetUInt32Value(DYNAMICOBJECT_BYTES, 0x01);
SetUInt32Value(DYNAMICOBJECT_SPELLID, m_spellProto->Id);
SetFloatValue(DYNAMICOBJECT_RADIUS, radius);
SetUInt32Value(DYNAMICOBJECT_CASTTIME, getMSTime());
m_aliveDuration = duration;
m_factionTemplate = caster->GetFactionTemplate();
PushToWorld(caster->GetMapInstance());
if(caster->IsUnit() && m_spellProto->isChanneledSpell())
{
castPtr<Unit>(caster)->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, GetGUID());
castPtr<Unit>(caster)->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellProto->Id);
}
UpdateTargets(0);
}
void DynamicObject::UpdateTargets(uint32 p_time)
{
Unit* u_caster = NULL;
if(GUID_HIPART(casterGuid) == HIGHGUID_TYPE_GAMEOBJECT)
{
GameObject* goCaster = GetMapInstance()->GetGameObject(casterGuid);
if(goCaster == NULL || !goCaster->IsInWorld())
m_aliveDuration = 0; // Set alive duration to 0
else if(goCaster->m_summoner)
u_caster = goCaster->m_summoner;
}
else
{
u_caster = GetMapInstance()->GetUnit(casterGuid);
if(u_caster == NULL || !u_caster->IsInWorld())
m_aliveDuration = 0; // Set alive duration to 0
}
// If we're a channelled spell, we are required to be the caster channel target
if(m_spellProto->IsSpellChannelSpell() && u_caster)
{
if(GetGUID() != u_caster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT))
m_aliveDuration = 0;
}
if(m_aliveDuration > 0)
{
if(m_aliveDuration < p_time)
m_aliveDuration = 0;
else m_aliveDuration -= p_time;
}
if(m_aliveDuration && u_caster)
{
Aura* pAura;
Unit* target;
float radius = GetFloatValue(DYNAMICOBJECT_RADIUS);
radius *= radius;
// loop the targets, check the range of all of them
DynamicObjectList::iterator jtr = targets.begin(), jtr2, jend = targets.end();
while(jtr != jend)
{
jtr2 = jtr;
++jtr;
target = GetMapInstance() ? GetMapInstance()->GetUnit(*jtr2) : NULL;
if(target == NULL || GetDistanceSq(target) > radius)
{
if(target)
target->RemoveAura(m_spellProto->Id);
targets.erase(jtr2);
}
}
}
else
{
// call remove here
Remove();
}
}
void DynamicObject::Remove()
{
if(IsInWorld())
{
// remove aura from all targets
for(std::set< uint64 >::iterator itr = targets.begin(); itr != targets.end(); ++itr)
if(Unit *target = m_mapInstance->GetUnit(*itr))
target->RemoveAura(m_spellProto->Id);
WorldPacket data(SMSG_DESTROY_OBJECT, 8);
data << GetGUID() << uint8(1);
SendMessageToSet(&data, true);
if(m_spellProto->IsSpellChannelSpell() && GUID_HIPART(casterGuid) != HIGHGUID_TYPE_GAMEOBJECT)
{
if(Unit* u_caster = GetMapInstance()->GetUnit(casterGuid))
{
if(GetGUID() == u_caster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT))
{
u_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
u_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0);
}
}
}
RemoveFromWorld();
}
Destruct();
}
<file_sep>/README.md
Project Ronin is a private source attempt at rewriting and cleaning up the internal systems of Ascent based Emulation.
Rather than continue to update this emulator privately, I've decided to dump my source back onto Github where anyone can use or contribute to it.
There is no database, sorry. Creating one from a mangos based cataclysm project is incredibly easy though, as the core has internal support for table based data modification.
Hardware this core's fulltilt mode is (over)optimized for:
Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz
12.0GB RAM
64-bit Operating System
Recent Contributors
Karasu(Thetruecrow)
Citric(Anon)
<file_sep>/src/ronin-world/Map System/Map Managers/InstanceManager.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2015-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
SERVER_DECL InstanceManager sInstanceMgr;
InstanceManager::InstanceManager()
{
}
InstanceManager::~InstanceManager()
{
}
void InstanceManager::Destruct()
{
}
void InstanceManager::Launch()
{
InstanceManagerSlave *worker = new InstanceManagerSlave();
// Only need one instance management thread to start with, dynamically allocate more if we need them.
ThreadPool.ExecuteTask(format("InstanceManager - Worker %u", 0+1).c_str(), worker);
}
void InstanceManager::Prepare()
{
// Nullify these counters here
m_creatureGUIDCounter = m_gameObjectGUIDCounter = 0;
// Create all non-instance type maps.
if( QueryResult *result = CharacterDatabase.Query( "SELECT MAX(id) FROM instances" ) )
{
m_instanceCounter = result->Fetch()[0].GetUInt32();
delete result;
} else m_instanceCounter = 0x3FF;
}
MapInstance *InstanceManager::GetInstanceForObject(WorldObject *obj)
{
Map *mapData = NULL;
MapInstance *ret = NULL;
instanceStorageLock.Acquire();
uint32 mapId = obj->GetMapId(), instanceId = obj->GetInstanceID();
if(instanceId != 0)
{
// Check to see if we have the instance ID in storage
if(mInstanceStorage.find(instanceId) != mInstanceStorage.end())
ret = mInstanceStorage.at(instanceId).second;
else ret = _LoadInstance(mapId, instanceId);
// If not, then we can return nothing
}
else if(obj->IsPlayer() && (mapData = GetMapData(mapId)))
{
Player *plr = castPtr<Player>(obj);
if(instanceId = castPtr<Player>(obj)->GetLinkedInstanceID(mapData->GetEntry()))
{
if(mInstanceStorage.find(instanceId) != mInstanceStorage.end())
ret = mInstanceStorage.at(instanceId).second;
else ret = _LoadInstance(mapId, instanceId);
}
else if(plr->CanCreateNewDungeon(mapId))
{
// Instance ID generation occurs inside mutex
counterLock.Acquire();
uint32 instanceId = ++m_instanceCounter;
counterLock.Release();
ret = new MapInstance(mapData, mapId, instanceId);
_AddInstance(instanceId, ret);
}
}
instanceStorageLock.Release();
return ret;
}
uint32 InstanceManager::PreTeleportInstanceCheck(uint64 guid, uint32 mapId, uint32 instanceId, bool canCreate)
{
Map *mapData = NULL;
uint32 ret = INSTANCE_OK;
instanceStorageLock.Acquire();
if(instanceId != 0)
{
// Instance exists, run checks before we return the OK
if(mInstanceStorage.find(instanceId) != mInstanceStorage.end())
{
MapInstance *instance = mInstanceStorage.at(instanceId).second;
if(instance->IsClosing())
ret = INSTANCE_ABORT_INSTANCE_CLOSING;
else if(instance->IsFull())
ret = INSTANCE_ABORT_FULL;
else if(instance->CheckCombatStatus())
ret = INSTANCE_ABORT_ENCOUNTER;
// else ret = instance_ok and we can enter our existing instance
} // Check instance data for load preparation, if no data abort
else if(m_instanceData.find(instanceId) == m_instanceData.end())
ret = INSTANCE_ABORT_NOT_FOUND;
else // We have instance data, run checks on if we can access it
{
InstanceData *data = m_instanceData.at(instanceId);
if(data->GetMapId() != mapId) // Check if we're loading into a different instance to prevent abuse
ret = INSTANCE_ABORT_NOT_FOUND;
// Check if we're in the list of allowed players to load in(we need to have entered normally)
/*if(data->PlayerBlocked(plr) || data->IsExpired())
ret = INSTANCE_ABORT_NOT_FOUND;*/
}
} else if(canCreate && (mapData = GetMapData(mapId)))
ret = INSTANCE_ABORT_CREATE_NEW_INSTANCE;
else ret = canCreate ? INSTANCE_ABORT_NOT_FOUND : INSTANCE_ABORT_TOO_MANY;
instanceStorageLock.Release();
return ret;
}
void InstanceManager::_AddInstance(uint32 instanceId, MapInstance *instance)
{
MapInstanceContainer *container = new MapInstanceContainer(instance);
// Quick store our container and instance since we've allocated them to prevent double allocation
mInstanceStorage.insert(std::make_pair(instanceId, std::make_pair(container, instance)));
// Preload instance data before mapping
instance->Preload();
// Time for push to pool
instancePoolLock.Acquire();
// Get our timer inside the lock so that everything occurs in the same timeframe
uint32 msTime = getMSTime();
instance->Init(msTime);
container->ResetTimer(msTime);
mInstancePool.push_back(container);
instancePoolLock.Release();
}
MapInstance *InstanceManager::_LoadInstance(uint32 mapId, uint32 instanceId)
{
MapInstance *ret = NULL;
if(Map *mapData = GetMapData(mapId))
{
ret = new MapInstance(mapData, mapId, instanceId);
//ret->LoadInstanceData();
_AddInstance(instanceId, ret);
}
return ret;
}
void InstanceManager::HandleUpdateRequests(InstanceManagerSlave *slaveThis)
{
uint32 diff = 0, msTimer = 0;
MapInstanceContainer *container = NULL;
while(slaveThis->SetThreadState(THREADSTATE_BUSY))
{
msTimer = getMSTime();
instancePoolLock.Acquire();
if(!mInstancePool.empty())
{
container = mInstancePool.front();
// Test if the update timeout has passed and grab our map difference
if(container->Validate(msTimer, diff))
mInstancePool.pop_front();
else container = NULL;
}
instancePoolLock.Release();
if(container != NULL)
{
if(MapInstance *instance = container->Get())
{
// Process all pending inputs in sequence
instance->_ProcessInputQueue();
if(!slaveThis->SetThreadState(THREADSTATE_BUSY))
break;
// Perform all player updates in sequence
instance->_PerformPlayerUpdates(msTimer, diff);
if(!slaveThis->SetThreadState(THREADSTATE_BUSY))
break;
// Perform all dynamic object updates in sequence
instance->_PerformDynamicObjectUpdates(msTimer, diff);
if(!slaveThis->SetThreadState(THREADSTATE_BUSY))
break;
// Perform all creature updates in sequence
instance->_PerformCreatureUpdates(msTimer, diff);
if(!slaveThis->SetThreadState(THREADSTATE_BUSY))
break;
// Perform all object updates in sequence
instance->_PerformObjectUpdates(msTimer, diff);
if(!slaveThis->SetThreadState(THREADSTATE_BUSY))
break;
// Perform all session updates in sequence
instance->_PerformSessionUpdates();
if(!slaveThis->SetThreadState(THREADSTATE_BUSY))
break;
// Perform all pending object updates in sequence
instance->_PerformPendingUpdates();
if(!slaveThis->SetThreadState(THREADSTATE_BUSY))
break;
// Reset the last update timer for next update processing
container->ResetTimer(msTimer);
// Readd the instance to the update pool
instancePoolLock.Acquire();
mInstancePool.push_back(container);
instancePoolLock.Release();
} else delete container; // Clean up the empty container
}
if(!slaveThis->SetThreadState(THREADSTATE_SLEEPING))
break;
Sleep(25);
}
}
<file_sep>/src/ronin-world/Map System/Map Interface/MapCell.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
//
// MapCell.cpp
//
#include "StdAfx.h"
MapCell::MapCell()
{
_forcedActive = false;
}
MapCell::~MapCell()
{
UnloadCellData(true);
}
void MapCell::Init(uint32 x, uint32 y, uint32 mapid, MapInstance* instance)
{
_mapData = instance->GetBaseMap();
_instance = instance;
_active = false;
_loaded = false;
_x = x;
_y = y;
_unloadpending=false;
}
void MapCell::AddObject(WorldObject* obj)
{
if(obj->IsPlayer())
m_playerSet[obj->GetGUID()] = obj;
else
{
m_nonPlayerSet[obj->GetGUID()] = obj;
if(obj->IsCreature())
m_creatureSet[obj->GetGUID()] = obj;
else if(obj->IsGameObject())
m_gameObjectSet[obj->GetGUID()] = obj;
}
}
void MapCell::RemoveObject(WorldObject* obj)
{
m_playerSet.erase(obj->GetGUID());
m_nonPlayerSet.erase(obj->GetGUID());
m_creatureSet.erase(obj->GetGUID());
m_gameObjectSet.erase(obj->GetGUID());
}
WorldObject *MapCell::FindObject(WoWGuid guid)
{
MapCell::CellObjectMap::iterator itr;
if((itr = m_playerSet.find(guid)) != m_playerSet.end() || (itr = m_nonPlayerSet.find(guid)) != m_nonPlayerSet.end())
return itr->second;
return NULL;
}
void MapCell::ProcessObjectSets(WorldObject *obj, ObjectProcessCallback *callback, uint32 objectMask)
{
WorldObject *curObj;
if(objectMask == 0)
{
for(MapCell::CellObjectMap::iterator itr = m_nonPlayerSet.begin(); itr != m_nonPlayerSet.end(); itr++)
if((curObj = itr->second) && obj != curObj)
(*callback)(obj, curObj);
for(MapCell::CellObjectMap::iterator itr = m_playerSet.begin(); itr != m_playerSet.end(); itr++)
if((curObj = itr->second) && obj != curObj)
(*callback)(obj, curObj);
}
else
{
if(objectMask & TYPEMASK_TYPE_UNIT)
{
for(MapCell::CellObjectMap::iterator itr = m_creatureSet.begin(); itr != m_creatureSet.end(); itr++)
if((curObj = itr->second) && obj != curObj)
(*callback)(obj, curObj);
}
if(objectMask & TYPEMASK_TYPE_PLAYER)
{
for(MapCell::CellObjectMap::iterator itr = m_playerSet.begin(); itr != m_playerSet.end(); itr++)
if((curObj = itr->second) && obj != curObj)
(*callback)(obj, curObj);
}
if(objectMask & TYPEMASK_TYPE_GAMEOBJECT)
{
for(MapCell::CellObjectMap::iterator itr = m_gameObjectSet.begin(); itr != m_gameObjectSet.end(); itr++)
if((curObj = itr->second) && obj != curObj)
(*callback)(obj, curObj);
}
}
}
void MapCell::SetActivity(bool state)
{
uint32 x = _x/8, y = _y/8;
if(state && _unloadpending)
CancelPendingUnload();
else if(!state && !_unloadpending)
QueueUnloadPending();
_active = state;
}
uint32 MapCell::LoadCellData(CellSpawns * sp)
{
if(_loaded == true)
return 0;
// start calldown for cell map loading
_mapData->CellLoaded(_x, _y);
_loaded = true;
// check if we have a spawn map, otherwise no use continuing
if(sp == NULL)
return 0;
uint32 loadCount = 0, mapId = _instance->GetMapId();
//MapInstance *pInstance = NULL;//_instance->IsInstance() ? castPtr<InstanceMgr>(_instance) : NULL;
if(sp->CreatureSpawns.size())//got creatures
{
for(CreatureSpawnArray::iterator i=sp->CreatureSpawns.begin();i!=sp->CreatureSpawns.end();++i)
{
CreatureSpawn *spawn = *i;
if(Creature *c = _instance->CreateCreature(spawn->guid))
{
c->Load(mapId, spawn->x, spawn->y, spawn->z, spawn->o, _instance->iInstanceMode, spawn);
c->SetInstanceID(_instance->GetInstanceID());
if(!c->CanAddToWorld())
{
c->Destruct();
continue;
}
if(_instance->IsCreaturePoolUpdating())
_instance->AddObject(c);
else c->PushToWorld(_instance);
loadCount++;
}
}
}
if(sp->GameObjectSpawns.size())//got GOs
{
for(GameObjectSpawnArray::iterator i = sp->GameObjectSpawns.begin(); i != sp->GameObjectSpawns.end(); i++)
{
GameObjectSpawn *spawn = *i;
if(GameObject *go = _instance->CreateGameObject(spawn->guid))
{
go->Load(mapId, spawn->x, spawn->y, spawn->z, 0.f, spawn->rX, spawn->rY, spawn->rZ, spawn->rAngle, spawn);
go->SetInstanceID(_instance->GetInstanceID());
if(_instance->IsGameObjectPoolUpdating())
_instance->AddObject(go);
else go->PushToWorld(_instance);
loadCount++;
}
}
}
return loadCount;
}
void MapCell::UnloadCellData(bool preDestruction)
{
if(_loaded == false)
return;
_loaded = false;
std::set<WorldObject*> deletionSet;
//This time it's simpler! We just remove everything :)
for(MapCell::CellObjectMap::iterator itr = m_nonPlayerSet.begin(); itr != m_nonPlayerSet.end(); itr++)
{
WorldObject *obj = itr->second;
if(obj == NULL)
continue;
if( !preDestruction && _unloadpending )
{
if(obj->GetHighGUID() == HIGHGUID_TYPE_TRANSPORTER)
continue;
if(obj->GetTypeId() == TYPEID_CORPSE && obj->GetUInt32Value(CORPSE_FIELD_OWNER) != 0)
continue;
}
if( obj->IsInWorld())
obj->RemoveFromWorld();
deletionSet.insert(obj);
}
m_nonPlayerSet.clear();
while(deletionSet.size())
{
WorldObject *obj = *deletionSet.begin();
deletionSet.erase(deletionSet.begin());
obj->Destruct();
}
// Start calldown for cell map unloading
_mapData->CellUnloaded(_x, _y);
}
void MapCell::QueueUnloadPending()
{
if(_unloadpending)
return;
_unloadpending = true;
sLog.Debug("MapCell", "Queueing pending unload of cell %u %u", _x, _y);
}
void MapCell::CancelPendingUnload()
{
sLog.Debug("MapCell", "Cancelling pending unload of cell %u %u", _x, _y);
if(!_unloadpending)
return;
}
void MapCell::Unload()
{
if(_active)
return;
sLog.Debug("MapCell", "Unloading cell %u %u", _x, _y);
UnloadCellData(false);
_unloadpending = false;
}
<file_sep>/src/ronin-world/Spell/SpellTarget.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
uint32 Spell::GetTargetType(uint32 implicittarget, uint32 i)
{
uint32 type = m_implicitTargetFlags[implicittarget];
//CHAIN SPELLS ALWAYS CHAIN!
uint32 jumps = m_spellInfo->EffectChainTarget[i];
_unitCaster->SM_FIValue(SMT_JUMP_REDUCE, (int32*)&jumps, m_spellInfo->SpellGroupType);
if(jumps != 0)
type |= SPELL_TARGET_AREA_CHAIN;
return type;
}
void Spell::FillTargetMap(bool fromDelayed)
{
bool ignoreAOE = m_isDelayedAOEMissile && fromDelayed == false;
uint32 targetTypes[3] = {SPELL_TARGET_NOT_IMPLEMENTED, SPELL_TARGET_NOT_IMPLEMENTED, SPELL_TARGET_NOT_IMPLEMENTED};
// Set destination position for target types when we have target pos flags on current target
for(uint32 i = 0; i < 3; i++)
{
if(m_spellInfo->Effect[i] == 0)
continue;
// Fill from A regardless
targetTypes[i] = GetTargetType(m_spellInfo->EffectImplicitTargetA[i], i);
//never get info from B if it is 0 :P
if(m_spellInfo->EffectImplicitTargetB[i] != 0)
targetTypes[i] |= GetTargetType(m_spellInfo->EffectImplicitTargetB[i], i);
if(targetTypes[i] & SPELL_TARGET_AREA_CURTARGET)
{
//this just forces dest as the targets location :P
if(WorldObject* target = _unitCaster->GetInRangeObject(m_targets.m_unitTarget))
{
m_targets.m_targetMask = TARGET_FLAG_DEST_LOCATION;
m_targets.m_dest = target->GetPosition();
break;
}
}
}
// Fill out our different targets for spell effects
for(uint8 i = 0; i < 3; i++)
{
float radius = GetRadius(i);
if(targetTypes[i] & SPELL_TARGET_NOT_IMPLEMENTED)
continue;
if(targetTypes[i] & SPELL_TARGET_NO_OBJECT) //summon spells that appear infront of caster
{
HandleTargetNoObject();
continue;
}
bool inWorld = _unitCaster->IsInWorld(); //always add this guy :P
if(inWorld && !(targetTypes[i] & (SPELL_TARGET_AREA | SPELL_TARGET_AREA_SELF | SPELL_TARGET_AREA_CURTARGET | SPELL_TARGET_AREA_CONE | SPELL_TARGET_OBJECT_SELF | SPELL_TARGET_OBJECT_PETOWNER)))
if(Unit* target = _unitCaster->GetInRangeObject<Unit>(m_targets.m_unitTarget))
AddTarget(i, targetTypes[i], target);
// We can always push self to our target map
if(targetTypes[i] & SPELL_TARGET_OBJECT_SELF)
AddTarget(i, targetTypes[i], _unitCaster);
if (inWorld && (targetTypes[i] & SPELL_TARGET_OBJECT_CURTOTEMS))
{
std::vector<Creature*> m_totemList;
_unitCaster->FillSummonList(m_totemList, SUMMON_TYPE_TOTEM);
for(std::vector<Creature*>::iterator itr = m_totemList.begin(); itr != m_totemList.end(); itr++)
AddTarget(i, targetTypes[i], *itr);
}
if(radius && inWorld)
{ // These require that we're in world with people around us
if(ignoreAOE == false && (targetTypes[i] & SPELL_TARGET_AREA)) // targetted aoe
AddAOETargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets);
if((targetTypes[i] & SPELL_TARGET_AREA_SELF)) // targetted aoe near us
AddAOETargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets);
//targets party, not raid
if((targetTypes[i] & SPELL_TARGET_AREA_PARTY) && !(targetTypes[i] & SPELL_TARGET_AREA_RAID))
{
if(!_unitCaster->IsPlayer() && !(_unitCaster->IsCreature() || _unitCaster->IsTotem()))
AddAOETargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets); //npcs
else AddPartyTargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets); //players/pets/totems
}
if(targetTypes[i] & SPELL_TARGET_AREA_RAID)
{
if(!_unitCaster->IsPlayer() && !(_unitCaster->IsCreature() || _unitCaster->IsTotem()))
AddAOETargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets); //npcs
else AddRaidTargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets, (targetTypes[i] & SPELL_TARGET_AREA_PARTY) ? true : false); //players/pets/totems
}
if(targetTypes[i] & SPELL_TARGET_AREA_CHAIN)
AddChainTargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets);
//target cone
if(targetTypes[i] & SPELL_TARGET_AREA_CONE)
AddConeTargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets);
if(targetTypes[i] & SPELL_TARGET_OBJECT_SCRIPTED)
AddScriptedOrSpellFocusTargets(i, targetTypes[i], radius, m_spellInfo->MaxTargets);
}
// Allow auto self target, especially when map is empty
if(!m_targets.hasDestination() && (m_effectTargetMaps[i].empty() && (m_targets.m_unitTarget.empty() || m_targets.m_unitTarget == _unitCaster->GetGUID())))
AddTarget(i, SPELL_TARGET_NONE, _unitCaster);
}
}
void Spell::HandleTargetNoObject()
{
float dist = 3;
float srcX = _unitCaster->GetPositionX(), newx = srcX + cosf(_unitCaster->GetOrientation()) * dist;
float srcY = _unitCaster->GetPositionY(), newy = srcY + sinf(_unitCaster->GetOrientation()) * dist;
float srcZ = _unitCaster->GetPositionZ(), newz = _unitCaster->GetMapInstance()->GetWalkableHeight(_unitCaster, newx, newy, srcZ);
//if not in line of sight, or too far away we summon inside caster
if(fabs(newz - srcZ) > 10 || !sVMapInterface.CheckLOS(_unitCaster->GetMapId(), _unitCaster->GetInstanceID(), _unitCaster->GetPhaseMask(), srcX, srcY, srcZ, newx, newy, newz + 2))
newx = srcX, newy = srcY, newz = srcZ;
m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
m_targets.m_dest.ChangeCoords(newx, newy, newz);
}
bool Spell::AddTarget(uint32 i, uint32 TargetType, WorldObject* obj)
{
if(obj == NULL || (obj != _unitCaster && !obj->IsInWorld()))
return false;
//GO target, not item
if((TargetType & SPELL_TARGET_REQUIRE_GAMEOBJECT) && !(TargetType & SPELL_TARGET_REQUIRE_ITEM) && !obj->IsGameObject())
return false;
//target go, not able to target go
if(obj->IsGameObject() && !(TargetType & SPELL_TARGET_OBJECT_SCRIPTED) && !(TargetType & SPELL_TARGET_REQUIRE_GAMEOBJECT) && !m_triggeredSpell)
return false;
//target item, not able to target item
if(obj->IsItem() && !(TargetType & SPELL_TARGET_REQUIRE_ITEM) && !m_triggeredSpell)
return false;
if(_unitCaster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IGNORE_PC) && (obj->IsPlayer() || _unitCaster->IsPlayer()))
return false;
if(TargetType & SPELL_TARGET_REQUIRE_FRIENDLY && !sFactionSystem.isFriendly(_unitCaster, obj))
return false;
if(TargetType & SPELL_TARGET_REQUIRE_ATTACKABLE && !sFactionSystem.isAttackable(_unitCaster, obj))
return false;
if(TargetType & SPELL_TARGET_OBJECT_TARCLASS)
{
WorldObject* originaltarget = _unitCaster->GetInRangeObject(m_targets.m_unitTarget);
if(originaltarget == NULL || (originaltarget->IsPlayer() && obj->IsPlayer() && castPtr<Player>(originaltarget)->getClass() != castPtr<Player>(obj)->getClass())
|| (originaltarget->IsPlayer() && !obj->IsPlayer()) || (!originaltarget->IsPlayer() && obj->IsPlayer()))
return false;
}
if(TargetType & (SPELL_TARGET_AREA | SPELL_TARGET_AREA_SELF | SPELL_TARGET_AREA_CURTARGET | SPELL_TARGET_AREA_CONE | SPELL_TARGET_AREA_PARTY | SPELL_TARGET_AREA_RAID)
&& ((obj->IsUnit() && !castPtr<Unit>(obj)->isAlive()) || (obj->IsCreature() && obj->IsTotem())))
return false;
_AddTarget(obj, i);
//final checks, require line of sight unless range/radius is 50000 yards
SpellRangeEntry* r = dbcSpellRange.LookupEntry(m_spellInfo->rangeIndex);
if(sWorld.Collision && r->maxRangeHostile < 50000 && GetRadius(i) < 50000 && !obj->IsItem())
{
float x = _unitCaster->GetPositionX(), y = _unitCaster->GetPositionY(), z = _unitCaster->GetPositionZ() + 0.5f;
//are we using a different location?
if(TargetType & SPELL_TARGET_AREA)
{
x = m_targets.m_dest.x;
y = m_targets.m_dest.y;
z = m_targets.m_dest.z;
}
else if(TargetType & SPELL_TARGET_AREA_CHAIN)
{
//TODO: Support
}
if(!sVMapInterface.CheckLOS(_unitCaster->GetMapId(), _unitCaster->GetInstanceID(), _unitCaster->GetPhaseMask(), x, y, z + 2, obj->GetPositionX(), obj->GetPositionY(), obj->GetPositionZ() + 2))
return false;
}
return true;
}
bool Spell::GenerateTargets(SpellCastTargets *t)
{
if(!_unitCaster->IsInWorld())
return false;
bool result = false;
for(uint32 i = 0; i < 3; ++i)
{
if(m_spellInfo->Effect[i] == 0)
continue;
uint32 TargetType = GetTargetType(m_spellInfo->EffectImplicitTargetA[i], i);
//never get info from B if it is 0 :P
if(m_spellInfo->EffectImplicitTargetB[i] != 0)
TargetType |= GetTargetType(m_spellInfo->EffectImplicitTargetB[i], i);
if(TargetType & (SPELL_TARGET_OBJECT_SELF | SPELL_TARGET_AREA_PARTY | SPELL_TARGET_AREA_RAID))
{
t->m_targetMask |= TARGET_FLAG_UNIT;
t->m_unitTarget = _unitCaster->GetGUID();
result = true;
}
if(TargetType & SPELL_TARGET_NO_OBJECT)
{
t->m_targetMask = TARGET_FLAG_SELF;
t->m_unitTarget = _unitCaster->GetGUID();
result = true;
}
if(!(TargetType & (SPELL_TARGET_AREA | SPELL_TARGET_AREA_SELF | SPELL_TARGET_AREA_CURTARGET | SPELL_TARGET_AREA_CONE)))
{
if(TargetType & SPELL_TARGET_ANY_OBJECT)
{
if(_unitCaster->GetUInt64Value(UNIT_FIELD_TARGET))
{
//generate targets for things like arcane missiles trigger, tame pet, etc
if(WorldObject* target = _unitCaster->GetInRangeObject<WorldObject>(_unitCaster->GetUInt64Value(UNIT_FIELD_TARGET)))
{
if(target->IsUnit())
{
t->m_targetMask |= TARGET_FLAG_UNIT;
t->m_unitTarget = target->GetGUID();
result = true;
}
else if(target->IsGameObject())
{
t->m_targetMask |= TARGET_FLAG_OBJECT;
t->m_unitTarget = target->GetGUID();
result = true;
}
}
result = true;
}
}
if(TargetType & SPELL_TARGET_REQUIRE_ATTACKABLE)
{
if(_unitCaster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT))
{
//generate targets for things like arcane missiles trigger, tame pet, etc
if(WorldObject* target = _unitCaster->GetInRangeObject<WorldObject>(_unitCaster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT)))
{
if(target->IsUnit())
{
t->m_targetMask |= TARGET_FLAG_UNIT;
t->m_unitTarget = target->GetGUID();
result = true;
}
else if(target->IsGameObject())
{
t->m_targetMask |= TARGET_FLAG_OBJECT;
t->m_unitTarget = target->GetGUID();
result = true;
}
}
}
else if(_unitCaster->GetUInt64Value(UNIT_FIELD_TARGET))
{
//generate targets for things like arcane missiles trigger, tame pet, etc
if(WorldObject* target = _unitCaster->GetInRangeObject<WorldObject>(_unitCaster->GetUInt64Value(UNIT_FIELD_TARGET)))
{
if(target->IsUnit())
{
t->m_targetMask |= TARGET_FLAG_UNIT;
t->m_unitTarget = target->GetGUID();
result = true;
}
else if(target->IsGameObject())
{
t->m_targetMask |= TARGET_FLAG_OBJECT;
t->m_unitTarget = target->GetGUID();
result = true;
}
}
result = true;
}
else if(_unitCaster->IsCreature() && _unitCaster->IsTotem())
{
if(Unit* target = _unitCaster->GetInRangeObject<Unit>(GetSinglePossibleEnemy(i)))
{
t->m_targetMask |= TARGET_FLAG_UNIT;
t->m_unitTarget = target->GetGUID();
}
}
}
if(TargetType & SPELL_TARGET_REQUIRE_FRIENDLY)
{
result = true;
t->m_targetMask |= TARGET_FLAG_UNIT;
if(Unit* target = _unitCaster->GetInRangeObject<Unit>(GetSinglePossibleFriend(i)))
t->m_unitTarget = target->GetGUID();
else t->m_unitTarget = _unitCaster->GetGUID();
}
}
if(TargetType & SPELL_TARGET_AREA_RANDOM)
{
//we always use radius(0) for some reason
uint8 attempts = 0;
do
{
//prevent deadlock
++attempts;
if(attempts > 10)
return false;
float r = RandomFloat(GetRadius(0));
float ang = RandomFloat(M_PI * 2);
t->m_dest.x = _unitCaster->GetPositionX() + (cosf(ang) * r);
t->m_dest.y = _unitCaster->GetPositionY() + (sinf(ang) * r);
t->m_dest.z = _unitCaster->GetMapInstance()->GetWalkableHeight(_unitCaster, t->m_dest.x, t->m_dest.y, _unitCaster->GetPositionZ() + 2.0f);
t->m_targetMask = TARGET_FLAG_DEST_LOCATION;
}
while(sWorld.Collision && !sVMapInterface.CheckLOS(_unitCaster->GetMapId(), _unitCaster->GetInstanceID(), _unitCaster->GetPhaseMask(), _unitCaster->GetPositionX(), _unitCaster->GetPositionY(), _unitCaster->GetPositionZ(), t->m_dest.x, t->m_dest.y, t->m_dest.z));
result = true;
}
else if(TargetType & SPELL_TARGET_AREA) //targetted aoe
{
if(TargetType & SPELL_TARGET_REQUIRE_FRIENDLY)
{
t->m_targetMask |= TARGET_FLAG_DEST_LOCATION;
t->m_dest = _unitCaster->GetPosition();
result = true;
}
else if(_unitCaster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT)) //spells like blizzard, rain of fire
{
if(WorldObject* target = _unitCaster->GetInRangeObject<WorldObject>(_unitCaster->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT)))
{
t->m_targetMask |= TARGET_FLAG_DEST_LOCATION | TARGET_FLAG_UNIT;
t->m_unitTarget = target->GetGUID();
t->m_dest = target->GetPosition();
}
result = true;
}
}
else if(TargetType & SPELL_TARGET_AREA_SELF)
{
t->m_targetMask |= TARGET_FLAG_SOURCE_LOCATION;
t->m_dest = t->m_src = _unitCaster->GetPosition();
result = true;
}
if(TargetType & SPELL_TARGET_AREA_CHAIN && !(TargetType & SPELL_TARGET_REQUIRE_ATTACKABLE))
{
t->m_targetMask |= TARGET_FLAG_UNIT;
t->m_unitTarget = _unitCaster->GetGUID();
result = true;
}
}
return result;
}
void Spell::FillSpecifiedTargetsInArea( float srcx, float srcy, float srcz, uint32 ind, uint32 specification )
{
FillSpecifiedTargetsInArea( ind, srcx, srcy, srcz, GetRadius(ind), specification );
}
// for the moment we do invisible targets
void Spell::FillSpecifiedTargetsInArea(uint32 i,float srcx,float srcy,float srcz, float range, uint32 specification)
{
float r = range * range;
WorldObject *wObj = NULL;
/*for(WorldObject::InRangeHashMap::iterator itr = m_caster->GetInRangeMapBegin(); itr != m_caster->GetInRangeMapEnd(); itr++ )
{
if((wObj = itr->second) == NULL)
continue;
if(wObj->IsUnit())
{
if(!castPtr<Unit>(wObj)->isAlive())
continue;
if(m_spellInfo->TargetCreatureType)
{
Unit* Target = castPtr<Unit>(wObj);
if(uint32 creatureType = Target->GetCreatureType())
{
if(((1<<(creatureType-1)) & m_spellInfo->TargetCreatureType) == 0)
continue;
} else continue;
}
} else if(wObj->IsGameObject() && !CanEffectTargetGameObjects(i))
continue;
if(!IsInrange(srcx, srcy, srcz, wObj, r))
continue;
if( !wObj->IsUnit() || sFactionSystem.CanEitherUnitAttack(castPtr<Unit>(m_caster), castPtr<Unit>(wObj), !m_spellInfo->isSpellStealthTargetCapable()) )
_AddTarget(wObj, i);
if(m_spellInfo->MaxTargets && m_effectTargetMaps[i].size() >= m_spellInfo->MaxTargets)
break;
}*/
}
void Spell::FillAllTargetsInArea(LocationVector & location,uint32 ind)
{
FillAllTargetsInArea(ind,location.x,location.y,location.z,GetRadius(ind));
}
void Spell::FillAllTargetsInArea(float srcx,float srcy,float srcz,uint32 ind)
{
FillAllTargetsInArea(ind,srcx,srcy,srcz,GetRadius(ind));
}
/// We fill all the targets in the area, including the stealth ed one's
void Spell::FillAllTargetsInArea(uint32 i,float srcx,float srcy,float srcz, float range, bool includegameobjects)
{
float r = range*range;
uint32 placeholder = 0;
WorldObject *wObj = NULL;
std::vector<WorldObject*> ChainTargetContainer;
bool canAffectGameObjects = CanEffectTargetGameObjects(i);
/*for(WorldObject::InRangeHashMap::iterator itr = m_caster->GetInRangeMapBegin(); itr != m_caster->GetInRangeMapEnd(); itr++ )
{
if((wObj = itr->second) == NULL)
continue;
if(wObj->IsUnit())
{
Unit *uTarget = castPtr<Unit>(wObj);
if(!uTarget->isAlive())
continue;
if( m_spellInfo->TargetCreatureType && !(m_spellInfo->TargetCreatureType & (1<<(uTarget->GetCreatureType()-1))))
continue;
} else if(wObj->IsGameObject() && !canAffectGameObjects)
continue;
if(!IsInrange(srcx, srcy, srcz, wObj, r))
continue;
if(castPtr<Unit>(m_caster) && wObj->IsUnit() )
{
if( sFactionSystem.CanEitherUnitAttack(castPtr<Unit>(m_caster), castPtr<Unit>(wObj), !m_spellInfo->isSpellStealthTargetCapable()) )
{
ChainTargetContainer.push_back(wObj);
placeholder++;
}
} else ChainTargetContainer.push_back(wObj);
}*/
if(m_spellInfo->MaxTargets)
{
WorldObject* chaintarget = NULL;
uint32 targetCount = m_spellInfo->MaxTargets;
while(targetCount && ChainTargetContainer.size())
{
placeholder = (rand()%ChainTargetContainer.size());
chaintarget = ChainTargetContainer.at(placeholder);
if(chaintarget == NULL)
continue;
if(chaintarget->IsUnit())
_AddTarget(castPtr<Unit>(chaintarget), i);
else _AddTarget(chaintarget, i);
ChainTargetContainer.erase(ChainTargetContainer.begin()+placeholder);
targetCount--;
}
}
else
{
for(std::vector<WorldObject*>::iterator itr = ChainTargetContainer.begin(); itr != ChainTargetContainer.end(); itr++)
{
if((*itr)->IsUnit())
_AddTarget(castPtr<Unit>(*itr), i);
else _AddTarget(*itr, i);
}
}
ChainTargetContainer.clear();
}
// We fill all the targets in the area, including the stealthed one's
void Spell::FillAllFriendlyInArea( uint32 i, float srcx, float srcy, float srcz, float range )
{
float r = range*range;
WorldObject *wObj = NULL;
bool canAffectGameObjects = CanEffectTargetGameObjects(i);
/*for(WorldObject::InRangeHashMap::iterator itr = m_caster->GetInRangeMapBegin(); itr != m_caster->GetInRangeMapEnd(); itr++ )
{
if((wObj = itr->second) == NULL)
continue;
if(wObj->IsUnit())
{
Unit *uTarget = castPtr<Unit>(wObj);
if( !uTarget->isAlive() || (uTarget->IsCreature() && castPtr<Creature>(uTarget)->IsTotem()))
continue;
if( m_spellInfo->TargetCreatureType && !(m_spellInfo->TargetCreatureType & (1<<(uTarget->GetCreatureType()-1))))
continue;
} else if(wObj->IsGameObject() && !canAffectGameObjects)
continue;
if( IsInrange( srcx, srcy, srcz, wObj, r ))
{
if(castPtr<Unit>(m_caster) && wObj->IsUnit() )
{
if( sFactionSystem.CanEitherUnitAttack(castPtr<Unit>(m_caster), castPtr<Unit>(wObj), !m_spellInfo->isSpellStealthTargetCapable()) )
_AddTarget(castPtr<Unit>(wObj), i);
}
else _AddTarget(wObj, i);
if( m_spellInfo->MaxTargets && m_effectTargetMaps[i].size() >= m_spellInfo->MaxTargets )
break;
}
}*/
}
/// We fill all the gameobject targets in the area
void Spell::FillAllGameObjectTargetsInArea(uint32 i,float srcx,float srcy,float srcz, float range)
{
float r = range*range;
/*for(WorldObject::InRangeArray::iterator itr = m_caster->GetInRangeGameObjectSetBegin(); itr != m_caster->GetInRangeGameObjectSetEnd(); itr++ )
{
if(GameObject *gObj = m_caster->GetInRangeObject<GameObject>(*itr))
{
if(!IsInrange( srcx, srcy, srcz, gObj, r ))
continue;
_AddTarget(gObj, i);
}
}*/
}
uint64 Spell::GetSinglePossibleEnemy(uint32 i,float prange)
{
float rMin = m_spellInfo->minRange[0], rMax = prange;
if(rMax == 0.f)
{
rMax = m_spellInfo->maxRange[0];
if( m_spellInfo->SpellGroupType)
{
_unitCaster->SM_FFValue(SMT_RADIUS,&rMax,m_spellInfo->SpellGroupType);
_unitCaster->SM_PFValue(SMT_RADIUS,&rMax,m_spellInfo->SpellGroupType);
}
}
float srcx = _unitCaster->GetPositionX(), srcy = _unitCaster->GetPositionY(), srcz = _unitCaster->GetPositionZ();
/*for( WorldObject::InRangeArray::iterator itr = m_caster->GetInRangeUnitSetBegin(); itr != m_caster->GetInRangeUnitSetEnd(); itr++ )
{
Unit *unit = m_caster->GetInRangeObject<Unit>(*itr);
if(!unit->isAlive())
continue;
if( m_spellInfo->TargetCreatureType && (!(1<<(unit->GetCreatureType()-1) & m_spellInfo->TargetCreatureType)))
continue;
if(!IsInrange(srcx,srcy,srcz, unit, rMax, rMin))
continue;
if(!sFactionSystem.isAttackable(m_caster, unit,!m_spellInfo->isSpellStealthTargetCapable()))
continue;
if(_DidHit(unit) != SPELL_DID_HIT_SUCCESS)
continue;
return unit->GetGUID();
}*/
return 0;
}
uint64 Spell::GetSinglePossibleFriend(uint32 i,float prange)
{
float rMin = m_spellInfo->minRange[1], rMax = prange;
if(rMax == 0.f)
{
rMax = m_spellInfo->maxRange[1];
if( m_spellInfo->SpellGroupType)
{
_unitCaster->SM_FFValue(SMT_RADIUS,&rMax,m_spellInfo->SpellGroupType);
_unitCaster->SM_PFValue(SMT_RADIUS,&rMax,m_spellInfo->SpellGroupType);
}
}
float srcx = _unitCaster->GetPositionX(), srcy = _unitCaster->GetPositionY(), srcz = _unitCaster->GetPositionZ();
/*for(WorldObject::InRangeArray::iterator itr = m_caster->GetInRangeUnitSetBegin(); itr != m_caster->GetInRangeUnitSetEnd(); itr++ )
{
Unit *unit = m_caster->GetInRangeObject<Unit>(*itr);
if(!unit->isAlive())
continue;
if( m_spellInfo->TargetCreatureType && (!(1<<(unit->GetCreatureType()-1) & m_spellInfo->TargetCreatureType)))
continue;
if(!IsInrange(srcx,srcy,srcz, unit, rMax, rMin))
continue;
if(!sFactionSystem.isFriendly(m_caster, unit))
continue;
if(_DidHit(unit) != SPELL_DID_HIT_SUCCESS)
continue;
return unit->GetGUID();
}*/
return 0;
}
void Spell::AddAOETargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets)
{
LocationVector source;
//cant do raid/party stuff here, seperate functions for it
if(TargetType & (SPELL_TARGET_AREA_PARTY | SPELL_TARGET_AREA_RAID))
return;
WorldObject* tarobj = _unitCaster->GetInRangeObject(m_targets.m_unitTarget);
if(TargetType & SPELL_TARGET_AREA_SELF)
source = _unitCaster->GetPosition();
else if(TargetType & SPELL_TARGET_AREA_CURTARGET && tarobj != NULL)
source = tarobj->GetPosition();
else
{
m_targets.m_targetMask |= TARGET_FLAG_DEST_LOCATION;
source = m_targets.m_dest;
}
float range = r*r; //caster might be in the aoe LOL
if(_unitCaster->GetDistanceSq(source) <= range)
AddTarget(i, TargetType, _unitCaster);
WorldObject *wObj = NULL;
/*for(WorldObject::InRangeHashMap::iterator itr = m_caster->GetInRangeMapBegin(); itr != m_caster->GetInRangeMapEnd(); itr++ )
{
if((wObj = itr->second) == NULL)
continue;
if(maxtargets != 0 && m_effectTargetMaps[i].size() >= maxtargets)
break;
if(wObj->GetDistanceSq(source) > range)
continue;
AddTarget(i, TargetType, wObj);
}*/
}
void Spell::AddPartyTargets(uint32 i, uint32 TargetType, float radius, uint32 maxtargets)
{
WorldObject* u = _unitCaster->GetInRangeObject(m_targets.m_unitTarget);
if(u == NULL && (u = _unitCaster) == NULL)
return;
if(!u->IsPlayer())
return;
Player* p = castPtr<Player>(u);
AddTarget(i, TargetType, p);
float range = radius*radius;
/*WorldObject::InRangeArray::iterator itr;
for(itr = u->GetInRangePlayerSetBegin(); itr != u->GetInRangePlayerSetEnd(); itr++)
{
Player *target = u->GetInRangeObject<Player>(*itr);
if(target == NULL || !target->isAlive())
continue;
if(!p->IsGroupMember(target))
continue;
if(u->GetDistanceSq(target) > range)
continue;
AddTarget(i, TargetType, target);
}*/
}
void Spell::AddRaidTargets(uint32 i, uint32 TargetType, float radius, uint32 maxtargets, bool partylimit)
{
WorldObject* u = _unitCaster->GetInRangeObject(m_targets.m_unitTarget);
if(u == NULL && (u = _unitCaster) == NULL)
return;
if(!u->IsPlayer())
return;
Player* p = castPtr<Player>(u);
AddTarget(i, TargetType, p);
float range = radius*radius;
/*WorldObject::InRangeArray::iterator itr;
for(itr = u->GetInRangePlayerSetBegin(); itr != u->GetInRangePlayerSetEnd(); itr++)
{
Player *target = u->GetInRangeObject<Player>(*itr);
if(target == NULL || !target->isAlive())
continue;
if(!p->IsGroupMember(target))
continue;
if(u->GetDistanceSq(target) > range)
continue;
AddTarget(i, TargetType, target);
}*/
}
void Spell::AddChainTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets)
{
if(!_unitCaster->IsInWorld())
return;
WorldObject* targ = _unitCaster->GetInRangeObject(m_targets.m_unitTarget);
if(targ == NULL)
return;
//if selected target is party member, then jumps on party
Unit* firstTarget = NULL;
if(targ->IsUnit())
firstTarget = castPtr<Unit>(targ);
else firstTarget = _unitCaster;
bool RaidOnly = false;
float range = m_spellInfo->maxRange[0];
//this is cast distance, not searching distance
range *= range;
//is this party only?
Player* casterFrom = NULL;
if(_unitCaster->IsPlayer())
casterFrom = castPtr<Player>(_unitCaster);
Player* pfirstTargetFrom = NULL;
if(firstTarget->IsPlayer())
pfirstTargetFrom = castPtr<Player>(firstTarget);
if(casterFrom != NULL && pfirstTargetFrom != NULL && casterFrom->GetGroup() == pfirstTargetFrom->GetGroup())
RaidOnly = true;
uint32 jumps = m_spellInfo->EffectChainTarget[i];
//range
range /= jumps; //hacky, needs better implementation!
if(m_spellInfo->SpellGroupType)
_unitCaster->SM_FIValue(SMT_JUMP_REDUCE, (int32*)&jumps, m_spellInfo->SpellGroupType);
AddTarget(i, TargetType, firstTarget);
if(jumps <= 1 || m_effectTargetMaps[i].size() == 0) //1 because we've added the first target, 0 size if spell is resisted
return;
/*WorldObject::InRangeArray::iterator itr;
for(itr = firstTarget->GetInRangeUnitSetBegin(); itr != firstTarget->GetInRangeUnitSetEnd(); itr++)
{
Unit *target = m_caster->GetInRangeObject<Unit>(*itr);
if(target == NULL || !target->isAlive())
continue;
if(RaidOnly)
{
if(!target->IsPlayer())
continue;
if(!pfirstTargetFrom->IsGroupMember(castPtr<Player>(target)))
continue;
}
//healing spell, full health target = NONO
if(IsHealingSpell(m_spellInfo) && target->GetHealthPct() == 100)
continue;
size_t oldsize;
if(IsInrange(firstTarget->GetPositionX(), firstTarget->GetPositionY(), firstTarget->GetPositionZ(), target, range))
{
oldsize = m_effectTargetMaps[i].size();
AddTarget(i, TargetType, target);
if(m_effectTargetMaps[i].size() == oldsize || m_effectTargetMaps[i].size() >= jumps) //either out of jumps or a resist
return;
}
}*/
}
void Spell::AddConeTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets)
{
/*WorldObject::InRangeArray::iterator itr;
for(itr = m_caster->GetInRangeUnitSetBegin(); itr != m_caster->GetInRangeUnitSetEnd(); itr++)
{
Unit *target = m_caster->GetInRangeObject<Unit>(*itr);
if(!target->isAlive())
continue;
//is Creature in range
if(m_caster->isInRange(target, GetRadius(i)))
{
if(m_caster->isTargetInFront(target)) // !!! is the target within our cone ?
{
AddTarget(i, TargetType, target);
}
}
if(maxtargets != 0 && m_effectTargetMaps[i].size() >= maxtargets)
return;
}*/
}
void Spell::AddScriptedOrSpellFocusTargets(uint32 i, uint32 TargetType, float r, uint32 maxtargets)
{
/*for(WorldObject::InRangeArray::iterator itr = m_caster->GetInRangeGameObjectSetBegin(); itr != m_caster->GetInRangeGameObjectSetEnd(); itr++ )
{
if(GameObject* go = m_caster->GetInRangeObject<GameObject>(*itr))
{
if(go->GetInfo()->data.spellFocus.focusId == m_spellInfo->RequiresSpellFocus)
{
if(!m_caster->isInRange(go, r))
continue;
if(AddTarget(i, TargetType, go))
return;
}
}
}*/
}
// returns Guid of lowest percentage health friendly party or raid target within sqrt('dist') yards
uint64 Spell::FindLowestHealthRaidMember(Player* Target, uint32 dist)
{
if(!Target || !Target->IsInWorld())
return 0;
uint64 lowestHealthTarget = Target->GetGUID();
uint32 lowestHealthPct = Target->GetHealthPct();
if(Group *group = Target->GetGroup())
{
group->Lock();
for(uint32 j = 0; j < group->GetSubGroupCount(); ++j) {
for(GroupMembersSet::iterator itr = group->GetSubGroup(j)->GetGroupMembersBegin(); itr != group->GetSubGroup(j)->GetGroupMembersEnd(); itr++)
{
if((*itr)->m_loggedInPlayer && Target->GetDistance2dSq((*itr)->m_loggedInPlayer) <= dist)
{
uint32 healthPct = (*itr)->m_loggedInPlayer->GetHealthPct();
if(healthPct < lowestHealthPct)
{
lowestHealthPct = healthPct;
lowestHealthTarget = (*itr)->m_loggedInPlayer->GetGUID();
}
}
}
}
group->Unlock();
}
return lowestHealthTarget;
}
<file_sep>/src/ronin-world/Objects/DynamicObject.h
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
class BaseSpell;
struct SpellEntry;
typedef std::set<uint64> DynamicObjectList;
class SERVER_DECL DynamicObject : public WorldObject
{
public:
DynamicObject( uint32 high, uint32 low, uint32 fieldCount = DYNAMICOBJECT_END );
~DynamicObject( );
virtual void Init();
virtual void Destruct();
virtual bool IsDynamicObj() { return true; }
// Don't think we need reactivate for world objects either
virtual void Reactivate() {}
RONIN_INLINE uint8 GetDynamicObjectPool() { return m_dynamicobjectPool; }
RONIN_INLINE void AssignDynamicObjectPool(uint8 pool) { m_dynamicobjectPool = pool; }
void Create(WorldObject* caster, BaseSpell* pSpell, float x, float y, float z, int32 duration, float radius);
void UpdateTargets(uint32 p_time);
void Remove();
uint32 getLevel() { return casterLevel; }
uint64 GetCasterGuid() { return casterGuid; }
protected:
uint8 m_dynamicobjectPool;
uint32 casterLevel;
uint64 casterGuid;
SpellEntry * m_spellProto;
DynamicObjectList targets;
int32 m_aliveDuration;
};
<file_sep>/dependencies/SRC/threading/Mutex.h
/*
* Sandshroud Project Ronin
* Copyright (C) 2015-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#ifdef __DragonFly__
#include <pthread.h>
#endif
#ifdef _WIN32_WINNT
#include <Windows.h>
#endif
class SERVER_DECL EasyMutex
{
public:
friend class Condition;
/** Initializes a mutex class, with InitializeCriticalSection / pthread_mutex_init
*/
EasyMutex();
/** Deletes the associated critical section / mutex
*/
~EasyMutex();
/** Acquires this mutex. If it cannot be acquired immediately, it will block.
*/
RONIN_INLINE void Acquire()
{
#if PLATFORM != PLATFORM_WIN
pthread_mutex_lock(&mutex);
#else
EnterCriticalSection(&cs);
#endif
}
/** Releases this mutex. No error checking performed
*/
RONIN_INLINE void Release()
{
#if PLATFORM != PLATFORM_WIN
pthread_mutex_unlock(&mutex);
#else
LeaveCriticalSection(&cs);
#endif
}
/** Attempts to acquire this mutex. If it cannot be acquired (held by another thread)
* it will return false.
* @return false if cannot be acquired, true if it was acquired.
*/
RONIN_INLINE bool AttemptAcquire()
{
#if PLATFORM != PLATFORM_WIN
return (pthread_mutex_trylock(&mutex) == 0);
#else
return (TryEnterCriticalSection(&cs) == TRUE ? true : false);
#endif
}
protected:
#if PLATFORM == PLATFORM_WIN
/** Critical section used for system calls
*/
CRITICAL_SECTION cs;
#else
/** Static mutex attribute
*/
static bool attr_initalized;
static pthread_mutexattr_t attr;
/** pthread struct used in system calls
*/
pthread_mutex_t mutex;
#endif
};
class SERVER_DECL SmartMutex
{
public:
friend class Condition;
/** Initializes a mutex class, with InitializeCriticalSection / pthread_mutex_init
*/
SmartMutex();
/** Deletes the associated critical section / mutex
*/
~SmartMutex();
/** Acquires this mutex. If it cannot be acquired immediately, it will block.
*/
RONIN_INLINE void Acquire(bool RestrictUnlocking = false)
{
if(ronin_GetThreadId() == m_activeThread)
{
m_ThreadCalls++;
return;
}
#if PLATFORM != PLATFORM_WIN
pthread_mutex_lock(&mutex);
#else
EnterCriticalSection(&cs);
#endif
m_ThreadCalls++;
m_activeThread = ronin_GetThreadId();
LockReleaseToThread = RestrictUnlocking;
}
/** Releases this mutex. No error checking performed
*/
RONIN_INLINE void Release()
{
// If we're locked to this specific thread, and we're unlocked from another thread, error
if(LockReleaseToThread && ronin_GetThreadId() != m_activeThread)
ASSERT(false && "MUTEX RELEASE CALLED FROM NONACTIVE THREAD!");
m_ThreadCalls--;
if(m_ThreadCalls == 0)
{
m_activeThread = 0;
#if PLATFORM != PLATFORM_WIN
pthread_mutex_unlock(&mutex);
#else
LeaveCriticalSection(&cs);
#endif
}
}
/** Attempts to acquire this mutex. If it cannot be acquired (held by another thread)
* it will return false.
* @return false if cannot be acquired, true if it was acquired.
*/
RONIN_INLINE bool AttemptAcquire(bool RestrictUnlocking = false)
{
if(ronin_GetThreadId() == m_activeThread)
{
m_ThreadCalls++;
return true;
}
#if PLATFORM != PLATFORM_WIN
if(pthread_mutex_trylock(&mutex) == 0)
#else
if(TryEnterCriticalSection(&cs) == TRUE)
#endif
{
m_ThreadCalls++;
m_activeThread = ronin_GetThreadId();
LockReleaseToThread = RestrictUnlocking;
return true;
}
return false;
}
protected:
bool LockReleaseToThread;
uint32 m_activeThread;
uint32 m_ThreadCalls;
#if PLATFORM == PLATFORM_WIN
/** Critical section used for system calls
*/
CRITICAL_SECTION cs;
#else
/** Static mutex attribute
*/
static bool attr_initalized;
static pthread_mutexattr_t attr;
/** pthread struct used in system calls
*/
pthread_mutex_t mutex;
#endif
};
#define Mutex EasyMutex
<file_sep>/dependencies/SRC/threading/ThreadPool.h
/*
* Sandshroud Project Ronin
* Copyright (C) 2015-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // must be 0x1000
LPCSTR szName; // pointer to name (in user addr space)
DWORD dwThreadID; // thread ID (-1=caller thread)
DWORD dwFlags; // reserved for future use, must be zero
} THREADNAME_INFO;
struct SERVER_DECL Thread
{
char* name;
uint32 ThreadId;
Thread(char* tname) { name = tname; }
ThreadContext * ExecutionTarget;
};
class SERVER_DECL CThreadPool
{
Mutex _mutex;
typedef std::set<Thread*> ThreadSet;
ThreadSet m_activeThreads;
public:
CThreadPool();
// shutdown all threads
void Shutdown();
// return true - suspend ourselves, and wait for a future task.
// return false - exit, we're shutting down or no longer needed.
void ThreadExit(Thread * t);
// creates a thread, returns a handle to it.
Thread * StartThread(ThreadContext * ExecutionTarget);
// grabs/spawns a thread, and tells it to execute a task.
void ExecuteTask(const char* ThreadName, ThreadContext * ExecutionTarget);
// gets active thread count
RONIN_INLINE uint32 GetActiveThreadCount() { return (uint32)m_activeThreads.size(); }
// Creates exception which sets the thread name, do not call inside try block
static void SetThreadName(const char* format);
static void Suicide();
};
extern SERVER_DECL CThreadPool ThreadPool;
<file_sep>/src/ronin-world/Spell/SpellAuras.cpp
/*
* Sandshroud Project Ronin
* Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2009 AspireDev <http://www.aspiredev.org/>
* Copyright (C) 2009-2017 Sandshroud <https://github.com/Sandshroud>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
pSpellAura SpellAuraHandler[SPELL_AURA_TOTAL] = {
&Aura::SpellAuraNULL, //SPELL_AURA_NONE = 0
&Aura::SpellAuraBindSight, //SPELL_AURA_BIND_SIGHT = 1
&Aura::SpellAuraModPossess, //SPELL_AURA_MOD_POSSESS = 2
&Aura::SpellAuraPeriodicDamage, //SPELL_AURA_PERIODIC_DAMAGE = 3
&Aura::SpellAuraDummy, //SPELL_AURA_DUMMY = 4
&Aura::SpellAuraModConfuse, //SPELL_AURA_MOD_CONFUSE = 5
&Aura::SpellAuraModCharm, //SPELL_AURA_MOD_CHARM = 6
&Aura::SpellAuraModFear, //SPELL_AURA_MOD_FEAR = 7
&Aura::SpellAuraPeriodicHeal, //SPELL_AURA_PERIODIC_HEAL = 8
&Aura::SpellAuraModAttackSpeed, //SPELL_AURA_MOD_ATTACKSPEED = 9
&Aura::SpellAuraModThreatGenerated, //SPELL_AURA_MOD_THREAT = 10
&Aura::SpellAuraModTaunt, //SPELL_AURA_MOD_TAUNT = 11
&Aura::SpellAuraModStun, //SPELL_AURA_MOD_STUN = 12
&Aura::SpellAuraModDamageDone, //SPELL_AURA_MOD_DAMAGE_DONE = 13
&Aura::SpellAuraModDamageTaken, //SPELL_AURA_MOD_DAMAGE_TAKEN = 14
&Aura::SpellAuraDamageShield, //SPELL_AURA_DAMAGE_SHIELD = 15
&Aura::SpellAuraModStealth, //SPELL_AURA_MOD_STEALTH = 16
&Aura::SpellAuraModDetect, //SPELL_AURA_MOD_DETECT = 17
&Aura::SpellAuraModInvisibility, //SPELL_AURA_MOD_INVISIBILITY = 18
&Aura::SpellAuraModInvisibilityDetection, //SPELL_AURA_MOD_INVISIBILITY_DETECTION = 19
&Aura::SpellAuraModTotalHealthRegenPct, //SPELL_AURA_MOD_TOTAL_HEALTH_REGEN_PCT = 20
&Aura::SpellAuraModTotalManaRegenPct, //SPELL_AURA_MOD_TOTAL_MANA_REGEN_PCT = 21
&Aura::SpellAuraUtilized, //SPELL_AURA_MOD_RESISTANCE = 22
&Aura::SpellAuraPeriodicTriggerSpell, //SPELL_AURA_PERIODIC_TRIGGER_SPELL = 23
&Aura::SpellAuraPeriodicEnergize, //SPELL_AURA_PERIODIC_ENERGIZE = 24
&Aura::SpellAuraModPacify, //SPELL_AURA_MOD_PACIFY = 25
&Aura::SpellAuraModRoot, //SPELL_AURA_MOD_ROOT = 26
&Aura::SpellAuraModSilence, //SPELL_AURA_MOD_SILENCE = 27
&Aura::SpellAuraReflectSpells, //SPELL_AURA_REFLECT_SPELLS = 28
&Aura::SpellAuraModStat, //SPELL_AURA_MOD_STAT = 29
&Aura::SpellAuraModSkill, //SPELL_AURA_MOD_SKILL = 30
&Aura::SpellAuraModIncreaseSpeed, //SPELL_AURA_MOD_INCREASE_SPEED = 31
&Aura::SpellAuraModIncreaseMountedSpeed, //SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED = 32
&Aura::SpellAuraModDecreaseSpeed, //SPELL_AURA_MOD_DECREASE_SPEED = 33
&Aura::SpellAuraModIncreaseHealth, //SPELL_AURA_MOD_INCREASE_HEALTH = 34
&Aura::SpellAuraModIncreaseEnergy, //SPELL_AURA_MOD_INCREASE_ENERGY = 35
&Aura::SpellAuraModShapeshift, //SPELL_AURA_MOD_SHAPESHIFT = 36
&Aura::SpellAuraModEffectImmunity, //SPELL_AURA_EFFECT_IMMUNITY = 37
&Aura::SpellAuraModStateImmunity, //SPELL_AURA_STATE_IMMUNITY = 38
&Aura::SpellAuraModSchoolImmunity, //SPELL_AURA_SCHOOL_IMMUNITY = 39
&Aura::SpellAuraModDmgImmunity, //SPELL_AURA_DAMAGE_IMMUNITY = 40
&Aura::SpellAuraModDispelImmunity, //SPELL_AURA_DISPEL_IMMUNITY = 41
&Aura::SpellAuraProcTriggerSpell, //SPELL_AURA_PROC_TRIGGER_SPELL = 42
&Aura::SpellAuraProcTriggerDamage, //SPELL_AURA_PROC_TRIGGER_DAMAGE = 43
&Aura::SpellAuraTrackCreatures, //SPELL_AURA_TRACK_CREATURES = 44
&Aura::SpellAuraTrackResources, //SPELL_AURA_TRACK_RESOURCES = 45
&Aura::SpellAuraModParrySkill, //SPELL_AURA_MOD_PARRY_SKILL = 46
&Aura::SpellAuraModParryPerc, //SPELL_AURA_MOD_PARRY_PERCENT = 47
&Aura::SpellAuraModDodgeSkill, //SPELL_AURA_MOD_DODGE_SKILL = 48
&Aura::SpellAuraModDodgePerc, //SPELL_AURA_MOD_DODGE_PERCENT = 49
&Aura::SpellAuraModBlockSkill, //SPELL_AURA_MOD_BLOCK_SKILL = 50
&Aura::SpellAuraModBlockPerc, //SPELL_AURA_MOD_BLOCK_PERCENT = 51
&Aura::SpellAuraModCritPerc, //SPELL_AURA_MOD_CRIT_PERCENT = 52
&Aura::SpellAuraPeriodicLeech, //SPELL_AURA_PERIODIC_LEECH = 53
&Aura::SpellAuraModHitChance, //SPELL_AURA_MOD_HIT_CHANCE = 54
&Aura::SpellAuraModSpellHitChance, //SPELL_AURA_MOD_SPELL_HIT_CHANCE = 55
&Aura::SpellAuraTransform, //SPELL_AURA_TRANSFORM = 56
&Aura::SpellAuraModSpellCritChance, //SPELL_AURA_MOD_SPELL_CRIT_CHANCE = 57
&Aura::SpellAuraIncreaseSwimSpeed, //SPELL_AURA_MOD_INCREASE_SWIM_SPEED = 58
&Aura::SpellAuraModCratureDmgDone, //SPELL_AURA_MOD_DAMAGE_DONE_CREATURE = 59
&Aura::SpellAuraPacifySilence, //SPELL_AURA_MOD_PACIFY_SILENCE = 60
&Aura::SpellAuraModScale, //SPELL_AURA_MOD_SCALE = 61
&Aura::SpellAuraPeriodicHealthFunnel, //SPELL_AURA_PERIODIC_HEALTH_FUNNEL = 62
&Aura::SpellAuraIgnore, //SPELL_AURA_PERIODIC_MANA_FUNNEL = 63
&Aura::SpellAuraPeriodicManaLeech, //SPELL_AURA_PERIODIC_MANA_LEECH = 64
&Aura::SpellAuraModCastingSpeed, //SPELL_AURA_MOD_CASTING_SPEED = 65
&Aura::SpellAuraFeignDeath, //SPELL_AURA_FEIGN_DEATH = 66
&Aura::SpellAuraModDisarm, //SPELL_AURA_MOD_DISARM = 67
&Aura::SpellAuraModStalked, //SPELL_AURA_MOD_STALKED = 68
&Aura::SpellAuraSchoolAbsorb, //SPELL_AURA_SCHOOL_ABSORB = 69
&Aura::SpellAuraIgnore, //SPELL_AURA_EXTRA_ATTACKS = 70
&Aura::SpellAuraModSpellCritChanceSchool, //SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL = 71
&Aura::SpellAuraModPowerCost, //SPELL_AURA_MOD_POWER_COST = 72
&Aura::SpellAuraModPowerCostSchool, //SPELL_AURA_MOD_POWER_COST_SCHOOL = 73
&Aura::SpellAuraReflectSpellsSchool, //SPELL_AURA_REFLECT_SPELLS_SCHOOL = 74
&Aura::SpellAuraModLanguage, //SPELL_AURA_MOD_LANGUAGE = 75
&Aura::SpellAuraAddFarSight, //SPELL_AURA_FAR_SIGHT = 76
&Aura::SpellAuraMechanicImmunity, //SPELL_AURA_MECHANIC_IMMUNITY = 77
&Aura::SpellAuraMounted, //SPELL_AURA_MOUNTED = 78
&Aura::SpellAuraModDamagePercDone, //SPELL_AURA_MOD_DAMAGE_PERCENT_DONE = 79
&Aura::SpellAuraModPercStat, //SPELL_AURA_MOD_PERCENT_STAT = 80
&Aura::SpellAuraSplitDamage, //SPELL_AURA_SPLIT_DAMAGE = 81
&Aura::SpellAuraWaterBreathing, //SPELL_AURA_WATER_BREATHING = 82
&Aura::SpellAuraUtilized, //SPELL_AURA_MOD_BASE_RESISTANCE = 83
&Aura::SpellAuraModRegen, //SPELL_AURA_MOD_REGEN = 84
&Aura::SpellAuraModPowerRegen, //SPELL_AURA_MOD_POWER_REGEN = 85
&Aura::SpellAuraChannelDeathItem, //SPELL_AURA_CHANNEL_DEATH_ITEM = 86
&Aura::SpellAuraModDamagePercTaken, //SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN = 87
&Aura::SpellAuraModRegenPercent, //SPELL_AURA_MOD_PERCENT_REGEN = 88
&Aura::SpellAuraPeriodicDamagePercent, //SPELL_AURA_PERIODIC_DAMAGE_PERCENT = 89
&Aura::SpellAuraModResistChance, //SPELL_AURA_MOD_RESIST_CHANCE = 90
&Aura::SpellAuraModDetectRange, //SPELL_AURA_MOD_DETECT_RANGE = 91
&Aura::SpellAuraPreventsFleeing, //SPELL_AURA_PREVENTS_FLEEING = 92
&Aura::SpellAuraModUnattackable, //SPELL_AURA_MOD_UNATTACKABLE = 93
&Aura::SpellAuraInterruptRegen, //SPELL_AURA_INTERRUPT_REGEN = 94
&Aura::SpellAuraGhost, //SPELL_AURA_GHOST = 95
&Aura::SpellAuraMagnet, //SPELL_AURA_SPELL_MAGNET = 96
&Aura::SpellAuraManaShield, //SPELL_AURA_MANA_SHIELD = 97
&Aura::SpellAuraSkillTalent, //SPELL_AURA_MOD_SKILL_TALENT = 98
&Aura::SpellAuraModAttackPower, //SPELL_AURA_MOD_ATTACK_POWER = 99
&Aura::SpellAuraVisible, //SPELL_AURA_AURAS_VISIBLE = 100
&Aura::SpellAuraUtilized, //SPELL_AURA_MOD_RESISTANCE_PCT = 101
&Aura::SpellAuraModCreatureAttackPower, //SPELL_AURA_MOD_CREATURE_ATTACK_POWER = 102
&Aura::SpellAuraModTotalThreat, //SPELL_AURA_MOD_TOTAL_THREAT = 103
&Aura::SpellAuraWaterWalk, //SPELL_AURA_WATER_WALK = 104
&Aura::SpellAuraFeatherFall, //SPELL_AURA_FEATHER_FALL = 105
&Aura::SpellAuraHover, //SPELL_AURA_HOVER = 106
&Aura::SpellAuraAddFlatModifier, //SPELL_AURA_ADD_FLAT_MODIFIER = 107
&Aura::SpellAuraAddPctMod, //SPELL_AURA_ADD_PCT_MODIFIER = 108
&Aura::SpellAuraAddTargetTrigger, //SPELL_AURA_ADD_TARGET_TRIGGER = 109
&Aura::SpellAuraModPowerRegPerc, //SPELL_AURA_MOD_POWER_REGEN_PERCENT = 110
&Aura::SpellAuraNULL, //SPELL_AURA_ADD_CASTER_HIT_TRIGGER = 111
&Aura::SpellAuraOverrideClassScripts, //SPELL_AURA_OVERRIDE_CLASS_SCRIPTS = 112
&Aura::SpellAuraModRangedDamageTaken, //SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN = 113
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT = 114
&Aura::SpellAuraModHealing, //SPELL_AURA_MOD_HEALING = 115
&Aura::SpellAuraIgnoreRegenInterrupt, //SPELL_AURA_IGNORE_REGEN_INTERRUPT = 116
&Aura::SpellAuraModMechanicResistance, //SPELL_AURA_MOD_MECHANIC_RESISTANCE = 117
&Aura::SpellAuraModHealingPCT, //SPELL_AURA_MOD_HEALING_PCT = 118
&Aura::SpellAuraNULL, //SPELL_AURA_SHARE_PET_TRACKING = 119
&Aura::SpellAuraUntrackable, //SPELL_AURA_UNTRACKABLE = 120
&Aura::SpellAuraEmphaty, //SPELL_AURA_EMPATHY = 121
&Aura::SpellAuraModOffhandDamagePCT, //SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT = 122
&Aura::SpellAuraModPenetration, //SPELL_AURA_MOD_POWER_COST_PCT = 123
&Aura::SpellAuraModRangedAttackPower, //SPELL_AURA_MOD_RANGED_ATTACK_POWER = 124
&Aura::SpellAuraModMeleeDamageTaken, //SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN = 125
&Aura::SpellAuraModMeleeDamageTakenPct, //SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT = 126
&Aura::SpellAuraRAPAttackerBonus, //SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS = 127
&Aura::SpellAuraModPossessPet, //SPELL_AURA_MOD_POSSESS_PET = 128
&Aura::SpellAuraModIncreaseSpeedAlways, //SPELL_AURA_MOD_INCREASE_SPEED_ALWAYS = 129
&Aura::SpellAuraModIncreaseMountedSpeed, //SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS = 130
&Aura::SpellAuraModCreatureRangedAttackPower, //SPELL_AURA_MOD_CREATURE_RANGED_ATTACK_POWER = 131
&Aura::SpellAuraModIncreaseEnergyPerc, //SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT = 132
&Aura::SpellAuraModIncreaseHealthPerc, //SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT = 133
&Aura::SpellAuraModManaRegInterrupt, //SPELL_AURA_MOD_MANA_REGEN_INTERRUPT = 134
&Aura::SpellAuraModHealingDone, //SPELL_AURA_MOD_HEALING_DONE = 135
&Aura::SpellAuraModHealingDonePct, //SPELL_AURA_MOD_HEALING_DONE_PERCENT = 136
&Aura::SpellAuraModTotalStatPerc, //SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE = 137
&Aura::SpellAuraModHaste, //SPELL_AURA_MOD_HASTE = 138
&Aura::SpellAuraForceReaction, //SPELL_AURA_FORCE_REACTION = 139
&Aura::SpellAuraModRangedHaste, //SPELL_AURA_MOD_RANGED_HASTE = 140
&Aura::SpellAuraModRangedAmmoHaste, //SPELL_AURA_MOD_RANGED_AMMO_HASTE = 141
&Aura::SpellAuraUtilized, //SPELL_AURA_MOD_BASE_RESISTANCE_PCT = 142
&Aura::SpellAuraUtilized, //SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE = 143
&Aura::SpellAuraSafeFall, //SPELL_AURA_SAFE_FALL = 144
&Aura::SpellAuraModPetTalentPoints, //SPELL_AURA_MOD_PET_TALENT_POINTS = 145
&Aura::SpellAuraAllowTamePetType, //SPELL_AURA_ALLOW_TAME_PET_TYPE = 146
&Aura::SpellAuraAddCreatureImmunity, //SPELL_AURA_ADD_CREATURE_IMMUNITY = 147
&Aura::SpellAuraRetainComboPoints, //SPELL_AURA_RETAIN_COMBO_POINTS = 148
&Aura::SpellAuraResistPushback, //SPELL_AURA_RESIST_PUSHBACK = 149
&Aura::SpellAuraModShieldBlockPCT, //SPELL_AURA_MOD_SHIELD_BLOCK_PCT = 150
&Aura::SpellAuraTrackStealthed, //SPELL_AURA_TRACK_STEALTHED = 151
&Aura::SpellAuraModDetectedRange, //SPELL_AURA_MOD_DETECTED_RANGE = 152
&Aura::SpellAuraSplitDamageFlat, //SPELL_AURA_SPLIT_DAMAGE_FLAT= 153
&Aura::SpellAuraModStealthLevel, //SPELL_AURA_MOD_STEALTH_LEVEL = 154
&Aura::SpellAuraModUnderwaterBreathing, //SPELL_AURA_MOD_WATER_BREATHING = 155
&Aura::SpellAuraModReputationAdjust, //SPELL_AURA_MOD_REPUTATION_ADJUST = 156
&Aura::SpellAuraNULL, //SPELL_AURA_PET_DAMAGE_MULTI = 157
&Aura::SpellAuraModBlockValue, //SPELL_AURA_MOD_SHIELD_BLOCKVALUE = 158
&Aura::SpellAuraNoPVPCredit, //SPELL_AURA_NO_PVP_CREDIT = 159
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_AOE_AVOIDANCE = 160
&Aura::SpellAuraModHealthRegInCombat, //SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT = 161
&Aura::SpellAuraPowerBurn, //SPELL_AURA_POWER_BURN_MANA = 162
&Aura::SpellAuraModCritDmgPhysical, //SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE = 163
&Aura::SpellAuraNULL, //missing = 164
&Aura::SpellAuraAPAttackerBonus, //SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS = 165
&Aura::SpellAuraModPAttackPower, //SPELL_AURA_MOD_ATTACK_POWER_PCT = 166
&Aura::SpellAuraModRangedAttackPowerPct, //SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT = 167
&Aura::SpellAuraIncreaseDamageTypePCT, //SPELL_AURA_MOD_DAMAGE_DONE_VERSUS = 168
&Aura::SpellAuraIncreaseCricticalTypePCT, //SPELL_AURA_MOD_CRIT_PERCENT_VERSUS = 169
&Aura::SpellAuraNULL, //SPELL_AURA_DETECT_AMORE = 170
&Aura::SpellAuraIncreasePartySpeed, //SPELL_AURA_MOD_SPEED_NOT_STACK = 171
&Aura::SpellAuraIncreaseMovementAndMountedSpeed, //SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK = 172
&Aura::SpellAuraNULL, //missing = 173
&Aura::SpellAuraIncreaseSpellDamageByAttribute, //SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT = 174
&Aura::SpellAuraIncreaseHealingByAttribute, //SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT = 175
&Aura::SpellAuraSpiritOfRedemption, //SPELL_AURA_SPIRIT_OF_REDEMPTION = 176
&Aura::SpellAuraNULL, //SPELL_AURA_AOE_CHARM = 177
&Aura::SpellAuraDispelDebuffResist, //SPELL_AURA_MOD_DEBUFF_RESISTANCE = 178
&Aura::SpellAuraIncreaseAttackerSpellCrit, //SPELL_AURA_INCREASE_ATTACKER_SPELL_CRIT = 179
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS = 180
&Aura::SpellAuraNULL, //missing = 181
&Aura::SpellAuraIncreaseArmorByPctInt, //SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT = 182
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_CRITICAL_THREAT = 183
&Aura::SpellAuraReduceAttackerMHitChance, //SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE = 184
&Aura::SpellAuraReduceAttackerRHitChance, //SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE = 185
&Aura::SpellAuraReduceAttackerSHitChance, //SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE = 186
&Aura::SpellAuraReduceEnemyMCritChance, //SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE = 187
&Aura::SpellAuraReduceEnemyRCritChance, //SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE = 188
&Aura::SpellAuraIncreaseRating, //SPELL_AURA_MOD_RATING = 189
&Aura::SpellAuraIncreaseRepGainPct, //SPELL_AURA_MOD_FACTION_REPUTATION_GAIN = 190
&Aura::SpellAuraUseNormalMovementSpeed, //SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED = 191
&Aura::SpellAuraModAttackSpeed, //SPELL_AURA_MOD_MELEE_RANGED_HASTE = 192
&Aura::SpellAuraIncreaseTimeBetweenAttacksPCT, //SPELL_AURA_MELEE_SLOW = 193
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL = 194
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL = 195
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_COOLDOWN = 196
&Aura::SpellAuraModAttackerCritChance, //SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE = 197
&Aura::SpellAuraIncreaseAllWeaponSkill, // = 198
&Aura::SpellAuraIncreaseHitRate, //SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT = 199
&Aura::SpellAuraModMobKillXPGain, //SPELL_AURA_MOD_XP_PCT = 200
&Aura::SpellAuraEnableFlight, //SPELL_AURA_FLY = 201
&Aura::SpellAuraFinishingMovesCannotBeDodged, //SPELL_AURA_IGNORE_COMBAT_RESULT = 202
&Aura::SpellAuraReduceCritMeleeAttackDmg, //SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE = 203
&Aura::SpellAuraReduceCritRangedAttackDmg, //SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE = 204
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_SCHOOL_CRIT_DMG_TAKEN = 205
&Aura::SpellAuraIncreaseFlightSpeed, //SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED = 206
&Aura::SpellAuraEnableFlight, //SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED = 207
&Aura::SpellAuraEnableFlightWithUnmountedSpeed, //SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED = 208
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_MOUNTED_FLIGHT_SPEED_ALWAYS = 209
&Aura::SpellAuraIncreaseFlightSpeed, //SPELL_AURA_MOD_VEHICLE_SPEED_ALWAYS = 210
&Aura::SpellAuraIncreaseFlightSpeed, //SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK = 211
&Aura::SpellAuraIncreaseRangedAPStatPCT, //SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_INTELLECT = 212
&Aura::SpellAuraIncreaseRageFromDamageDealtPCT, //SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT = 213
&Aura::SpellAuraNULL, // = 214
&Aura::SpellAuraNoReagentCost, //SPELL_AURA_ARENA_PREPARATION = 215
&Aura::SpellAuraModCastingSpeed, //SPELL_AURA_HASTE_SPELLS = 216
&Aura::SpellAuraNULL, // = 217
&Aura::SpellAuraHasteRanged, //SPELL_AURA_HASTE_RANGED = 218
&Aura::SpellAuraRegenManaStatPCT, //SPELL_AURA_MOD_MANA_REGEN_FROM_STAT = 219
&Aura::SpellAuraSpellHealingStatPCT, //SPELL_AURA_MOD_RATING_FROM_STAT = 220
&Aura::SpellAuraIgnoreEnemy, //SPELL_AURA_MOD_DETAUNT = 221
&Aura::SpellAuraNULL, // = 222
&Aura::SpellAuraNULL, //SPELL_AURA_RAID_PROC_FROM_CHARGE = 223
&Aura::SpellAuraNULL, // = 224
&Aura::SpellAuraHealAndJump, //SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE = 225
&Aura::SpellAuraDrinkNew, //SPELL_AURA_PERIODIC_DUMMY = 226
&Aura::SpellAuraPeriodicTriggerSpellWithValue, //SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE = 227
&Aura::SpellAuraAuraModInvisibilityDetection, //SPELL_AURA_DETECT_STEALTH = 228
&Aura::SpellAuraReduceAOEDamageTaken, //SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE = 229
&Aura::SpellAuraIncreaseMaxHealth, //SPELL_AURA_MOD_INCREASE_MAX_HEALTH = 230
&Aura::SpellAuraProcTriggerWithValue, //SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE = 231
&Aura::SpellAuraReduceEffectDuration, //SPELL_AURA_MECHANIC_DURATION_MOD = 232
&Aura::SpellAuraNULL, // = 233
&Aura::SpellAuraReduceEffectDuration, //SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK = 234
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_DISPEL_RESIST = 235
&Aura::SpellAuraVehiclePassenger, //SPELL_AURA_CONTROL_VEHICLE = 236
&Aura::SpellAuraModSpellDamageFromAP, //SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER = 237
&Aura::SpellAuraModSpellHealingFromAP, //SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER = 238
&Aura::SpellAuraModScale, //SPELL_AURA_MOD_SCALE_2 = 239
&Aura::SpellAuraExpertise, //SPELL_AURA_MOD_EXPERTISE = 240
&Aura::SpellAuraForceMoveFoward, //SPELL_AURA_FORCE_MOVE_FORWARD = 241
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_SPELL_DAMAGE_FROM_HEALING = 242
&Aura::SpellAuraModFaction, //SPELL_AURA_MOD_FACTION = 243
&Aura::SpellAuraComprehendLanguage, //SPELL_AURA_COMPREHEND_LANGUAGE = 244
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL = 245
&Aura::SpellAuraReduceEffectDuration, //SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK = 246
&Aura::SpellAuraNULL, //SPELL_AURA_CLONE_CASTER = 247
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_COMBAT_RESULT_CHANCE = 248
&Aura::SpellAuraConvertRune, //SPELL_AURA_CONVERT_RUNE = 249
&Aura::SpellAuraModIncreaseHealth, //SPELL_AURA_MOD_INCREASE_HEALTH_2 = 250
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_ENEMY_DODGE = 251
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_SPEED_SLOW_ALL = 252
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_BLOCK_CRIT_CHANCE = 253
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_DISARM_OFFHAND = 254
&Aura::SpellAuraModDamageTakenByMechPCT, //SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT = 255
&Aura::SpellAuraNoReagent, //SPELL_AURA_NO_REAGENT_USE = 256
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_TARGET_RESIST_BY_SPELL_CLASS = 257
&Aura::SpellAuraNULL, // = 258
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_HOT_PCT = 259
&Aura::SpellAuraNULL, //SPELL_AURA_SCREEN_EFFECT = 260
&Aura::SpellAuraSetPhase, //SPELL_AURA_PHASE = 261
&Aura::SpellAuraSkipCanCastCheck, //SPELL_AURA_ABILITY_IGNORE_AURASTATE = 262
&Aura::SpellAuraCastFilter, //SPELL_AURA_ALLOW_ONLY_ABILITY = 263
&Aura::SpellAuraNULL, // = 264
&Aura::SpellAuraNULL, // = 265
&Aura::SpellAuraNULL, // = 266
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL = 267
&Aura::SpellAuraIncreaseAPByAttribute, //SPELL_AURA_MOD_ATTACK_POWER_OF_STAT_PERCENT = 268
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_IGNORE_TARGET_RESIST = 269
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST = 270
&Aura::SpellAuraModDamageTakenPctPerCaster, //SPELL_AURA_MOD_DAMAGE_FROM_CASTER = 271
&Aura::SpellAuraNULL, //SPELL_AURA_IGNORE_MELEE_RESET = 272
&Aura::SpellAuraNULL, //SPELL_AURA_X_RAY = 273
&Aura::SpellAuraRequireNoAmmo, //SPELL_AURA_ABILITY_CONSUME_NO_AMMO = 274
&Aura::SpellAuraSkipCanCastCheck, //SPELL_AURA_MOD_IGNORE_SHAPESHIFT = 275
&Aura::SpellAuraNULL, // = 276
&Aura::SpellAuraRedirectThreat, //SPELL_AURA_MOD_MAX_AFFECTED_TARGETS = 277
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_DISARM_RANGED = 278
&Aura::SpellAuraNULL, //SPELL_AURA_INITIALIZE_IMAGES = 279
&Aura::SpellAuraModIgnoreArmorPct, //SPELL_AURA_MOD_ARMOR_PENETRATION_PCT = 280
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_HONOR_GAIN_PCT = 281
&Aura::SpellAuraModBaseHealth, //SPELL_AURA_MOD_BASE_HEALTH_PCT = 282
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_HEALING_RECEIVED = 283
&Aura::SpellAuraNULL, //SPELL_AURA_LINKED = 284
&Aura::SpellAuraModAttackPowerByArmor, //SPELL_AURA_MOD_ATTACK_POWER_OF_ARMOR = 285
&Aura::SpellAuraNULL, //SPELL_AURA_ABILITY_PERIODIC_CRIT = 286
&Aura::SpellAuraReflectInfront, //SPELL_AURA_DEFLECT_SPELLS = 287
&Aura::SpellAuraNULL, //SPELL_AURA_IGNORE_HIT_DIRECTION = 288
&Aura::SpellAuraNULL, // = 289
&Aura::SpellAuraModCritChanceAll, //SPELL_AURA_MOD_CRIT_PCT = 290
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_XP_QUEST_PCT = 291
&Aura::SpellAuraOpenStable, //SPELL_AURA_OPEN_STABLE = 292
&Aura::SpellAuraNULL, //SPELL_AURA_OVERRIDE_SPELLS = 293
&Aura::SpellAuraNULL, //SPELL_AURA_PREVENT_REGENERATE_POWER = 294
&Aura::SpellAuraNULL, // = 295
&Aura::SpellAuraNULL, //SPELL_AURA_SET_VEHICLE_ID = 296
&Aura::SpellAuraNULL, //SPELL_AURA_BLOCK_SPELL_FAMILY = 297
&Aura::SpellAuraNULL, //SPELL_AURA_STRANGULATE = 298
&Aura::SpellAuraNULL, // = 299
&Aura::SpellAuraNULL, //SPELL_AURA_SHARE_DAMAGE_PCT = 300
&Aura::SpellAuraNULL, //SPELL_AURA_SCHOOL_HEAL_ABSORB = 301
&Aura::SpellAuraNULL, // = 302
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE = 303
&Aura::SpellAuraFakeInebriation, //SPELL_AURA_MOD_FAKE_INEBRIATE = 304
&Aura::SpellAuraModWalkSpeed, //SPELL_AURA_MOD_MINIMUM_SPEED = 305
&Aura::SpellAuraNULL, // = 306
&Aura::SpellAuraNULL, //SPELL_AURA_HEAL_ABSORB_TEST = 307
&Aura::SpellAuraNULL, // = 308
&Aura::SpellAuraNULL, // = 309
&Aura::SpellAuraNULL, //SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE = 310
&Aura::SpellAuraNULL, // = 311
&Aura::SpellAuraNULL, // = 312
&Aura::SpellAuraNULL, // = 313
&Aura::SpellAuraPreventResurrection, //SPELL_AURA_PREVENT_RESSURECTION = 314
&Aura::SpellAuraNULL, //SPELL_AURA_UNDERWATER_WALKING = 315
&Aura::SpellAuraNULL, //SPELL_AURA_PERIODIC_HASTE = 316
&Aura::SpellAuraNULL, // = 317
&Aura::SpellAuraNULL, // = 318
&Aura::SpellAuraNULL, // = 319
&Aura::SpellAuraNULL, // = 320
&Aura::SpellAuraNULL, // = 321
&Aura::SpellAuraNULL, // = 322
&Aura::SpellAuraNULL, // = 323
&Aura::SpellAuraNULL, // = 324
&Aura::SpellAuraNULL, // = 325
&Aura::SpellAuraNULL, // = 326
&Aura::SpellAuraNULL, // = 327
&Aura::SpellAuraNULL, // = 328
&Aura::SpellAuraNULL, // = 329
&Aura::SpellAuraNULL, // = 330
&Aura::SpellAuraNULL, // = 331
&Aura::SpellAuraNULL, // = 332
&Aura::SpellAuraNULL, // = 333
&Aura::SpellAuraNULL, // = 334
&Aura::SpellAuraNULL, // = 335
&Aura::SpellAuraNULL, // = 336
&Aura::SpellAuraNULL, // = 337
&Aura::SpellAuraNULL, // = 338
&Aura::SpellAuraNULL, // = 339
&Aura::SpellAuraNULL, // = 340
&Aura::SpellAuraNULL, // = 341
&Aura::SpellAuraNULL, // = 342
&Aura::SpellAuraNULL, // = 343
&Aura::SpellAuraNULL, // = 344
&Aura::SpellAuraNULL, // = 345
&Aura::SpellAuraNULL, // = 346
&Aura::SpellAuraNULL, // = 347
&Aura::SpellAuraNULL, // = 348
&Aura::SpellAuraNULL, // = 349
&Aura::SpellAuraNULL, // = 350
&Aura::SpellAuraNULL, // = 351
&Aura::SpellAuraNULL, // = 352
&Aura::SpellAuraNULL, // = 353
&Aura::SpellAuraNULL, // = 354
&Aura::SpellAuraNULL, // = 355
&Aura::SpellAuraNULL, // = 356
&Aura::SpellAuraNULL, // = 357
&Aura::SpellAuraNULL, // = 358
&Aura::SpellAuraNULL, // = 359
&Aura::SpellAuraNULL, // = 360
&Aura::SpellAuraNULL, // = 361
&Aura::SpellAuraNULL, // = 362
&Aura::SpellAuraNULL, // = 363
&Aura::SpellAuraNULL, // = 364
&Aura::SpellAuraNULL, // = 365
&Aura::SpellAuraNULL, // = 366
&Aura::SpellAuraNULL, // = 367
&Aura::SpellAuraNULL, // = 368
&Aura::SpellAuraNULL, // = 369
&Aura::SpellAuraNULL // = 370
};
Unit* Aura::GetUnitCaster()
{
if( m_target == NULL && m_casterGuid && m_casterGuid.getHigh() == HIGHGUID_TYPE_PLAYER)
if(Player* punit = objmgr.GetPlayer(m_casterGuid))
return punit;
if( m_target == NULL )
return NULL;
if( m_casterGuid && m_casterGuid == m_target->GetGUID() )
return m_target;
if( m_target->GetMapInstance() != NULL )
return m_target->GetMapInstance()->GetUnit( m_casterGuid );
return NULL;
}
Aura::Aura(Unit *target, SpellEntry *proto, uint16 auraFlags, uint8 auraLevel, int16 auraStackCharge, time_t expirationTime, WoWGuid casterGuid)
: m_target(target), m_spellProto(proto), m_auraFlags(auraFlags), m_auraLevel(auraLevel), m_duration(-1), m_expirationTime(0), m_casterGuid(casterGuid),
m_auraSlot(0xFF), m_applied(false), m_deleted(false), m_dispelled(false), m_castInDuel(false), m_creatureAA(false), m_areaAura(false), m_interrupted(-1),
m_positive(!proto->isNegativeSpell1())
{
m_stackSizeorProcCharges = auraStackCharge;
if(expirationTime)
{
CalculateDuration();
m_expirationTime = expirationTime;
}
m_modcount = 0;
memset(m_modList, 0, sizeof(Modifier)*3);
m_castedItemId = 0;
m_triggeredSpellId = 0;
periodic_target = 0;
}
Aura::~Aura()
{
}
void Aura::Update(uint32 diff)
{
if(m_expirationTime == 0)
return;
if(m_expirationTime <= UNIXTIME)
Remove();
}
void Aura::UpdatePreApplication()
{
CalculateDuration();
}
void Aura::CalculateDuration()
{
if(IsPassive())
return;
int32 Duration = m_spellProto->CalculateSpellDuration(m_auraLevel, 0);
if(!m_positive && !m_spellProto->isPassiveSpell())
::ApplyDiminishingReturnTimer(&Duration, m_target, GetSpellProto());
uint32 mechanic = GetMechanic();
if( m_target->IsPlayer() && mechanic < NUM_MECHANIC && Duration > 0 )
Duration *= m_target->GetMechanicDurationPctMod(mechanic);
if((m_duration = Duration) > 0)
{
m_auraFlags |= AFLAG_HAS_DURATION;
m_expirationTime = UNIXTIME+(m_duration/1000);
} else m_expirationTime = 0;
}
void Aura::Remove()
{
if( m_deleted )
return;
m_deleted = true;
if( !IsPassive() )
BuildAuraUpdate();
m_target->m_AuraInterface.OnAuraRemove(this, m_auraSlot);
ApplyModifiers( false );
// reset diminishing return timer if needed
::UnapplyDiminishingReturnTimer( m_target, m_spellProto );
Unit * m_caster = GetUnitCaster();
if (m_caster != NULL)
{
m_caster->OnAuraRemove(m_spellProto->NameHash, m_target);
if(m_spellProto->IsSpellChannelSpell() && m_caster->isCasting() && m_caster->GetSpellInterface()->GetCurrentSpellProto()->Id == m_spellProto->Id)
m_caster->GetSpellInterface()->CleanupCurrentSpell();
}
for( uint32 x = 0; x < 3; x++ )
{
if( !m_spellProto->Effect[x] )
continue;
if( m_spellProto->Effect[x] == SPELL_EFFECT_TRIGGER_SPELL && !m_spellProto->always_apply )
m_target->RemoveAura(m_spellProto->EffectTriggerSpell[x]);
}
if( m_spellProto->MechanicsType == MECHANIC_ENRAGED )
m_target->RemoveFlag(UNIT_FIELD_AURASTATE, AURASTATE_FLAG_ENRAGE );
else if( m_spellProto->Id == 642 )
{
m_target->RemoveAura( 53523 );
m_target->RemoveAura( 53524 );
}
m_target = NULL;
m_casterGuid = 0;
delete this;
}
void Aura::OnTargetChangeLevel(uint32 newLevel, uint64 targetGuid)
{
// Get our unit target so we can test against the given guid
if(m_target->GetGUID() == targetGuid)
RecalculateModBaseAmounts();
}
void Aura::AddMod(uint32 i, uint32 t, int32 a, uint32 b, int32 f, float ff )
{
if( m_modcount >= 3 || m_target == NULL || m_target->GetMechanicDispels(GetMechanicOfEffect(i)))
return;
if(i == 0) m_auraFlags |= AFLAG_EFF_INDEX_0;
else if(i == 1) m_auraFlags |= AFLAG_EFF_INDEX_1;
else if(i == 2) m_auraFlags |= AFLAG_EFF_INDEX_2;
int32 amount = a;
if(m_stackSizeorProcCharges >= 0)
amount *= m_stackSizeorProcCharges;
m_modList[m_modcount].i = i;
m_modList[m_modcount].m_type = t;
m_modList[m_modcount].m_amount = amount;
m_modList[m_modcount].m_baseAmount = a;
m_modList[m_modcount].m_miscValue[0] = m_spellProto->EffectMiscValue[i];
m_modList[m_modcount].m_miscValue[1] = m_spellProto->EffectMiscValueB[i];
m_modList[m_modcount].m_bonusAmount = b;
m_modList[m_modcount].fixed_amount = f;
m_modList[m_modcount].fixed_float_amount = ff;
m_modList[m_modcount].m_spellInfo = GetSpellProto();
CalculateBonusAmount(GetUnitCaster(), m_modcount);
m_modcount++;
}
void Aura::ResetExpirationTime()
{
if(m_expirationTime == 0 || m_duration == -1)
return;
m_expirationTime = UNIXTIME+(m_duration/1000);
}
void Aura::RemoveIfNecessary()
{
if( !m_applied )
return; // already removed
if( m_spellProto->CasterAuraState && m_target && !(m_target->GetUInt32Value(UNIT_FIELD_AURASTATE) & (uint32(1) << (m_spellProto->CasterAuraState-1)) ) )
{
ApplyModifiers(false);
return;
}
if( m_spellProto->CasterAuraStateNot && m_target && m_target->GetUInt32Value(UNIT_FIELD_AURASTATE) & (uint32(1) << (m_spellProto->CasterAuraStateNot-1)) )
{
ApplyModifiers(false);
return;
}
}
void Aura::ApplyModifiers( bool apply )
{
if(!m_applied && !apply) // Don't want to unapply modifiers if they haven't been applied
return;
m_applied = apply;
if( apply && m_spellProto->CasterAuraState && m_target && !(m_target->GetUInt32Value(UNIT_FIELD_AURASTATE) & (uint32(1) << (m_spellProto->CasterAuraState - 1) ) ) )
{
m_applied = false;
return;
}
if( apply && m_spellProto->CasterAuraStateNot && m_target && m_target->GetUInt32Value(UNIT_FIELD_AURASTATE) & (uint32(1) << (m_spellProto->CasterAuraStateNot - 1) ) )
{
m_applied = false;
return;
}
if(m_spellProto->buffIndex > BUFF_PALADIN_SEAL_START && m_spellProto->buffIndex < BUFF_PALADIN_HAND_START)
{
if(apply && !m_target->HasFlag(UNIT_FIELD_AURASTATE, AURASTATE_FLAG_JUDGEMENT))
m_target->SetFlag(UNIT_FIELD_AURASTATE, AURASTATE_FLAG_JUDGEMENT);
else if(apply == false)
m_target->RemoveFlag(UNIT_FIELD_AURASTATE, AURASTATE_FLAG_JUDGEMENT);
}
for( uint32 x = 0; x < m_modcount; x++ )
{
mod = &m_modList[x];
if(mod->m_type >= SPELL_AURA_TOTAL)
{
sLog.Debug( "Aura","Unknown Aura id %d in spell %u", uint32(mod->m_type), GetSpellId());
continue;
}
m_target->m_AuraInterface.UpdateModifier(GetAuraSlot(), x, mod, apply);
sLog.Debug( "Aura","Known Aura id %d, value %d in spell %u", uint32(mod->m_type), uint32(mod->m_amount), GetSpellId());
(*this.*SpellAuraHandler[mod->m_type])(apply);
}
}
void Aura::UpdateModifiers( )
{
for( uint32 x = 0; x < m_modcount; x++ )
{
mod = &m_modList[x];
if(mod->m_type >= SPELL_AURA_TOTAL)
{
sLog.Debug( "Aura","Unknown Aura id %d", (uint32)mod->m_type);
continue;
}
m_target->m_AuraInterface.UpdateModifier(GetAuraSlot(), x, mod, m_applied);
sLog.Debug( "Aura","Updating Aura modifiers target = %u, slot = %u, Spell Aura id = %u, SpellId = %u, i = %u, duration = %i, damage = %d",
m_target->GetLowGUID(), m_auraSlot, mod->m_type, m_spellProto->Id, mod->i, GetDuration(),mod->m_amount);
}
}
bool Aura::AddAuraVisual()
{
uint8 slot = m_target->m_AuraInterface.GetFreeSlot(IsPositive());
if (slot == 0xFF)
return false;
m_auraSlot = slot;
BuildAuraUpdate();
return true;
}
void Aura::BuildAuraUpdate()
{
if( m_target == NULL || IsPassive() )
return;
WorldPacket data(SMSG_AURA_UPDATE, 50);
FastGUIDPack(data, m_target->GetGUID());
BuildAuraUpdatePacket(&data);
m_target->SendMessageToSet(&data, true);
}
void Aura::BuildAuraUpdatePacket(WorldPacket *data)
{
*data << uint8(m_auraSlot);
if(m_deleted || m_stackSizeorProcCharges == 0)
{
*data << uint32(0);
return;
}
uint16 flags = GetAuraFlags();
*data << uint32(GetSpellProto()->Id) << uint16(flags);
*data << uint8(GetAuraLevel());
*data << uint8(m_stackSizeorProcCharges & 0xFF);
if(!(flags & AFLAG_NOT_GUID))
*data << GetCasterGUID().asPacked();
if( flags & AFLAG_HAS_DURATION )
{
*data << GetDuration();
*data << GetMSTimeLeft();
}
if (flags & AFLAG_EFF_AMOUNT_SEND)
{
for (uint8 i = 0; i < 3; ++i)
{
if (flags & 1<<i)
{
Modifier *mod = GetMod(i);
*data << uint32(mod ? mod->m_amount : 0);
}
}
}
}
void Aura::EventRelocateRandomTarget()
{
Unit * m_caster = GetUnitCaster();
if( m_caster == NULL || !m_caster->IsPlayer() || m_caster->isDead() )
return;
// Ok, let's do it. :D
std::set<Unit* > enemies;
// Can't do anything w/o a target
if( !enemies.size() )
return;
uint32 random = RandomUInt(uint32(enemies.size()) - 1);
std::set<Unit* >::iterator it2 = enemies.begin();
while( random-- )
it2++;
Unit* pTarget = (*it2);
if(pTarget == NULL)
return; // In case I did something horribly wrong.
float ang = pTarget->GetOrientation();
// avoid teleporting into the model on scaled models
const static float killingspree_distance = 1.6f * GetDBCScale( dbcCreatureDisplayInfo.LookupEntry( pTarget->GetUInt32Value(UNIT_FIELD_DISPLAYID)));
float new_x = pTarget->GetPositionX() - (killingspree_distance * cosf(ang));
float new_y = pTarget->GetPositionY() - (killingspree_distance * sinf(ang));
float new_z = pTarget->GetMapInstance()->GetWalkableHeight(pTarget, new_x, new_y, pTarget->GetPositionZ());
castPtr<Player>(m_caster)->SafeTeleport( pTarget->GetMapId(), pTarget->GetInstanceID(), new_x, new_y, new_z, pTarget->GetOrientation() );
// void Unit::Strike( Unit pVictim, uint32 weapon_damage_type, SpellEntry* ability, uint32 exclusive_damage, bool disable_proc, bool skip_hit_check, bool proc_extrahit = false )
castPtr<Player>(m_caster)->Strike( pTarget, MELEE, NULL, 0, false, false, true );
castPtr<Player>(m_caster)->Strike( pTarget, OFFHAND, NULL, 0, false, false, true );
}
//------------------------- Aura Effects -----------------------------
void Aura::SpellAuraNULL(bool apply)
{
sLog.Debug( "Aura","Unknown Aura id %d in spell %u", uint32(mod->m_type), GetSpellId());
}
void Aura::SpellAuraUtilized(bool apply)
{
// We do nothing here
}
void Aura::SpellAuraBindSight(bool apply)
{
Unit * m_caster = GetUnitCaster();
if(m_caster != NULL || !m_caster->IsPlayer())
return;
if(apply)
m_caster->SetUInt64Value(PLAYER_FARSIGHT, m_target->GetGUID());
else m_caster->SetUInt64Value(PLAYER_FARSIGHT, 0 );
}
void Aura::SpellAuraModPossess(bool apply)
{
}
void Aura::SpellAuraPeriodicDamage(bool apply)
{
}
void Aura::EventPeriodicDamage(uint32 amount)
{
}
void Aura::SpellAuraDummy(bool apply)
{
}
void Aura::SpellAuraModConfuse(bool apply)
{
}
void Aura::SpellAuraModCharm(bool apply)
{
}
void Aura::SpellAuraModFear(bool apply)
{
}
void Aura::SpellAuraPeriodicHeal( bool apply )
{
Unit * m_caster = GetUnitCaster();
if(m_caster == NULL)
return;
}
void Aura::EventPeriodicHeal( uint32 amount )
{
int32 add = amount; // IMPORTANT: target heals himself, but the packet says the caster does it. This is important, to allow for casters to log out and players still get healed.
uint32 overheal = m_target->Heal(m_target, GetSpellId(), add, true);
SendPeriodicAuraLog( m_casterGuid, m_target, GetSpellProto(), add, 0, overheal, FLAG_PERIODIC_HEAL );
if( m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_ON_STAND_UP )
m_target->Emote( EMOTE_ONESHOT_EAT );
}
void Aura::SpellAuraModAttackSpeed(bool apply)
{
}
void Aura::SpellAuraModThreatGenerated(bool apply)
{
}
void Aura::SpellAuraModTaunt(bool apply)
{
}
void Aura::SpellAuraModStun(bool apply)
{
}
void Aura::SpellAuraModDamageDone(bool apply)
{
}
void Aura::SpellAuraModDamageTaken(bool apply)
{
}
void Aura::SpellAuraDamageShield(bool apply)
{
// Todo:PROC
}
void Aura::SpellAuraModStealth(bool apply)
{
}
void Aura::SpellAuraModDetect(bool apply)
{
}
void Aura::SpellAuraModInvisibility(bool apply)
{
m_target->UpdateVisibility();
}
void Aura::SpellAuraModInvisibilityDetection(bool apply)
{
//Always Positive
assert(mod->m_miscValue[0] < INVIS_FLAG_TOTAL);
if(apply)
m_target->m_invisDetect[mod->m_miscValue[0]] += mod->m_amount;
else m_target->m_invisDetect[mod->m_miscValue[0]] -= mod->m_amount;
if(m_target->IsPlayer())
castPtr<Player>( m_target )->UpdateVisibility();
}
void Aura::SpellAuraModTotalHealthRegenPct(bool apply)
{
}
void Aura::EventPeriodicHealPct(float RegenPct)
{
Unit* m_caster = GetUnitCaster();
if(m_caster == NULL || !m_target->isAlive())
return;
uint32 add = float2int32(m_target->GetUInt32Value(UNIT_FIELD_MAXHEALTH) * (RegenPct / 100.0f));
uint32 overheal = m_caster->Heal(m_target, GetSpellId(), add, true);
SendPeriodicAuraLog( m_casterGuid, m_target, GetSpellProto(), add, 0, overheal, FLAG_PERIODIC_HEAL );
if(m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_ON_STAND_UP)
m_target->Emote(EMOTE_ONESHOT_EAT);
}
void Aura::SpellAuraModTotalManaRegenPct(bool apply)
{
}
void Aura::EventPeriodicManaPct(float RegenPct)
{
if(!m_target->isAlive())
return;
uint32 manaMax = m_target->GetMaxPower(POWER_TYPE_MANA);
if(manaMax == 0)
return;
uint32 add = float2int32(manaMax * (RegenPct / 100.0f));
uint32 newMana = m_target->GetPower(POWER_TYPE_MANA) + add;
m_target->SetPower(POWER_TYPE_MANA, newMana <= manaMax ? newMana : manaMax);
SendPeriodicAuraLog(m_casterGuid, m_target, m_spellProto, add, 0, 0, FLAG_PERIODIC_ENERGIZE);
if(m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_ON_STAND_UP)
m_target->Emote(EMOTE_ONESHOT_EAT);
m_target->SendPowerUpdate();
}
void Aura::SpellAuraPeriodicTriggerSpell(bool apply)
{
}
void Aura::EventPeriodicTriggerSpell(SpellEntry* spellInfo, bool overridevalues, int32 overridevalue)
{
/*if(overridevalues)
for(uint32 i = 0; i < 3; ++i)
spell->forced_basepoints[i] = overridevalue;*/
SpellCastTargets targets;
if(Spell* spell = new Spell(m_target, spellInfo))
{
spell->GenerateTargets(&targets);
if(spell->prepare(&targets, true) != SPELL_CANCAST_OK)
Remove();
}
}
void Aura::SpellAuraPeriodicEnergize(bool apply)
{
}
void Aura::EventPeriodicEnergize(uint32 amount,uint32 type)
{
m_target->Energize(m_target, m_spellProto->Id, amount, type );
if((m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_ON_STAND_UP) && type == 0)
m_target->Emote(EMOTE_ONESHOT_EAT);
m_target->SendPowerUpdate();
}
void Aura::SpellAuraModPacify(bool apply)
{
}
void Aura::SpellAuraModRoot(bool apply)
{
}
void Aura::SpellAuraModSilence(bool apply)
{
if(apply)
{
m_target->m_silenced++;
m_target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
// remove the current spell (for channelers)
/*if(m_target->GetCurrentSpell() && m_target->GetGUID() != m_casterGuid &&
m_target->GetCurrentSpell()->getState() == SPELL_STATE_CASTING )
{
m_target->GetCurrentSpell()->cancel();
m_target->SetCurrentSpell(NULL);
}*/
}
else
{
m_target->m_silenced--;
if(m_target->m_silenced == 0)
{
m_target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED);
}
}
}
void Aura::SpellAuraReflectSpells(bool apply)
{
// Todo:PROC
}
void Aura::SpellAuraModStat(bool apply)
{
}
void Aura::SpellAuraModSkill(bool apply)
{
}
void Aura::SpellAuraModIncreaseSpeed(bool apply)
{
}
void Aura::SpellAuraModIncreaseMountedSpeed(bool apply)
{
}
void Aura::SpellAuraModCreatureRangedAttackPower(bool apply)
{
}
void Aura::SpellAuraModDecreaseSpeed(bool apply)
{
}
void Aura::UpdateAuraModDecreaseSpeed()
{
}
void Aura::SpellAuraModIncreaseHealth(bool apply)
{
}
void Aura::SpellAuraModIncreaseEnergy(bool apply)
{
}
void Aura::SpellAuraModShapeshift(bool apply)
{
if( !m_target->IsPlayer())
return;
Player *p = castPtr<Player>(m_target);
uint32 modelId = p->GenerateShapeshiftModelId(mod->m_miscValue[0]);
if( apply )
{
if( modelId != 0 )
{
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, modelId );
}
p->SetShapeShift( mod->m_miscValue[0] );
}
else
{
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, m_target->GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID));
p->m_ShapeShifted = 0;
p->SetShapeShift(0);
if(m_target->HasAura(52610))
m_target->RemoveAura(52610);
}
}
void Aura::SpellAuraModEffectImmunity(bool apply)
{
}
void Aura::SpellAuraModStateImmunity(bool apply)
{
//%50 chance to dispel 1 magic effect on target
//23922
}
void Aura::SpellAuraModSchoolImmunity(bool apply)
{
}
void Aura::SpellAuraModDmgImmunity(bool apply)
{
}
void Aura::SpellAuraModDispelImmunity(bool apply)
{
assert(mod->m_miscValue[0] < 10);
if(apply)
m_target->m_AuraInterface.RemoveAllAurasWithDispelType((uint32)mod->m_miscValue[0]);
}
void Aura::SpellAuraProcTriggerSpell(bool apply)
{
// Todo:PROC
}
void Aura::SpellAuraProcTriggerDamage(bool apply)
{
// Todo:PROC
}
void Aura::SpellAuraTrackCreatures(bool apply)
{
if(m_target->IsPlayer())
{
if(apply)
{
if(castPtr<Player>( m_target )->TrackingSpell)
m_target->RemoveAura( castPtr<Player>( m_target )->TrackingSpell);
m_target->SetUInt32Value(PLAYER_TRACK_CREATURES,(uint32)1<< (mod->m_miscValue[0]-1));
castPtr<Player>( m_target )->TrackingSpell = GetSpellId();
}
else
{
castPtr<Player>( m_target )->TrackingSpell = 0;
m_target->SetUInt32Value(PLAYER_TRACK_CREATURES,0);
}
}
}
void Aura::SpellAuraTrackResources(bool apply)
{
if(m_target->IsPlayer())
{
if(apply)
{
if(castPtr<Player>( m_target )->TrackingSpell)
m_target->RemoveAura(castPtr<Player>( m_target )->TrackingSpell);
m_target->SetUInt32Value(PLAYER_TRACK_RESOURCES,(uint32)1<< (mod->m_miscValue[0]-1));
castPtr<Player>( m_target )->TrackingSpell = GetSpellId();
}
else
{
castPtr<Player>( m_target )->TrackingSpell = 0;
m_target->SetUInt32Value(PLAYER_TRACK_RESOURCES,0);
}
}
}
void Aura::SpellAuraModParrySkill(bool apply)
{
}
void Aura::SpellAuraModParryPerc(bool apply)
{
}
void Aura::SpellAuraModDodgeSkill(bool apply)
{
}
void Aura::SpellAuraModDodgePerc(bool apply)
{
}
void Aura::SpellAuraModBlockSkill(bool apply)
{
}
void Aura::SpellAuraModBlockPerc(bool apply)
{
}
void Aura::SpellAuraModCritPerc(bool apply)
{
}
void Aura::SpellAuraPeriodicLeech(bool apply)
{
}
void Aura::EventPeriodicLeech(uint32 amount, SpellEntry* sp)
{
Unit * m_caster = GetUnitCaster();
if( m_caster == NULL || m_target == NULL || !m_target->isAlive() || !m_caster->isAlive() )
return;
if( sp->NameHash == SPELL_HASH_DRAIN_LIFE && m_caster->HasDummyAura(SPELL_HASH_DEATH_S_EMBRACE) && m_caster->GetHealthPct() <= 20 )
amount *= 1.3f;
amount = m_caster->GetSpellBonusDamage(m_target, sp, mod->i, amount, false);
uint32 Amount = std::min(amount, m_target->GetUInt32Value( UNIT_FIELD_HEALTH ));
SendPeriodicAuraLog(m_casterGuid, m_target, sp, Amount, -1, 0, (uint32)FLAG_PERIODIC_DAMAGE);
//deal damage before we add healing bonus to damage
m_caster->DealDamage(m_target, Amount, 0, 0, sp->Id, true);
if(sp)
{
float coef = sp->EffectValueMultiplier[mod->i]; // how much health is restored per damage dealt
m_caster->SM_FFValue(SMT_MULTIPLE_VALUE, &coef, sp->SpellGroupType);
m_caster->SM_PFValue(SMT_MULTIPLE_VALUE, &coef, sp->SpellGroupType);
Amount = float2int32((float)Amount * coef);
}
uint32 newHealth = float2int32(m_caster->GetUInt32Value(UNIT_FIELD_HEALTH) + Amount);
uint32 mh = m_caster->GetUInt32Value(UNIT_FIELD_MAXHEALTH);
if(newHealth <= mh)
m_caster->SetUInt32Value(UNIT_FIELD_HEALTH, newHealth);
else
m_caster->SetUInt32Value(UNIT_FIELD_HEALTH, mh);
SendPeriodicAuraLog(m_casterGuid, m_caster, sp, Amount, -1, 0, (uint32)FLAG_PERIODIC_HEAL);
}
void Aura::SpellAuraModHitChance(bool apply)
{
}
void Aura::SpellAuraModSpellHitChance(bool apply)
{
}
void Aura::SpellAuraTransform(bool apply)
{
uint32 displayId = 0;
CreatureData* data = sCreatureDataMgr.GetCreatureData(mod->m_miscValue[0]);
if(data == NULL)
sLog.Debug("Aura","SpellAuraTransform cannot find CreatureData for id %d",mod->m_miscValue[0]);
else displayId = data->displayInfo[0];
Unit * m_caster = GetUnitCaster();
switch( m_spellProto->Id )
{
case 47585: // Dispersion
{
if( apply && m_caster != NULL )
{
SpellEntry *spellInfo = dbcSpell.LookupEntry( 60069 );
if(!spellInfo)
return;
SpellCastTargets targets(m_target->GetGUID());
if(Spell* spell = new Spell(m_target, spellInfo))
spell->prepare(&targets, true);
}
}break;
case 20584://wisp
{
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, apply ? 10045:m_target->GetUInt32Value( UNIT_FIELD_NATIVEDISPLAYID ) );
}break;
case 30167: // Red Ogre Costume
{
if( apply )
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, 11549 );
else
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, m_target->GetUInt32Value( UNIT_FIELD_NATIVEDISPLAYID ) );
}break;
case 41301: // Time-Lost Figurine
{
if( apply )
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, 18628 );
else
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, m_target->GetUInt32Value( UNIT_FIELD_NATIVEDISPLAYID ) );
}break;
case 16739: // Orb of Deception
{
if( apply )
{
switch(m_target->getRace())
{
case RACE_ORC:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10139);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10140);
}break;
case RACE_TAUREN:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10136);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10147);
}break;
case RACE_TROLL:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10135);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10134);
}break;
case RACE_UNDEAD:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10146);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10145);
}break;
case RACE_BLOODELF:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 17829);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 17830);
}break;
case RACE_GNOME:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10148);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10149);
}break;
case RACE_DWARF:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10141);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10142);
}break;
case RACE_HUMAN:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10137);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10138);
}break;
case RACE_NIGHTELF:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10143);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 10144);
}break;
case RACE_DRAENEI:
{
if( m_target->getGender() == 0 )
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 17827);
else
m_target->SetUInt32Value(UNIT_FIELD_DISPLAYID, 17828);
}break;
default:
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, m_target->GetUInt32Value( UNIT_FIELD_NATIVEDISPLAYID ) );
}
}
}break;
case 42365: // murloc costume
m_target->SetUInt32Value( UNIT_FIELD_DISPLAYID, apply ? 21723 : m_target->GetUInt32Value( UNIT_FIELD_NATIVEDISPLAYID ) );
break;
case 19937:
{
if (apply)
{
// TODO: Sniff the spell / item, we need to know the real displayID
// guessed this may not be correct
// human = 7820
// dwarf = 7819
// halfling = 7818
// maybe 7842 as its from a lesser npc
m_target->SetUInt32Value (UNIT_FIELD_DISPLAYID, 7842);
}
else
{
m_target->SetUInt32Value (UNIT_FIELD_DISPLAYID, m_target->GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID));
}
}break;
default:
{
if(!displayId) return;
if (apply)
{
m_target->SetUInt32Value (UNIT_FIELD_DISPLAYID, displayId);
}
else
{
m_target->SetUInt32Value (UNIT_FIELD_DISPLAYID, m_target->GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID));
}
}break;
};
}
void Aura::SpellAuraModSpellCritChance(bool apply)
{
}
void Aura::SpellAuraIncreaseSwimSpeed(bool apply)
{
}
void Aura::SpellAuraModCratureDmgDone(bool apply)
{
}
void Aura::SpellAuraPacifySilence(bool apply)
{
}
void Aura::SpellAuraModScale(bool apply)
{
float current = m_target->GetFloatValue(OBJECT_FIELD_SCALE_X);
float delta = mod->m_amount/100.0f;
m_target->SetFloatValue(OBJECT_FIELD_SCALE_X, apply ? (current+current*delta) : current/(1.0f+delta));
}
void Aura::SpellAuraPeriodicHealthFunnel(bool apply)
{
}
void Aura::EventPeriodicHealthFunnel(uint32 amount)
{
Unit * m_caster = GetUnitCaster();
if( m_caster == NULL || m_target == NULL || !m_target->isAlive() || !m_caster->isAlive())
return;
if(m_target->isAlive() && m_caster->isAlive())
{
m_caster->DealDamage(m_target, amount, 0, 0, GetSpellId(),true);
uint32 newHealth = m_caster->GetUInt32Value(UNIT_FIELD_HEALTH) + 1000;
uint32 mh = m_caster->GetUInt32Value(UNIT_FIELD_MAXHEALTH);
if(newHealth <= mh)
m_caster->SetUInt32Value(UNIT_FIELD_HEALTH, newHealth);
else
m_caster->SetUInt32Value(UNIT_FIELD_HEALTH, mh);
SendPeriodicAuraLog(m_casterGuid, m_target, m_spellProto, amount, -1, 0, (uint32)FLAG_PERIODIC_LEECH);
}
}
void Aura::SpellAuraPeriodicManaLeech(bool apply)
{
}
void Aura::EventPeriodicManaLeech(uint32 amount)
{
Unit * m_caster = GetUnitCaster();
if( m_caster == NULL || m_target == NULL || !m_target->isAlive() || !m_caster->isAlive())
return;
int32 amt = amount;
// Drained amount should be reduced by resilence
if(m_target->IsPlayer())
{
float amt_reduction_pct = 2.2f * castPtr<Player>(m_target)->CalcRating( PLAYER_RATING_MODIFIER_SPELL_RESILIENCE ) / 100.0f;
if( amt_reduction_pct > 0.33f ) amt_reduction_pct = 0.33f; // 3.0.3
amt = float2int32( amt - (amt * amt_reduction_pct) );
}
float coef = m_spellProto->EffectValueMultiplier[mod->i] > 0 ? m_spellProto->EffectValueMultiplier[mod->i] : 1; // how much mana is restored per mana leeched
m_caster->SM_FFValue(SMT_MULTIPLE_VALUE, &coef, m_spellProto->SpellGroupType);
m_caster->SM_PFValue(SMT_MULTIPLE_VALUE, &coef, m_spellProto->SpellGroupType);
amt = float2int32((float)amt * coef);
uint32 cm = m_caster->GetPower(POWER_TYPE_MANA) + amt;
uint32 mm = m_caster->GetMaxPower(POWER_TYPE_MANA);
if(cm <= mm)
{
m_caster->SetPower(POWER_TYPE_MANA, cm);
SendPeriodicAuraLog(m_casterGuid, m_target, m_spellProto, amt, 0, 0, FLAG_PERIODIC_LEECH);
}
else
{
m_caster->SetPower(POWER_TYPE_MANA, mm);
SendPeriodicAuraLog(m_casterGuid, m_target, m_spellProto, mm - cm, 0, 0, FLAG_PERIODIC_LEECH);
}
m_caster->SendPowerUpdate();
}
void Aura::SpellAuraModCastingSpeed(bool apply)
{
}
void Aura::SpellAuraFeignDeath(bool apply)
{
if( m_target->IsPlayer() )
{
Player* pTarget = castPtr<Player>( m_target );
WorldPacket data(50);
if( apply )
{
pTarget->EventAttackStop();
pTarget->SetFlag( UNIT_FIELD_FLAGS_2, 1 );
pTarget->SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_FEIGN_DEATH );
//pTarget->SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_DEAD );
pTarget->SetFlag( UNIT_DYNAMIC_FLAGS, U_DYN_FLAG_DEAD );
//pTarget->SetUInt32Value( UNIT_NPC_EMOTESTATE, EMOTE_STATE_DEAD );
data.SetOpcode( SMSG_START_MIRROR_TIMER );
data << uint32( 2 ); // type
data << int32( GetDuration() );
data << int32( GetDuration() );
data << uint32( 0xFFFFFFFF );
data << uint8( 0 );
data << uint32( m_spellProto->Id ); // ???
pTarget->GetSession()->SendPacket( &data );
data.Initialize(SMSG_CLEAR_TARGET);
data << pTarget->GetGUID();
//now get rid of mobs agro. pTarget->CombatStatus.AttackersForgetHate() - this works only for already attacking mobs
/*WorldObject::InRangeArray::iterator itr, itr2;
for(itr = pTarget->GetInRangeUnitSetBegin(); itr != pTarget->GetInRangeUnitSetEnd();)
{
itr2 = itr++;
Unit* pObject = pTarget->GetInRangeObject<Unit>(*itr2);
if(pObject->isAlive())
{
//if this is player and targeting us then we interrupt cast
if(pObject->IsPlayer())
{ //if player has selection on us
if( castPtr<Player>(pObject)->GetSelection() == pTarget->GetGUID())
{
castPtr<Player>(pObject)->SetSelection(0); //lose selection
castPtr<Player>(pObject)->SetUInt64Value(UNIT_FIELD_TARGET, 0);
}
castPtr<Player>( pObject )->GetSession()->SendPacket( &data );
}
}
}*/
pTarget->SetDeathState(ALIVE);
}
else
{
pTarget->RemoveFlag(UNIT_FIELD_FLAGS_2, 1);
pTarget->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FEIGN_DEATH);
pTarget->RemoveFlag(UNIT_DYNAMIC_FLAGS, U_DYN_FLAG_DEAD);
//pTarget->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DEAD);
//pTarget->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0);
data.SetOpcode(SMSG_STOP_MIRROR_TIMER);
data << uint32(2);
pTarget->GetSession()->SendPacket(&data);
}
}
}
void Aura::SpellAuraModDisarm(bool apply)
{
if(apply)
{
if( m_target->IsPlayer() && castPtr<Player>(m_target)->IsInFeralForm())
return;
m_target->disarmed = true;
m_target->disarmedShield = (m_spellProto->NameHash == SPELL_HASH_DISMANTLE);
m_target->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED);
}
else
{
m_target->disarmed = false;
if( m_spellProto->NameHash == SPELL_HASH_DISMANTLE )
m_target->disarmedShield = false;
m_target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED);
}
}
void Aura::SpellAuraModStalked(bool apply)
{
}
void Aura::SpellAuraSchoolAbsorb(bool apply)
{
if(apply)
mod->fixed_amount = mod->m_amount;
}
void Aura::SpellAuraModSpellCritChanceSchool(bool apply)
{
}
void Aura::SpellAuraModPowerCost(bool apply)
{
}
void Aura::SpellAuraModPowerCostSchool(bool apply)
{
}
void Aura::SpellAuraReflectSpellsSchool(bool apply)
{
// Todo:PROC
}
void Aura::SpellAuraModLanguage(bool apply)
{
}
void Aura::SpellAuraAddFarSight(bool apply)
{
Unit * m_caster = GetUnitCaster();
if(m_caster == NULL || !m_caster->IsPlayer())
return;
if(apply)
{
float sightX = m_caster->GetPositionX() + 100.0f;
float sightY = m_caster->GetPositionY() + 100.0f;
m_caster->SetUInt64Value(PLAYER_FARSIGHT, mod->m_miscValue[0]);
m_caster->GetMapInstance()->ChangeFarsightLocation(castPtr<Player>(m_caster), sightX, sightY, true);
}
else
{
m_caster->SetUInt64Value(PLAYER_FARSIGHT, 0);
m_caster->GetMapInstance()->ChangeFarsightLocation(castPtr<Player>(m_caster), 0, 0, false);
}
}
void Aura::SpellAuraMechanicImmunity(bool apply)
{
if( m_target->IsPlayer())
{
switch(m_spellProto->Id)
{
case 49039:
{
if(apply && !m_target->HasAura(50397))
GetUnitCaster()->GetSpellInterface()->TriggerSpell(dbcSpell.LookupEntry(50397), m_target);
}
}
}
if(apply)
{
if(mod->m_miscValue[0] != MECHANIC_HEALING && mod->m_miscValue[0] != MECHANIC_INVULNARABLE && mod->m_miscValue[0] != MECHANIC_SHIELDED) // dont remove bandages, Power Word and protection effect
{
/* Supa's test run of Unit::RemoveAllAurasByMechanic */
if( m_target ) // just to be sure?
{
m_target->m_AuraInterface.RemoveAllAurasByMechanic( (uint32)mod->m_miscValue[0] , -1 , false );
}
if(m_spellProto->Id == 42292 || m_spellProto->Id == 59752) // PvP Trinket
{
// insignia of the A/H
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_CHARMED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_DISORIENTED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_FLEEING, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_ROOTED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_PACIFIED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_ASLEEP, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_STUNNED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_INCAPACIPATED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_POLYMORPHED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_SEDUCED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_FROZEN, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_ENSNARED, -1, false);
m_target->m_AuraInterface.RemoveAllAurasByMechanic(MECHANIC_BANISHED, -1, false);
}
}
}
}
void Aura::SpellAuraMounted(bool apply)
{
if(!m_target->IsPlayer())
return;
Player* pPlayer = castPtr<Player>(m_target);
if(apply)
{
TRIGGER_INSTANCE_EVENT( pPlayer->GetMapInstance(), OnPlayerMount )( pPlayer );
pPlayer->m_AuraInterface.RemoveAllAurasByInterruptFlagButSkip(AURA_INTERRUPT_ON_MOUNT, GetSpellId());
CreatureData* ctrData = sCreatureDataMgr.GetCreatureData(mod->m_miscValue[0]);
if(ctrData == NULL || ctrData->displayInfo[0] == 0)
return;
pPlayer->SetUInt32Value( UNIT_FIELD_MOUNTDISPLAYID, ctrData->displayInfo[0]);
if( pPlayer->GetShapeShift() && pPlayer->m_ShapeShifted != m_spellProto->Id &&
!(pPlayer->GetShapeShift() & FORM_BATTLESTANCE | FORM_DEFENSIVESTANCE | FORM_BERSERKERSTANCE ))
pPlayer->RemoveAura( pPlayer->m_ShapeShifted );
// If we already have a fixed amount, then this is a reapplication of the modifier
if(mod->fixed_amount)
return;
// Grab our mount capability spell
SpellEntry *mountCapability = pPlayer->GetMountCapability(mod->m_miscValue[1]);
if(mountCapability == NULL)
return;
SpellCastTargets targets(pPlayer->GetGUID());
if(Spell *mountAbility = new Spell(pPlayer, mountCapability))
{
mod->fixed_amount = mountCapability->Id;
mountAbility->prepare(&targets, true);
}
}
else
{
if(mod->fixed_amount)
pPlayer->RemoveAura(mod->fixed_amount);
pPlayer->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
pPlayer->m_AuraInterface.RemoveAllAurasByInterruptFlagButSkip( AURA_INTERRUPT_ON_DISMOUNT, GetSpellId() );
}
}
void Aura::SpellAuraModDamageTakenPctPerCaster(bool apply)
{
}
void Aura::SpellAuraRequireNoAmmo(bool apply)
{
if(!m_target->IsPlayer())
return;
}
void Aura::SpellAuraModDamagePercDone(bool apply)
{
}
void Aura::SpellAuraModPercStat(bool apply)
{
}
void Aura::SpellAuraSplitDamage(bool apply)
{
}
void Aura::SpellAuraModRegen(bool apply)
{
}
void Aura::SpellAuraIgnoreEnemy(bool apply)
{
}
void Aura::SpellAuraDrinkNew(bool apply)
{
}
void Aura::EventPeriodicSpeedModify(int32 modifier)
{
}
void Aura::EventPeriodicDrink(uint32 amount)
{
uint32 v = m_target->GetPower(POWER_TYPE_MANA) + amount;
if( v > m_target->GetMaxPower(POWER_TYPE_MANA) )
v = m_target->GetMaxPower(POWER_TYPE_MANA);
m_target->SetPower(POWER_TYPE_MANA, v);
SendPeriodicAuraLog(amount, FLAG_PERIODIC_ENERGIZE);
}
void Aura::EventPeriodicHeal1(uint32 amount)
{
if(m_target == NULL )
return;
if(!m_target->isAlive())
return;
uint32 ch = m_target->GetUInt32Value(UNIT_FIELD_HEALTH);
ch+=amount;
uint32 mh = m_target->GetUInt32Value(UNIT_FIELD_MAXHEALTH);
if(ch>mh)
m_target->SetUInt32Value(UNIT_FIELD_HEALTH,mh);
else m_target->SetUInt32Value(UNIT_FIELD_HEALTH,ch);
if(m_spellProto->AuraInterruptFlags & AURA_INTERRUPT_ON_STAND_UP)
m_target->Emote(EMOTE_ONESHOT_EAT);
else if(m_spellProto->buffIndex == 0)
SendPeriodicAuraLog(amount, FLAG_PERIODIC_HEAL);
}
void Aura::SpellAuraModPowerRegen(bool apply)
{
}
void Aura::SpellAuraChannelDeathItem(bool apply)
{
}
void Aura::SpellAuraModDamagePercTaken(bool apply)
{
}
void Aura::SpellAuraModRegenPercent(bool apply)
{
}
void Aura::SpellAuraPeriodicDamagePercent(bool apply)
{
}
void Aura::EventPeriodicDamagePercent(uint32 amount)
{
//DOT
if(!m_target->isAlive())
return;
uint32 damage = m_target->GetModPUInt32Value(UNIT_FIELD_MAXHEALTH, amount);
Unit * m_caster = GetUnitCaster();
if(m_caster!=NULL)
m_caster->SpellNonMeleeDamageLog(m_target, m_spellProto->Id, damage, m_triggeredSpellId==0, true);
else m_target->SpellNonMeleeDamageLog(m_target, m_spellProto->Id, damage, m_triggeredSpellId==0, true);
}
void Aura::SpellAuraModResistChance(bool apply)
{
}
void Aura::SpellAuraModDetectRange(bool apply)
{
}
void Aura::SpellAuraPreventsFleeing(bool apply)
{
// Curse of Recklessness
}
void Aura::SpellAuraModUnattackable(bool apply)
{
/*
Also known as Apply Aura: Mod Uninteractible
Used by: Spirit of Redemption, Divine Intervention, Phase Shift, Flask of Petrification
It uses one of the UNIT_FIELD_FLAGS, either UNIT_FLAG_NOT_SELECTABLE or UNIT_FLAG_NOT_ATTACKABLE_2
*/
}
void Aura::SpellAuraInterruptRegen(bool apply)
{
if(apply)
m_target->m_interruptRegen++;
else
{
m_target->m_interruptRegen--;
if(m_target->m_interruptRegen < 0)
m_target->m_interruptRegen = 0;
}
}
void Aura::SpellAuraGhost(bool apply)
{
if(m_target->IsPlayer())
{
SpellAuraWaterWalk( apply );
}
//m_target->SendPowerUpdate();
}
void Aura::SpellAuraMagnet(bool apply)
{
}
void Aura::SpellAuraManaShield(bool apply)
{
}
void Aura::SpellAuraSkillTalent(bool apply)
{
}
void Aura::SpellAuraModAttackPower(bool apply)
{
}
void Aura::SpellAuraVisible(bool apply)
{
}
void Aura::SpellAuraModCreatureAttackPower(bool apply)
{
}
void Aura::SpellAuraModTotalThreat( bool apply )
{
}
void Aura::SpellAuraWaterWalk( bool apply )
{
}
void Aura::SpellAuraFeatherFall( bool apply )
{
}
void Aura::SpellAuraHover( bool apply )
{
}
void Aura::SpellAuraAddFlatModifier(bool apply)
{
}
void Aura::SpellAuraAddPctMod( bool apply )
{
}
void Aura::SpellAuraAddTargetTrigger(bool apply)
{
}
void Aura::SpellAuraModPowerRegPerc(bool apply)
{
}
void Aura::SpellAuraOverrideClassScripts(bool apply)
{
}
void Aura::SpellAuraModRangedDamageTaken(bool apply)
{
}
void Aura::SpellAuraModHealing(bool apply)
{
}
void Aura::SpellAuraIgnoreRegenInterrupt(bool apply)
{
}
void Aura::SpellAuraModMechanicResistance(bool apply)
{
}
void Aura::SpellAuraModHealingPCT(bool apply)
{
}
void Aura::SpellAuraModRangedAttackPower(bool apply)
{
if(apply)
m_target->ModUnsigned32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MOD_POS,mod->m_amount);
else m_target->ModUnsigned32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MOD_POS,-mod->m_amount);
}
void Aura::SpellAuraModMeleeDamageTaken(bool apply)
{
}
void Aura::SpellAuraModMeleeDamageTakenPct(bool apply)
{
}
void Aura::SpellAuraRAPAttackerBonus(bool apply)
{
}
void Aura::SpellAuraModPossessPet(bool apply)
{
}
void Aura::SpellAuraModIncreaseSpeedAlways(bool apply)
{
}
void Aura::SpellAuraModIncreaseEnergyPerc( bool apply )
{
}
void Aura::SpellAuraModIncreaseHealthPerc( bool apply )
{
}
void Aura::SpellAuraModManaRegInterrupt( bool apply )
{
}
void Aura::SpellAuraModTotalStatPerc(bool apply)
{
}
void Aura::SpellAuraModHaste( bool apply )
{
}
void Aura::SpellAuraForceReaction( bool apply )
{
if( !m_target->IsPlayer() )
return;
std::map<uint32,uint32>::iterator itr;
Player* p_target = castPtr<Player>(m_target);
if( apply )
{
itr = p_target->m_forcedReactions.find( mod->m_miscValue[0] );
if( itr != p_target->m_forcedReactions.end() )
itr->second = mod->m_amount;
else
p_target->m_forcedReactions.insert( std::make_pair( mod->m_miscValue[0], mod->m_amount ) );
}
else
p_target->m_forcedReactions.erase( mod->m_miscValue[0] );
WorldPacket data( SMSG_SET_FORCED_REACTIONS, ( 8 * p_target->m_forcedReactions.size() ) + 4 );
data << uint32(p_target->m_forcedReactions.size());
for( itr = p_target->m_forcedReactions.begin(); itr != p_target->m_forcedReactions.end(); itr++ )
{
data << itr->first;
data << itr->second;
}
p_target->GetSession()->SendPacket( &data );
}
void Aura::SpellAuraModRangedHaste(bool apply)
{
}
void Aura::SpellAuraModRangedAmmoHaste(bool apply)
{
}
void Aura::SpellAuraRetainComboPoints(bool apply)
{
}
void Aura::SpellAuraResistPushback(bool apply)
{
}
void Aura::SpellAuraModShieldBlockPCT( bool apply )
{
}
void Aura::SpellAuraTrackStealthed(bool apply)
{
Unit * m_caster = GetUnitCaster();
if( m_caster== NULL || !m_caster->IsPlayer() )
return;
//0x00000002 is track stealthed
if( apply )
m_caster->SetFlag(PLAYER_FIELD_BYTES, 0x00000002);
else m_caster->RemoveFlag(PLAYER_FIELD_BYTES, 0x00000002);
}
void Aura::SpellAuraModDetectedRange(bool apply)
{
}
void Aura::SpellAuraSplitDamageFlat(bool apply)
{
}
void Aura::SpellAuraModStealthLevel(bool apply)
{
}
void Aura::SpellAuraModUnderwaterBreathing(bool apply)
{
}
void Aura::SpellAuraSafeFall(bool apply)
{
}
void Aura::SpellAuraModReputationAdjust(bool apply)
{
}
void Aura::SpellAuraNoPVPCredit(bool apply)
{
}
void Aura::SpellAuraModHealthRegInCombat(bool apply)
{
}
void Aura::EventPeriodicBurn(uint32 amount, uint32 misc)
{
Unit * m_caster = GetUnitCaster();
if( m_caster == NULL)
return;
if(m_target->isAlive() && m_caster->isAlive())
{
uint32 Amount = std::min( amount, m_target->GetPower(misc) );
SendPeriodicAuraLog(m_casterGuid, m_target, m_spellProto, Amount, 0, 0, FLAG_PERIODIC_DAMAGE);
m_target->DealDamage(m_target, Amount, 0, 0, m_spellProto->Id);
}
}
void Aura::SpellAuraPowerBurn(bool apply)
{
}
void Aura::SpellAuraModCritDmgPhysical(bool apply)
{
}
void Aura::SpellAuraWaterBreathing( bool apply )
{
}
void Aura::SpellAuraAPAttackerBonus(bool apply)
{
}
void Aura::SpellAuraModPAttackPower(bool apply)
{
}
void Aura::SpellAuraModRangedAttackPowerPct(bool apply)
{
}
void Aura::SpellAuraIncreaseDamageTypePCT(bool apply)
{
}
void Aura::SpellAuraIncreaseCricticalTypePCT(bool apply)
{
}
void Aura::SpellAuraIncreasePartySpeed(bool apply)
{
}
void Aura::SpellAuraIncreaseSpellDamageByAttribute(bool apply)
{
}
void Aura::SpellAuraIncreaseHealingByAttribute(bool apply)
{
}
void Aura::SpellAuraModHealingDone(bool apply)
{
}
void Aura::SpellAuraModHealingDonePct(bool apply)
{
}
void Aura::SpellAuraEmphaty(bool apply)
{
Unit * m_caster = GetUnitCaster();
if(m_caster == NULL || m_target == NULL || !m_caster->IsPlayer())
return;
m_target->SetUInt32Value(UNIT_DYNAMIC_FLAGS, U_DYN_FLAG_PLAYER_INFO);
}
void Aura::SpellAuraUntrackable(bool apply)
{
if(apply)
m_target->SetFlag(UNIT_FIELD_BYTES_1, 0x04000000);
else
m_target->RemoveFlag(UNIT_FIELD_BYTES_1, 0x04000000);
}
void Aura::SpellAuraModOffhandDamagePCT(bool apply)
{
}
void Aura::SpellAuraModPenetration(bool apply)
{
}
void Aura::SpellAuraIncreaseArmorByPctInt(bool apply)
{
}
void Aura::SpellAuraReduceAttackerMHitChance(bool apply)
{
}
void Aura::SpellAuraReduceAttackerRHitChance(bool apply)
{
}
void Aura::SpellAuraReduceAttackerSHitChance(bool apply)
{
}
void Aura::SpellAuraReduceEnemyMCritChance(bool apply)
{
}
void Aura::SpellAuraReduceEnemyRCritChance(bool apply)
{
}
void Aura::SpellAuraUseNormalMovementSpeed( bool apply )
{
}
void Aura::SpellAuraIncreaseTimeBetweenAttacksPCT(bool apply)
{
}
void Aura::SpellAuraModAttackerCritChance(bool apply)
{
}
void Aura::SpellAuraIncreaseAllWeaponSkill(bool apply)
{
}
void Aura::SpellAuraIncreaseHitRate( bool apply )
{
if( !m_target->IsPlayer() )
return;
}
void Aura::SpellAuraModMobKillXPGain( bool apply )
{
if( !m_target->IsPlayer() )
return;
if( apply )
castPtr<Player>( m_target )->MobXPGainRate += GetSpellProto()->EffectBasePoints[0]+1;
else castPtr<Player>( m_target )->MobXPGainRate -= GetSpellProto()->EffectBasePoints[0]+1;
if(castPtr<Player>( m_target )->MobXPGainRate <= (float)0.0f)
castPtr<Player>( m_target )->MobXPGainRate = (float)0.0f;
}
void Aura::SpellAuraIncreaseRageFromDamageDealtPCT(bool apply)
{
}
void Aura::SpellAuraNoReagentCost(bool apply)
{
}
void Aura::SpellAuraReduceCritMeleeAttackDmg(bool apply)
{
}
void Aura::SpellAuraReduceCritRangedAttackDmg(bool apply)
{
}
void Aura::SpellAuraEnableFlight(bool apply)
{
}
void Aura::SpellAuraEnableFlightWithUnmountedSpeed(bool apply)
{
}
void Aura::SpellAuraIncreaseMovementAndMountedSpeed( bool apply )
{
}
void Aura::SpellAuraIncreaseFlightSpeed( bool apply )
{
}
void Aura::SpellAuraIncreaseRating( bool apply )
{
}
void Aura::EventPeriodicRegenManaStatPct(uint32 perc, uint32 stat)
{
if(m_target->isDead())
return;
uint32 spellId = m_triggeredSpellId ? m_triggeredSpellId : (m_spellProto ? m_spellProto->Id : 0);
m_target->Energize(m_target, spellId, (m_target->GetUInt32Value(UNIT_FIELD_STATS + stat) * perc)/100, POWER_TYPE_MANA);
}
void Aura::SpellAuraRegenManaStatPCT(bool apply)
{
}
void Aura::SpellAuraSpellHealingStatPCT(bool apply)
{
}
void Aura::SpellAuraFinishingMovesCannotBeDodged(bool apply)
{
if( !m_target->IsPlayer() )
return;
castPtr<Player>( m_target )->m_finishingmovesdodge = apply;
}
void Aura::SpellAuraAuraModInvisibilityDetection(bool apply)
{
}
void Aura::SpellAuraIncreaseMaxHealth(bool apply)
{
//should only be used by a player
//and only ever target players
if( !m_target->IsPlayer() )
return;
int32 amount;
if( apply )
amount = mod->m_amount;
else
amount = -mod->m_amount;
}
void Aura::SpellAuraSpiritOfRedemption(bool apply)
{
if(!m_target->IsPlayer())
return;
if(apply)
{
//m_target->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.5);
m_target->SetUInt32Value(UNIT_FIELD_HEALTH, 1);
SpellEntry *sorInfo = dbcSpell.LookupEntry(27792);
if(sorInfo == NULL)
return;
SpellCastTargets targets(m_target->GetGUID());
if(Spell* sor = new Spell(m_target, sorInfo))
sor->prepare(&targets, true);
}
else
{
//m_target->SetFloatValue(OBJECT_FIELD_SCALE_X, 1);
m_target->RemoveAura(27792);
m_target->SetUInt32Value(UNIT_FIELD_HEALTH, 0);
}
}
void Aura::SpellAuraDispelDebuffResist(bool apply)
{
}
void Aura::SpellAuraIncreaseAttackerSpellCrit(bool apply)
{
}
void Aura::SpellAuraIncreaseRepGainPct(bool apply)
{
}
void Aura::SpellAuraIncreaseRangedAPStatPCT(bool apply)
{
}
void Aura::SpellAuraModBlockValue(bool apply)
{
}
// Looks like it should make spells skip some can cast checks. Atm only affects TargetAuraState check
void Aura::SpellAuraSkipCanCastCheck(bool apply)
{
}
void Aura::SpellAuraCastFilter(bool apply)
{
}
void Aura::SendInterrupted(uint8 result, WorldObject* m_ocaster)
{
if( !m_ocaster->IsInWorld() )
return;
WorldPacket data( SMSG_SPELL_FAILURE, 20 );
if( m_ocaster->IsPlayer() )
{
data << m_ocaster->GetGUID();
data << uint8(0); //extra_cast_number
data << uint32(m_spellProto->Id);
data << uint8( result );
castPtr<Player>( m_ocaster )->GetSession()->SendPacket( &data );
}
data.Initialize( SMSG_SPELL_FAILED_OTHER );
data << m_ocaster->GetGUID();
data << uint8(0); //extra_cast_number
data << uint32(m_spellProto->Id);
data << uint8( result );
m_ocaster->SendMessageToSet( &data, false );
m_interrupted = (int16)result;
}
void Aura::SendChannelUpdate(uint32 time, WorldObject* m_ocaster)
{
WorldPacket data(MSG_CHANNEL_UPDATE, 18);
data << m_ocaster->GetGUID();
data << time;
m_ocaster->SendMessageToSet(&data, true);
}
void Aura::SpellAuraExpertise(bool apply)
{
}
void Aura::SpellAuraForceMoveFoward(bool apply)
{
if(m_target == NULL || !m_target->IsPlayer())
return;
if(apply)
m_target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
else
m_target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE);
}
void Aura::SpellAuraModFaction(bool apply)
{
if(m_target == NULL)
return;
if(apply)
m_target->SetFaction(GetSpellProto()->EffectMiscValue[mod->i]);
else m_target->ResetFaction();
}
void Aura::SpellAuraComprehendLanguage(bool apply)
{
if(m_target == NULL || !m_target->IsPlayer())
return;
if(apply)
m_target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
else m_target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG);
}
void Aura::SendPeriodicAuraLog(uint32 amt, uint32 Flags)
{
SendPeriodicAuraLog(m_casterGuid, m_target, m_spellProto, amt, 0, 0, Flags, m_triggeredSpellId);
}
void Aura::SendPeriodicAuraLog(uint64 CasterGuid, Unit* Target, SpellEntry *sp, uint32 Amount, int32 abs_dmg, uint32 resisted_damage, uint32 Flags, uint32 pSpellId, bool crit)
{
if(Target == NULL || !Target->IsInWorld())
return;
uint32 spellId = pSpellId ? pSpellId : sp->Id;
uint8 isCritical = crit ? 1 : 0;
if(abs_dmg == -1)
abs_dmg = Amount;
WorldPacket data(SMSG_PERIODICAURALOG, 46);
data << Target->GetGUID(); // target guid
data << WoWGuid(CasterGuid).asPacked(); // caster guid
data << uint32(spellId); // spellid
data << uint32(1); // count of logs going next
data << uint32(Flags); // Log type
switch(Flags)
{
case FLAG_PERIODIC_DAMAGE:
{
data << uint32(Amount);
data << uint32(0);
data << uint32(SchoolMask(sp->School));
data << uint32(abs_dmg);
data << uint32(resisted_damage);
data << uint8(isCritical);
}break;
case FLAG_PERIODIC_HEAL:
{
data << uint32(Amount);
data << uint32(resisted_damage);
data << uint32(abs_dmg);
data << uint8(isCritical);
}break;
case FLAG_PERIODIC_ENERGIZE:
case FLAG_PERIODIC_LEECH:
{
data << uint32(sp->EffectMiscValue[mod->i]);
data << uint32(Amount);
if(Flags == FLAG_PERIODIC_LEECH)
data << float(sp->EffectValueMultiplier[mod->i]);
}break;
default:
{
sLog.printf("Unknown type!");
return;
}break;
}
Target->SendMessageToSet(&data, true);
}
void Aura::AttemptDispel(Unit* pCaster, bool canResist)
{
m_dispelled = true;
Remove();
}
void Aura::SpellAuraModIgnoreArmorPct(bool apply)
{
}
void Aura::SpellAuraSetPhase(bool apply)
{
}
void Aura::SpellAuraIncreaseAPByAttribute(bool apply)
{
}
void Aura::SpellAuraModSpellDamageFromAP(bool apply)
{
}
void Aura::SpellAuraModSpellHealingFromAP(bool apply)
{
}
void Aura::SpellAuraProcTriggerWithValue(bool apply)
{
// Todo:PROC
}
void Aura::SpellAuraVehiclePassenger(bool apply)
{
}
void Aura::SpellAuraReduceEffectDuration(bool apply)
{
}
void Aura::SpellAuraNoReagent(bool apply)
{
if( !m_target->IsPlayer() )
return;
uint32 ClassMask[3] = {0,0,0};
for(uint32 x=0;x<3;x++)
ClassMask[x] |= m_target->GetUInt32Value(PLAYER_NO_REAGENT_COST_1+x);
for(uint32 x=0;x<3;x++)
{
if(apply)
ClassMask[x] |= m_spellProto->EffectSpellClassMask[mod->i][x];
else ClassMask[x] &= ~m_spellProto->EffectSpellClassMask[mod->i][x];
}
for(uint32 x=0;x<3;x++)
m_target->SetUInt32Value(PLAYER_NO_REAGENT_COST_1+x, ClassMask[x]);
}
void Aura::SpellAuraModBaseHealth(bool apply)
{
}
uint8 Aura::GetMaxProcCharges(Unit* caster)
{
uint32 charges = m_spellProto->procCharges;
if(caster)
{
caster->SM_FIValue(SMT_CHARGES, (int32*)&charges, m_spellProto->SpellGroupType);
caster->SM_PIValue(SMT_CHARGES, (int32*)&charges, m_spellProto->SpellGroupType);
}
return uint8(charges & 0xFF);
}
void Aura::RecalculateModBaseAmounts()
{
Unit *unitCaster = GetUnitCaster();
Player *playerCaster = unitCaster ? unitCaster->IsPlayer() ? castPtr<Player>(unitCaster) : NULL : NULL;
uint32 casterLevel = unitCaster ? unitCaster->getLevel() : 0, casterComboPoints = 0;
for(uint32 i = 0; i < m_modcount; i++)
{
int32 value = m_spellProto->CalculateSpellPoints(m_modList[i].i, casterLevel, casterComboPoints);
if( unitCaster != NULL )
{
int32 spell_flat_modifers = 0, spell_pct_modifers = 0;
unitCaster->SM_FIValue(SMT_MISC_EFFECT, &spell_flat_modifers,GetSpellProto()->SpellGroupType);
unitCaster->SM_FIValue(SMT_MISC_EFFECT, &spell_pct_modifers, GetSpellProto()->SpellGroupType);
if( m_modList[i].i == 0 )
{
unitCaster->SM_FIValue(SMT_FIRST_EFFECT_BONUS,&spell_flat_modifers,GetSpellProto()->SpellGroupType);
unitCaster->SM_FIValue(SMT_FIRST_EFFECT_BONUS,&spell_pct_modifers,GetSpellProto()->SpellGroupType);
}
else if( m_modList[i].i == 1 )
{
unitCaster->SM_FIValue(SMT_SECOND_EFFECT_BONUS,&spell_flat_modifers,GetSpellProto()->SpellGroupType);
unitCaster->SM_FIValue(SMT_SECOND_EFFECT_BONUS,&spell_pct_modifers,GetSpellProto()->SpellGroupType);
}
if( ( m_modList[i].i == 2 ) || ( m_modList[i].i == 1 && GetSpellProto()->Effect[2] == 0 ) || ( m_modList[i].i == 0 && GetSpellProto()->Effect[1] == 0 && GetSpellProto()->Effect[2] == 0 ) )
{
unitCaster->SM_FIValue(SMT_LAST_EFFECT_BONUS,&spell_flat_modifers,GetSpellProto()->SpellGroupType);
unitCaster->SM_FIValue(SMT_LAST_EFFECT_BONUS,&spell_pct_modifers,GetSpellProto()->SpellGroupType);
}
value += float2int32(value * (float)(spell_pct_modifers / 100.0f)) + spell_flat_modifers;
}
m_modList[i].m_baseAmount = value;
}
UpdateModAmounts();
}
void Aura::UpdateModAmounts()
{
Unit * m_caster = GetUnitCaster();
for(uint8 i = 0; i < m_modcount; i++)
{
if( m_modList[i].m_bonusAmount == 0) CalculateBonusAmount(m_caster, i);
if(m_modList[i].m_baseAmount >= 0)
m_modList[i].m_amount = m_modList[i].m_baseAmount+m_modList[i].m_bonusAmount;
else m_modList[i].m_amount = m_modList[i].m_baseAmount-m_modList[i].m_bonusAmount;
if(m_stackSizeorProcCharges >= 0) m_modList[i].m_amount *= m_stackSizeorProcCharges;
if(m_target) m_target->OnAuraModChanged(m_modList[i].m_type);//m_AuraInterface.SetModMaskBit(m_modList[i].m_type);
}
}
void Aura::CalculateBonusAmount(Unit *caster, uint8 index)
{
if(index >= m_modcount || index >= 3)
return;
if(caster == NULL || m_target == NULL)
return;
m_modList[index].m_bonusAmount = caster->GetSpellBonusDamage(m_target, m_spellProto, index, m_modList[index].m_baseAmount, m_spellProto->isSpellHealingEffect());
if(m_modList[index].m_bonusAmount > m_modList[index].m_baseAmount)
m_modList[index].m_bonusAmount -= m_modList[index].m_baseAmount;
else m_modList[index].m_bonusAmount = 0;
}
void Aura::AddStackSize(uint8 mod)
{
if(mod == 0 || m_stackSizeorProcCharges < 0)
return;
uint16 maxStack = (m_spellProto->maxstack&0xFFFF);
if(maxStack && m_stackSizeorProcCharges == maxStack)
return;
int16 newStack = m_stackSizeorProcCharges + mod;
if(maxStack && newStack > maxStack)
newStack = maxStack;
m_stackSizeorProcCharges = newStack;
BuildAuraUpdate();
// now need to update amount and reapply modifiers
ApplyModifiers(false);
UpdateModAmounts();
ApplyModifiers(true);
}
void Aura::RemoveStackSize(uint8 mod)
{
if(mod == 0 || m_stackSizeorProcCharges < 0)
return;
if(m_stackSizeorProcCharges > mod)
{
m_stackSizeorProcCharges -= mod;
BuildAuraUpdate();
return;
}
m_stackSizeorProcCharges = 0;
Remove();
}
void Aura::SetProcCharges(uint8 mod)
{
if(m_stackSizeorProcCharges > 0)
return;
if(mod == 0)
m_stackSizeorProcCharges = 0;
else
{
m_stackSizeorProcCharges = -(mod&0xFF);
BuildAuraUpdate();
}
}
void Aura::RemoveProcCharges(uint8 mod)
{
if(mod == 0 || m_stackSizeorProcCharges > 0)
return;
if(m_stackSizeorProcCharges < mod)
{
m_stackSizeorProcCharges += mod;
BuildAuraUpdate();
return;
}
m_stackSizeorProcCharges = 0;
Remove();
}
void Aura::SpellAuraModDamageTakenByMechPCT(bool apply)
{
}
void Aura::SpellAuraAllowTamePetType(bool apply)
{
}
void Aura::SpellAuraAddCreatureImmunity(bool apply)
{
}
void Aura::SpellAuraRedirectThreat(bool apply)
{
}
void Aura::SpellAuraReduceAOEDamageTaken(bool apply)
{
}
void Aura::SpecialCases()
{
//We put all the special cases here, so we keep the code clean.
switch(m_spellProto->Id)
{
case 12976:// Last Stand
case 50322:// Survival Instincts
{
mod->m_amount = (uint32)(m_target->GetUInt32Value(UNIT_FIELD_MAXHEALTH) * 0.3);
}break;
case 23782:// Gift of Life
{
mod->m_amount = 1500;
}break;
case 48418:// Master Shapeshifter Physical Damage
case 48420:// Master Shapeshifter CritChance
case 48421:// Master Shapeshifter SpellDamage
case 48422:// Master Shapeshifter Healing
{
if(castPtr<Player>(m_target)->HasSpell(48411))
mod->m_amount = 2;
if(castPtr<Player>(m_target)->HasSpell(48412))
mod->m_amount = 4;
}break;
}
}
void Aura::SpellAuraHasteRanged(bool apply)
{
}
void Aura::SpellAuraModAttackPowerByArmor( bool apply )
{
}
void Aura::SpellAuraReflectInfront(bool apply)
{
// Todo:PROC
}
void Aura::SpellAuraModPetTalentPoints(bool apply)
{
if( !m_target->IsPlayer() )
return;
}
void Aura::SpellAuraPeriodicTriggerSpellWithValue(bool apply)
{
}
void Aura::SpellAuraModCritChanceAll(bool apply)
{
}
void Aura::SpellAuraOpenStable(bool apply)
{
if( !m_target || !m_target->IsPlayer() )
return;
}
void Aura::SpellAuraFakeInebriation(bool apply)
{
if( !m_target || !m_target->IsPlayer() )
return;
Player* plr = castPtr<Player>(m_target);
if( apply )
{
plr->m_invisDetect[INVIS_FLAG_DRUNK] += mod->m_amount;
plr->ModSignedInt32Value(PLAYER_FAKE_INEBRIATION, mod->m_amount);
}
else
{
plr->m_invisDetect[INVIS_FLAG_DRUNK] -= mod->m_amount;
plr->ModSignedInt32Value(PLAYER_FAKE_INEBRIATION, -mod->m_amount);
}
plr->UpdateVisibility();
}
void Aura::SpellAuraPreventResurrection(bool apply)
{
if( !m_target || !m_target->IsPlayer() )
return;
Player* plr = castPtr<Player>(m_target);
if( apply )
plr->PreventRes = true;
else plr->PreventRes = false;
}
void Aura::SpellAuraHealAndJump(bool apply)
{
}
void Aura::SpellAuraConvertRune(bool apply)
{
}
void Aura::SpellAuraModWalkSpeed(bool apply)
{
}
| 3fbfa5478386434ec98f1eeefcadbeb12e1b5157 | [
"Markdown",
"C++"
] | 17 | C++ | Zerixx/Ronin | c0056aebe1163d673625411646f5c44a9202b2fb | ca2536ea84e57a53b567d68cfe06821746ca7e33 |
refs/heads/master | <file_sep>#Python Selection Sort
def selectionSort(array):
for i in range(len(array)):
minValue = i
for k in range(i + 1, len(array)):
if array[minValue] > array[k]:
minValue = k
array[i], array[minValue] = array[minValue], array[i]
return array
<file_sep># SelectionSortPython
Selection Sort Coded In Python
| b34e02cd3f1840474064561d069d71f19309d117 | [
"Markdown",
"Python"
] | 2 | Python | cdsefcik/SelectionSortPython | eacd9d5cc8c7dd32625499e180cc36b6dc665e48 | 01a63bdaaf10aa74097562b57215c5315a3cf114 |
refs/heads/master | <repo_name>nickstoian/houghTransformLineDetection<file_sep>/main.cpp
//<NAME>
//CS780 Image Processing
//Project 8.2 - Hough Transform
//This program needs 3 command line arguments
//argv[1] "input" for text file representing the binary input image
//argv[2] "output1" for the result of the houghAry with header information
//argv[3] "output2" for pretty print of the houghAry
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
using namespace std;
class ImageProcessing{ friend class HoughTransform;
private:
int** imgAry;
int numRows;
int numCols;
int minVal;
int maxVal;
public:
ImageProcessing();
ImageProcessing(ifstream& inFile);
~ImageProcessing();
void loadImage(ifstream& inFile);
};
class HoughTransform{
private:
int** houghAry;
ImageProcessing* image;
int numRows;
int numCols;
int minVal;
int maxVal;
struct XYCoord{
int x;
int y;
};
XYCoord point;
int angleInDegree;
double angleInRadians;
public:
HoughTransform();
HoughTransform(ImageProcessing* image);
~HoughTransform();
void setPoint(int x, int y);
void computeDistance();
void determineHeader();
static string mapInt2Char(int theInt);
void prettyPrint(ofstream& outFile);
void printImage(ofstream& outFile);
};
int main(int argc, char* argv[]){
ifstream inFile1;
inFile1.open(argv[1]);
ImageProcessing* image = new ImageProcessing(inFile1);
inFile1.close();
HoughTransform* hough = new HoughTransform(image);
hough->computeDistance();
ofstream outFile1;
outFile1.open(argv[2]);
hough->printImage(outFile1);
outFile1.close();
ofstream outFile2;
outFile2.open(argv[3]);
hough->prettyPrint(outFile2);
outFile2.close();
}
ImageProcessing::ImageProcessing(): imgAry(NULL), numRows(0), numCols(0), minVal(0), maxVal(0){
}
ImageProcessing::ImageProcessing(ifstream& inFile){
loadImage(inFile);
}
ImageProcessing::~ImageProcessing(){
if(imgAry != NULL){
for(int i = 0; i < numRows; i++){
delete [] imgAry[i];
}
}
delete [] imgAry;
}
void ImageProcessing::loadImage(ifstream& inFile){
inFile >> numRows;
inFile >> numCols;
inFile >> minVal;
inFile >> maxVal;
imgAry = new int* [numRows];
for(int i = 0; i < numRows; i++){
imgAry[i] = new int [numCols];
}
for(int row = 0; row < numRows; row++){
for(int col = 0; col < numCols; col++){
imgAry[row][col] = 0;
}
}
for(int row = 0; row < numRows; row++){
for(int col = 0; col < numCols; col++){
int value;
inFile >> value;
imgAry[row][col] = value;
}
}
}
HoughTransform::HoughTransform(): houghAry(NULL), numRows(0), numCols(0), minVal(0), maxVal(0), angleInDegree(0), angleInRadians(0.0){
point.x = 0;
point.y = 0;
}
HoughTransform::HoughTransform(ImageProcessing* image): numCols(180), minVal(0), maxVal(0), angleInDegree(0.0){
this->image = image;
point.x = 0;
point.y = 0;
angleInRadians = angleInDegree * M_PI / 180.0;
numRows = (int)ceil(sqrt(pow(image->numRows, 2.0) + pow(image->numCols, 2.0)));
houghAry = new int* [numRows];
for(int i = 0; i < numRows; i++){
houghAry[i] = new int [numCols];
}
for(int row = 0; row < numRows; row++){
for(int col = 0; col < numCols; col++){
houghAry[row][col] = 0;
}
}
}
HoughTransform::~HoughTransform(){
if(houghAry != NULL){
for(int i = 0; i < numRows; i++){
delete [] houghAry[i];
}
}
delete [] houghAry;
image = NULL;
delete image;
}
void HoughTransform::setPoint(int x, int y){
point.x = x;
point.y = y;
}
void HoughTransform::computeDistance(){
for(int row = 0; row < image->numRows; row++){
for(int col = 0; col < image->numCols; col++){
if(image->imgAry[row][col] == 1){
setPoint(col, row);
for(angleInDegree = 0; angleInDegree < 180; angleInDegree++){
angleInRadians = angleInDegree * M_PI / 180.0;
double t = angleInRadians - atan((double)point.y / (double)point.x) - (M_PI / 2.0);
//double d = (sqrt(pow(point.x, 2.0) + pow(point.y, 2.0))) * cos(t);
int dist = abs((int)round((sqrt(pow(point.x, 2.0) + pow(point.y, 2.0))) * cos(t)));
houghAry[dist][angleInDegree]++;
//cout << setw(2) << point.x << " " << setw(2) << point.y << " " << setw(3) << angleInDegree << " " << setw(10)
//<< angleInRadians << " " << setw(10)<< t << " " << setw(10)<< d << " " << setw(2) << dist << endl;
}
}
}
}
}
string HoughTransform::mapInt2Char(int theInt){
char toReturn [33];
sprintf(toReturn, "%d", theInt);
return toReturn;
}
void HoughTransform::prettyPrint(ofstream& outFile){
for(int row = numRows - 1; row >= 0; row--){
for(int col = 0; col < numCols; col++){
if(houghAry[row][col] <= 0){
outFile << " " << " ";
}
else{
outFile << mapInt2Char(houghAry[row][col]) << " ";
}
}
outFile << endl;
}
}
void HoughTransform::determineHeader(){
for(int row = 0; row < numRows; row++){
for(int col = 0; col < numCols; col++){
if(houghAry[row][col] < minVal){
minVal = houghAry[row][col];
}
if(houghAry[row][col] > maxVal){
maxVal = houghAry[row][col];
}
}
}
}
void HoughTransform::printImage(ofstream& outFile){
determineHeader();
outFile << numRows << " " << numCols << " " << minVal << " " << maxVal << endl;
for(int row = numRows - 1; row >= 0 ; row--){
for(int col = 0; col < numCols; col++){
outFile << mapInt2Char(houghAry[row][col]) << " ";
}
outFile << endl;
}
}
<file_sep>/README.md
# houghTransformLineDetection
Project to perform Hough transform line feature detection
| fd8caf8a90653c13447a604c01b381313902a86c | [
"Markdown",
"C++"
] | 2 | C++ | nickstoian/houghTransformLineDetection | 6fe873749b3dc10aaff83e45ffccce868bc723fd | 24c1a317a7526d204b886286771997ecb1d0659e |
refs/heads/master | <file_sep>package com.offcn.springbootdemo1.controller;
import com.offcn.springbootdemo1.bean.User;
import com.offcn.springbootdemo1.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserDao userDao;
@Value("${spring.aaa}")
private Integer aaa;
@RequestMapping("/user/list")
@ResponseBody
public List<User> userListAll(){
List<User> userList = userDao.findAll();
return userList;
}
@RequestMapping("/user/table")
public String userListTable(Model model){
List<User> userList = userDao.findAll();
System.out.println(aaa);
model.addAttribute("userList",userList);
return "user";
}
}
| a53914e75f70ffcca521fc9a6069fbb20bc552b5 | [
"Java"
] | 1 | Java | wangju68/springbootDemo1 | bb53ab91f0bdaffc72b68a2d4493162fdca47a88 | db3bc4b1dd909586c7e3ef4b5f407ef0e139f6e3 |
refs/heads/main | <repo_name>kiruba-r11/Dynamic-Fragments<file_sep>/app/src/main/java/com/example/dynamicfragments/MainActivity.kt
package com.example.dynamicfragments
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.add
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fragment1.setOnClickListener {
supportFragmentManager
.beginTransaction()
.replace(R.id.container, FirstFragment()).addToBackStack(null)
.commit()
}
fragment2.setOnClickListener {
supportFragmentManager
.beginTransaction()
.replace(R.id.container, SecondFragment()).addToBackStack(null)
.commit()
}
}
} | 36cae7a525877350107c6f68142f1f3166cad909 | [
"Kotlin"
] | 1 | Kotlin | kiruba-r11/Dynamic-Fragments | e44e90ec9950698928cec176e6c81e41be639cb2 | 1bd95939fe0d406517502f102b27747d8fbe1a9e |
refs/heads/master | <repo_name>omochalov/test_task<file_sep>/test/categoryServic.js
/* eslint-disable no-undef */
process.env.NODE_ENV = 'test'
let Category = require('../models/category').model
let Product = require('../models/product').model
let categoryService = require('../services/category')
let chai = require('chai')
chai.should()
describe('Category service', () => {
beforeEach((done) => { // Before each test we empty the database
Promise.all([Category.remove(), Product.remove()])
.then(done())
})
it('new product should increment category.products_count value', (done) => {
let product = {name: 'Butter', price: 2.6}
let categoryId
Category.create({'name': 'serviceTest'})
.then(category => {
categoryId = category.id
return categoryService.createProductInCategory(categoryId, product)
})
.then(product => {
return Category.findById(categoryId)
})
.then(category => {
category.products_count.should.be.eql(1)
done()
})
})
})
<file_sep>/models/category.js
let mongoose = require('mongoose')
let Schema = mongoose.Schema
let uniqueValidator = require('mongoose-unique-validator')
let idPlugin = require('../db/idPlugin')
let categorySchema = new Schema({
name: {type: String, required: true, index: {unique: true}},
products: [{type: Schema.Types.ObjectId, ref: 'Product'}],
products_count: {type: Number, default: 0}
})
categorySchema.pre('validate', function (next) {
this.products_count = this.products.length
next()
})
categorySchema.plugin(uniqueValidator)
categorySchema.plugin(idPlugin)
module.exports.schema = categorySchema
module.exports.model = mongoose.model('Category', categorySchema)
<file_sep>/models/product.js
let mongoose = require('mongoose')
let Schema = mongoose.Schema
let uniqueValidator = require('mongoose-unique-validator')
let idPlugin = require('../db/idPlugin')
let productSchema = new Schema({
name: {type: String, required: true, index: {unique: true}},
price: {type: Number, required: true, min: 0},
category: {type: Schema.Types.ObjectId, ref: 'Category'}
})
productSchema.plugin(uniqueValidator)
productSchema.plugin(idPlugin)
module.exports.schema = productSchema
module.exports.model = mongoose.model('Product', productSchema)
<file_sep>/routes/categories.js
let router = require('express').Router()
const categoryService = require('../services/category')
router.get('/', (req, res) => {
categoryService.getAllCategories()
.then(result => res.json(result))
.catch(err => res.status(500).send(err))
})
router.post('/', (req, res) => {
if (!req.body.category) {
req.body.category = {}
}
categoryService.create(req.body.category.name)
.then(result => {
if (result.errors) {
res.status(422).json(result)
} else {
res.status(201).json(result)
}
})
.catch(err => res.status(422).send(err))
})
router.get('/:categoryID/products', (req, res) => {
categoryService.getAllProductsByCategoryId(req.params.categoryID)
.then(result => res.json(result))
.catch(err => res.status(500).send(err))
})
router.post('/:categoryID/products', (req, res) => {
categoryService.createProductInCategory(req.params.categoryID, req.body.product)
.then(result => {
if (result.errors) {
res.status(422).json(result)
} else {
res.status(201).json(result)
}
})
.catch(err => res.status(422).send(err))
})
module.exports = router
<file_sep>/README.md
test__task
Startup: docker-compose up
Connect to container running nodejs : docker exec -it test__task_web_1 bash
Connect to container running mongo : docker exec -it test__task_db_1 bash
<file_sep>/test/productsRoute.js
/* eslint-disable no-undef */
process.env.NODE_ENV = 'test'
let Category = require('../models/category').model
let Product = require('../models/product').model
let chai = require('chai')
let chaiHttp = require('chai-http')
let server = require('../app')
chai.use(chaiHttp)
chai.should()
describe('Products route', () => {
beforeEach((done) => { // Before each test we empty the database
Promise.all([Category.remove(), Product.remove()])
.then(done())
})
it('it should DELETE product', (done) => {
Category.create({name: 'deleteCat'}).then(category => {
Product.create({name: 'butter', 'price': 2.6, category: category.id})
.then((product) => {
chai.request(server)
.delete(`/products/${product.id}`)
.end((err, res) => {
res.should.have.status(204)
res.body.should.be.a('object')
done()
})
})
})
})
})
<file_sep>/routes/products.js
let router = require('express').Router()
const productService = require('../services/product')
router.delete('/:productId', (req, res) => {
productService.deleteById(req.params.productId)
.then(result => res.status(204).send(result))
.catch(err => res.send(err))
})
module.exports = router
<file_sep>/services/product.js
const mongoose = require('mongoose')
const Product = mongoose.model('Product')
module.exports = {
deleteById
}
function deleteById (productId) {
return Product.findById(productId)
.populate('category')
.exec()
.then(product => {
let category = product.category
let index = category.products.indexOf(productId)
if (index >= 0) {
category.products.splice(category.products.indexOf(productId), 1)
return category.save()
} else return {}
})
.then(() => {
Product.remove({_id: productId})
return {}
})
}
<file_sep>/db/index.js
require('./mongo')
| 0c89e6c9f9e11034cf460c6ac7826b5d47f41b9b | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | omochalov/test_task | 71cb76717411c55d4d8ef98a257a6fb35b344779 | cb566192b8f5a38c044b4a1002970b7940adbb86 |
refs/heads/master | <repo_name>klokik/PlaygroundGSoC<file_sep>/FailedRegionGrabCut.cc
#include <iostream>
#include <opencv2/opencv.hpp>
extern int depth_height;
extern int depth_width;
extern float depth_data[];
int main() {
// cv::Mat depth(depth_height, depth_width, CV_32FC1, &depth_data[0]);
cv::Mat depth = cv::imread("depth_2.png", cv::IMREAD_GRAYSCALE);
depth.convertTo(depth, CV_32FC1, 1./255, 0);
// cv::Mat im_mask = cv::imread("registrationMask.png", cv::IMREAD_GRAYSCALE);
cv::Mat rgb = cv::imread("color_2.png");//"image.png");
cv::threshold(depth, depth, 0.05, 1.0, cv::THRESH_BINARY);
// cv::threshold(depth, depth, 0, 1.0, cv::THRESH_BINARY);
depth.convertTo(depth, CV_8UC1, 255., 0.);
// cv::bitwise_or(im_mask, depth, depth);
cv::bitwise_not(depth, depth);
cv::Mat contours_mat = depth.clone();
std::vector<std::vector<cv::Point>> contours;
// cv::findContours(contours_mat, contours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE);
// for (auto &contour : contours) {
// std::vector<std::vector<cv::Point>> contour_list{contour};
// cv::fillPoly(depth, contour_list, cv::Scalar(255, 255, 255));
// }
cv::imshow("Depth", depth);
cv::Mat morph_cl_op;
cv::Mat mkernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3));
cv::morphologyEx(depth, depth, cv::MORPH_CLOSE, mkernel, cv::Point(-1,-1), 12);
cv::imshow("DepthCL", depth);
cv::morphologyEx(depth, depth, cv::MORPH_OPEN, mkernel, cv::Point(-1,-1), 6);
cv::imshow("DepthCLOP", depth);
// cv::morphologyEx(depth, depth, cv::MORPH_CLOSE, mkernel, cv::Point(-1,-1), 15);
// cv::imshow("DepthCLOPCL", depth);
contours_mat = depth.clone();
std::vector<std::vector<cv::Point>> hulls;
cv::findContours(contours_mat, contours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE);
for (auto &contour : contours) {
std::vector<cv::Point> hull;
cv::convexHull(contour, hull);
hulls.push_back(hull);
std::vector<std::vector<cv::Point>> contour_list{contour};
cv::fillPoly(depth, contour_list, cv::Scalar(255, 255, 255));
}
// cv::drawContours(rgb, hulls, -1, cv::Scalar(0, 0, 255), 2);
// cv::fillPoly(depth, hulls, cv::Scalar(255, 255, 255));
// cv::fillPoly(depth, contours, cv::Scalar(255, 255, 255));
cv::imshow("ConvHull", depth);
// ROI's and corresponding masks for grabCut
contours.clear();
cv::Mat depth_eroded, depth_dilated;
cv::erode(depth, depth_eroded, mkernel, cv::Point(-1, -1), 6);
cv::dilate(depth, depth_dilated, mkernel, cv::Point(-1, -1), 12);
contours_mat = depth.clone();
cv::findContours(contours_mat, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
std::vector<cv::Rect> rois;
std::vector<cv::Mat> roi_masks;
for (auto &contour : contours) {
if (cv::contourArea(contour) < 100)
continue;
constexpr int margin = 20;
cv::Rect roi = cv::boundingRect(contour);
roi.x = std::max(0, roi.x - margin);
roi.y = std::max(0, roi.y - margin);
roi.width = std::min(depth.cols - roi.x, roi.width + 2*margin);
roi.height = std::min(depth.rows - roi.y, roi.height + 2*margin);
cv::Mat c_mask(depth.size(), CV_8UC1, cv::GC_BGD);
c_mask(roi).setTo(cv::GC_PR_BGD, depth_dilated(roi));
c_mask(roi).setTo(cv::GC_PR_FGD, depth(roi));
c_mask(roi).setTo(cv::GC_FGD, depth_eroded(roi));
rois.push_back(roi);
roi_masks.push_back(c_mask(roi));
// cv::imshow("roi", c_mask(roi)*255.f/3);
// cv::waitKey();
}
cv::Mat refined_depth(depth.size(), CV_8UC1, cv::GC_BGD);
for (size_t i = 0; i < rois.size(); ++i) {
auto &roi = rois[i];
auto &gc_mask = roi_masks[i];
cv::Mat bgd_model, fgd_model;
cv::grabCut(rgb(roi), gc_mask, cv::Rect(),
bgd_model, fgd_model, 2, cv::GC_INIT_WITH_MASK);
cv::Mat refined_depth_roi = refined_depth(roi);
cv::Mat copy_mask = (gc_mask != cv::GC_BGD) & (gc_mask != cv::GC_PR_BGD);
gc_mask.copyTo(refined_depth_roi, copy_mask);
/* cv::imshow("mask_rgb", rgb(roi));
cv::Mat tmp;
rgb(roi).copyTo(tmp, copy_mask);
cv::imshow("masked", tmp);
cv::waitKey();*/
}
refined_depth = ((refined_depth == cv::GC_FGD)
| (refined_depth == cv::GC_PR_FGD));
cv::imshow("gc_refined", refined_depth);
contours_mat = refined_depth.clone();
cv::findContours(contours_mat, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);
cv::drawContours(rgb, contours, -1, cv::Scalar(0, 255, 255), 1);
// cv::imshow("RGB", rgb);
// cv::imshow("RMask", im_mask);
// cv::imshow("RMask", im_mask);
// cv::imshow("DepthM", depth);
cv::Mat masked_rgb;
refined_depth.convertTo(masked_rgb, CV_32FC1, 0.7/255, 0.3);
cv::Mat masked_rgb3;
cv::Mat l[] = {masked_rgb, masked_rgb, masked_rgb};
cv::merge(l, 3, masked_rgb3);
cv::multiply(masked_rgb3, rgb, masked_rgb3, 1./255, CV_32F);
cv::imshow("mRGB", masked_rgb3);
while(cv::waitKey(100) != 27);
return 0;
}
<file_sep>/SilhouetteExtraction.cc
#include <fstream>
#include <iostream>
#include <random>
#include <string>
#include <tuple>
#include <vector>
#include <opencv2/opencv.hpp>
constexpr auto storage_filename = "/tmp/edge_model_monkey.txt";
constexpr int im_size = 64;
using Triangle = std::vector<int>;
struct Mesh {
std::vector<cv::Point3f> points;
std::vector<Triangle> triangles;
};
struct Pose {
cv::Vec3f rot;
cv::Vec3f trans;
};
using Silhouette = std::vector<cv::Point2i>;
using Silhouettef = std::vector<cv::Point2f>;
struct Footprint {
cv::Mat img;
Silhouette contour;
Pose pose;
};
class EdgeModel {
public: void addFootprint(cv::Mat &footprint, const Silhouette &contour, const Pose &pose) {
if (contour.size() > 0)
this->items.push_back({footprint.clone(), contour, pose});
}
public: void saveToFile(std::string name) {
std::ofstream ofs(name);
for (auto &fp : this->items) {
ofs << "pose: " << fp.pose.rot(0) << " " << fp.pose.rot(1) << " " << fp.pose.rot(2) << " "
<< fp.pose.trans(0) << " " << fp.pose.trans(1) << std::endl;
for (auto &pt : fp.contour) {
ofs << pt.x << " " << pt.y << std::endl;
}
}
ofs.close();
}
public: bool loadFromFile(std::string name) {
std::ifstream ifs(name);
// check if file exists
if (!ifs.good())
return false;
Silhouette contour;
Pose pose;
for (std::string line; std::getline(ifs, line);) {
std::istringstream iss(line);
if (line.find("pose") == 0) {
auto img = drawFootprint(contour);
this->addFootprint(img, contour, pose);
contour.clear();
iss >> pose.rot(0) >> pose.rot(1) >> pose.rot(2) >> pose.trans(0) >> pose.trans(1);
}
else {
cv::Point2i pt;
iss >> pt.x >> pt.y;
contour.push_back(pt);
}
}
auto img = drawFootprint(contour);
this->addFootprint(img, contour, pose);
return true;
}
protected: cv::Mat drawFootprint(Silhouette &contour) {
if (contour.size() == 0)
return cv::Mat();
cv::Rect b_rect = cv::boundingRect(contour);
cv::Mat result = cv::Mat::zeros(b_rect.height + 8, b_rect.width + 8, CV_8UC1);
for (auto &pt : contour)
cv::circle(result, pt, 1, cv::Scalar(255), -1);
return result;
}
public: std::vector<Footprint> items;
};
struct Camera {
cv::Mat matrix = cv::Mat::eye(3, 3, CV_32FC1);
std::vector<float> ks;
};
Mesh getRandomMesh(void) {
std::vector<cv::Point3f> points;
std::vector<Triangle> triangles;
std::mt19937 rng(1337);
std::uniform_real_distribution<float> distrib(-1, 1);
for (int i = 0; i < 1000; ++i)
points.push_back(cv::Point3f(distrib(rng)+1, distrib(rng)*4-5, distrib(rng)));
return {points, triangles};
}
Mesh readTrainingMesh(std::string _filename) {
std::vector<cv::Point3f> points;
std::vector<Triangle> triangles;
std::ifstream ifs(_filename);
enum class PLYSection : int { HEADER=0, VERTEX, FACE};
std::map<PLYSection, int> counts;
PLYSection cur_section = PLYSection::HEADER;
for (std::string line; std::getline(ifs, line);) {
if (cur_section == PLYSection::HEADER) {
if (line.find("element face") == 0)
counts[PLYSection::FACE] = std::atoi(line.substr(line.rfind(" ")).c_str());
if (line.find("element vertex") == 0)
counts[PLYSection::VERTEX] = std::atoi(line.substr(line.rfind(" ")).c_str());
if (line.find("end_header") == 0) {
cur_section = PLYSection::VERTEX;
std::cout << "Vertices: " << counts[PLYSection::VERTEX] << std::endl;
std::cout << "Faces: " << counts[PLYSection::FACE] << std::endl;
}
}
else if (cur_section == PLYSection::VERTEX) {
if (0 < counts[cur_section]--) {
std::istringstream iss(line);
cv::Point3f pt;
iss >> pt.x >> pt.y >> pt.z;
points.push_back(pt);
}
else
cur_section = PLYSection::FACE;
}
if (cur_section == PLYSection::FACE) {
if (0 == counts[cur_section]--)
break;
std::istringstream iss(line);
int n_verts, i1, i2, i3;
iss >> n_verts >> i1 >> i2 >> i3;
assert(n_verts == 3);
triangles.push_back({i1, i2, i3});
}
}
std::cout << "Vertices left: " << counts[PLYSection::VERTEX] << std::endl;
std::cout << "Faces left: " << counts[PLYSection::FACE] << std::endl;
return {points, triangles};
}
cv::Rect_<float> getBoundingRect(Silhouettef &sil) {
cv::Rect_<float> b_rect;
auto h_it = std::minmax_element(sil.begin(), sil.end(),
[](const cv::Point2f &a, const cv::Point2f &b) {
return a.x < b.x;});
auto v_it = std::minmax_element(sil.begin(), sil.end(),
[](const cv::Point2f &a, const cv::Point2f &b) {
return a.y < b.y;});
b_rect.x = h_it.first->x;
b_rect.y = v_it.first->y;
b_rect.width = h_it.second->x - b_rect.x;
b_rect.height = v_it.second->y - b_rect.y;
return b_rect;
}
Footprint getFootprint(Mesh mesh, Pose pose, Camera cam, int im_size) {
// project points on a plane
std::vector<cv::Point2f> points2d;
cv::projectPoints(mesh.points, pose.rot, pose.trans, cam.matrix, cam.ks, points2d);
// find points2d bounding rect
cv::Rect_<float> b_rect;
// b_rect = cv::boundingRect2f(points2d); // available since 2.4.something
b_rect = getBoundingRect(points2d);
auto larger_size = std::max(b_rect.width, b_rect.height);
auto rate = static_cast<float>(im_size)/larger_size;
cv::Size fp_mat_size(b_rect.width*rate + 1, b_rect.height*rate + 1);
cv::Mat footprint = cv::Mat::zeros(fp_mat_size, CV_8UC1);
// std::cout << fp_mat_size << std::endl;
// std::cout << b_rect << std::endl;
// map point onto plane
for (auto &point : points2d) {
cv::Point2i xy = (point - b_rect.tl())*rate;
assert(xy.x >= 0);
assert(xy.y >= 0);
assert(xy.x <= footprint.cols);
assert(xy.y <= footprint.rows);
xy.x = std::min(xy.x, footprint.cols-1);
xy.y = std::min(xy.y, footprint.rows-1);
point = xy;
}
for (const auto &tri : mesh.triangles) {
std::vector<cv::Point2i> poly{
points2d[tri[0]],
points2d[tri[1]],
points2d[tri[2]]};
cv::fillConvexPoly(footprint, poly, cv::Scalar(255));
}
int margin = 4;
cv::copyMakeBorder(footprint, footprint, margin, margin, margin, margin,
cv::BORDER_CONSTANT | cv::BORDER_ISOLATED, cv::Scalar(0));
cv::Mat tmp = footprint.clone();
std::vector<Silhouette> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(tmp, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
assert(contours.size() == 1);
cv::Mat mkernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3));
cv::morphologyEx(footprint, footprint, cv::MORPH_GRADIENT, mkernel,
cv::Point(-1,-1), 1);
cv::imshow("footprint", footprint);
cv::waitKey(100);
return {footprint, contours[0], pose};
}
EdgeModel getSampledFootprints(Mesh &mesh, Camera &cam, int im_size,
int rot_samples, int trans_samples) {
EdgeModel e_model;
auto it = std::max_element(mesh.points.cbegin(), mesh.points.cend(),
[](const cv::Point3f &a, const cv::Point3f &b) {
return cv::norm(a) < cv::norm(b); });
float mlen = cv::norm(*it);
const auto pi = 3.1415926f;
for (int r_ax_i = 0; r_ax_i < rot_samples; ++r_ax_i) {
float axis_inc = pi * r_ax_i / rot_samples;
cv::Vec3f axis{std::cos(axis_inc), std::sin(axis_inc), 0};
for (int r_ang_i = 0; r_ang_i < rot_samples; ++r_ang_i ) {
float theta = pi * r_ang_i / rot_samples;
auto rodrigues = axis*theta;
std::cout << "Sample (" << r_ax_i << ";" << r_ang_i << ")" << std::endl;
// avoid translation sampling for now
Pose mesh_pose{rodrigues, {0,0,-mlen*3.f}};
auto footprint = getFootprint(mesh, mesh_pose, cam, im_size);
e_model.addFootprint(footprint.img, footprint.contour, footprint.pose);
}
}
return e_model;
}
int main() {
Camera camera;
// camera.matrix.at<float>(0, 0) = 1;
// camera.matrix.at<float>(1, 1) = 1;
// camera.matrix.at<float>(2, 2) = 1;
// camera.matrix.at<float>(0, 2) = 0;
// camera.matrix.at<float>(1, 2) = 0;
int rot_samples = 10;
int trans_samples = 1;
EdgeModel edge_model;
bool cached;
if (!(cached = edge_model.loadFromFile(storage_filename))) {
Mesh test_mesh = readTrainingMesh("monkey.ply");
edge_model = getSampledFootprints(test_mesh, camera, im_size, rot_samples, trans_samples);
}
auto seg_size = (im_size+9);
cv::Mat whole_image = cv::Mat::zeros(seg_size*rot_samples, seg_size*rot_samples, CV_8UC1);
int i = 0;
for (auto kv : edge_model.items) {
auto ix = (i % rot_samples)*seg_size;
auto iy = (i / rot_samples)*seg_size;
i++;
kv.img.copyTo(whole_image.colRange(ix, ix+kv.img.cols).
rowRange(iy, iy+kv.img.rows));
}
if (!cached)
edge_model.saveToFile("/tmp/edge_model_monkey.txt");
cv::imshow("Silhouettes", whole_image);
while ((cv::waitKey(100) & 255) != 27);
return 0;
}<file_sep>/Procrustes.cc
#include <iostream>
#include <numeric>
#include <opencv2/opencv.hpp>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>
using Silhouette = std::vector<cv::Point2f>;
Silhouette normalizeSilhouette(Silhouette &shape) {
Silhouette result(shape);
cv::Point2f mean = std::accumulate(shape.begin(), shape.end(), cv::Point2f()) * (1.f / shape.size());
float std_dev = 0;
for (auto &pt : result) {
pt = pt - mean;
std_dev += std::pow(cv::norm(pt), 2);
}
std_dev = std::sqrt(std_dev / shape.size());
for (auto &pt : result)
pt *= 1.f / std_dev;
return result;
}
void silhouetteToPC(Silhouette &sil, pcl::PointCloud<pcl::PointXYZ> &pc) {
pc.width = sil.size();
pc.height = 1;
pc.is_dense = false;
pc.resize(pc.width * pc.height);
for (size_t i = 0; i < sil.size(); ++i) {
pc.points[i] = {sil[i].x, sil[i].y, 0};
}
}
void PCToSilhouette(pcl::PointCloud<pcl::PointXYZ> &pc, Silhouette &sil) {
sil.clear();
assert(pc.height == 1);
for (size_t i = 0; i < pc.width; ++i) {
sil.push_back(cv::Point2f(pc.points[i].x, pc.points[i].y));
}
}
Silhouette fitICP(Silhouette &test, Silhouette &model) {
pcl::PointCloud<pcl::PointXYZ>::Ptr cl_test(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr cl_model(new pcl::PointCloud<pcl::PointXYZ>);
silhouetteToPC(test, *cl_test);
silhouetteToPC(model, *cl_model);
pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
icp.setInputSource(cl_test);
icp.setInputTarget(cl_model);
pcl::PointCloud<pcl::PointXYZ> cl_result;
icp.align(cl_result);
assert(icp.hasConverged());
std::cout << "Score: " << icp.getFitnessScore() << std::endl;
std::cout << icp.getFinalTransformation() << std::endl;
Silhouette result;
PCToSilhouette(cl_result, result);
return result;
}
const auto pi = 3.1415926f;
cv::Point2f operator*(cv::Mat &M, const cv::Point2f &pt) {
cv::Mat_<double> vec(3, 1);
vec(0, 0) = pt.x;
vec(1, 0) = pt.y;
vec(2, 0) = 1.f;
cv::Mat_<double> dst = M*vec;
return cv::Point2f(dst(0, 0), dst(1, 0));
}
Silhouette getTestSilhouette() {
Silhouette result;
cv::Point2f offset(50, 120);
int N = 100;
cv::Mat rot = cv::getRotationMatrix2D(cv::Point2f(), 30, 1);
for (int i = 0; i < N; ++i) {
float theta = 2*pi * i / N + pi/3;
cv::Point2f pt(std::cos(theta)*2, std::sin(theta));
pt *= 1+std::sin(theta*10)*0.1f;
pt = rot*pt;
result.push_back(pt*30 + offset);
}
return result;
}
Silhouette getModelSilhouette() {
Silhouette result;
cv::Point2f offset(128, 128);
int N = 50;
for (int i = 0; i < N; ++i) {
float theta = 2*pi * i / N;
cv::Point2f pt(std::cos(theta)*2, std::sin(theta));
result.push_back(pt*20 + offset);
}
return result;
}
void drawSilhouette(cv::Mat &mat, Silhouette &sil) {
for (auto &ptf : sil) {
cv::circle(mat, ptf, 1, cv::Scalar(255));
}
}
cv::Rect_<float> getBoundingRect(Silhouette &sil) {
cv::Rect_<float> b_rect;
auto h_it = std::minmax_element(sil.begin(), sil.end(),
[](const cv::Point2f &a, const cv::Point2f &b) {
return a.x < b.x;});
auto v_it = std::minmax_element(sil.begin(), sil.end(),
[](const cv::Point2f &a, const cv::Point2f &b) {
return a.y < b.y;});
b_rect.x = h_it.first->x;
b_rect.y = v_it.first->y;
b_rect.width = h_it.second->x - b_rect.x;
b_rect.height = v_it.second->y - b_rect.y;
return b_rect;
}
int main() {
cv::Mat test_sm = cv::Mat::zeros(256, 256, CV_8UC1);
cv::Mat model_sm = cv::Mat::zeros(256, 256, CV_8UC1);
auto test_s = getTestSilhouette();
auto model_s = getModelSilhouette();
drawSilhouette(test_sm, test_s);
drawSilhouette(model_sm, model_s);
cv::imshow("Test Silhouette", test_sm);
cv::imshow("Model Silhouette", model_sm);
test_s = normalizeSilhouette(test_s);
model_s = normalizeSilhouette(model_s);
auto fitted = fitICP(test_s, model_s);
Silhouette soup(fitted);
soup.insert(soup.end(), model_s.begin(), model_s.end());
int scale = 240;
auto t_box = getBoundingRect(soup);
for (auto &pt : soup)
pt = (pt - t_box.tl())*scale;
cv::Mat tnsm = cv::Mat::eye(t_box.height*scale, t_box.width*scale, CV_8UC1);
drawSilhouette(tnsm, soup);
cv::imshow("Shifted, scaled, rotated", tnsm);
while ((cv::waitKey(0) & 255) != 27);
return 0;
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(Playground)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "--std=c++1y -g ${CMAKE_CXX_FLAGS}")
find_package(OpenCV REQUIRED)
find_package(PCL 1.2 REQUIRED)
include_directories(${PCL_INCLUDE_DIRS})
link_directories(${PCL_LIBRARY_DIRS})
add_definitions(${PCL_DEFINITIONS})
add_executable(silhouette SilhouetteExtraction.cc)
target_link_libraries(silhouette ${OpenCV_LIBS})
add_executable(trans_segm FailedRegionGrabCut.cc data.cc)
target_link_libraries(trans_segm ${OpenCV_LIBS})
add_executable(procrustes Procrustes.cc)
target_link_libraries(procrustes ${OpenCV_LIBS} ${PCL_LIBRARIES})
add_executable(transform_corresp Correspondance2d3dPose.cc)
target_link_libraries(transform_corresp ${OpenCV_LIBS} ${PCL_LIBRARIES})<file_sep>/Correspondance2d3dPose.cc
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <tuple>
#include <vector>
#include <opencv2/opencv.hpp>
using Triangle = std::vector<int>;
struct Plane {
cv::Vec3f normal;
float d;
};
struct Pose {
cv::Vec3f rot;
cv::Vec3f trans;
};
// using Silhouette = std::vector<cv::Point2i>;
using Silhouettef = std::vector<cv::Point2f>;
struct Camera {
cv::Mat matrix = cv::Mat::eye(3, 3, CV_32FC1);
std::vector<float> ks;
};
struct Mesh {
std::vector<cv::Point3f> points;
std::vector<cv::Vec3f> normals;
std::vector<Triangle> triangles;
};
Mesh readMesh(std::string _filename) {
std::vector<cv::Point3f> points;
std::vector<cv::Vec3f> normals;
std::vector<Triangle> triangles;
std::ifstream ifs(_filename);
enum class PLYSection : int { HEADER=0, VERTEX, FACE};
std::map<PLYSection, int> counts;
PLYSection cur_section = PLYSection::HEADER;
for (std::string line; std::getline(ifs, line);) {
if (cur_section == PLYSection::HEADER) {
if (line.find("element face") == 0)
counts[PLYSection::FACE] = std::atoi(line.substr(line.rfind(" ")).c_str());
if (line.find("element vertex") == 0)
counts[PLYSection::VERTEX] = std::atoi(line.substr(line.rfind(" ")).c_str());
if (line.find("end_header") == 0) {
cur_section = PLYSection::VERTEX;
std::cout << "Vertices/Normals: " << counts[PLYSection::VERTEX] << std::endl;
std::cout << "Faces: " << counts[PLYSection::FACE] << std::endl;
}
}
else if (cur_section == PLYSection::VERTEX) {
if (0 < counts[cur_section]--) {
std::istringstream iss(line);
cv::Point3f pt;
cv::Point3f nrm;
iss >> pt.x >> pt.y >> pt.z >> nrm.x >> nrm.y >> nrm.z;
points.push_back(pt);
normals.push_back(nrm);
}
else
cur_section = PLYSection::FACE;
}
if (cur_section == PLYSection::FACE) {
if (0 == counts[cur_section]--)
break;
std::istringstream iss(line);
int n_verts, i1, i2, i3;
iss >> n_verts >> i1 >> i2 >> i3;
assert(n_verts == 3);
triangles.push_back({i1, i2, i3});
}
}
std::cout << "Vertices/Normals left: " << counts[PLYSection::VERTEX] << std::endl;
std::cout << "Faces left: " << counts[PLYSection::FACE] << std::endl;
return {points, normals, triangles};
}
cv::Mat mergeProcrustesTransform(cv::Vec2f procr_shift, float procr_scale, cv::Vec3f procr_rot) {
cv::Mat hom_2d_transform = cv::Mat::eye(3, 3, CV_32FC1);
cv::Mat rot;
cv::Rodrigues(procr_rot, rot);
cv::Mat scale = (cv::Mat_<float>(3, 3) << procr_scale, 0, 0, 0, procr_scale, 0, 0 , 0, 1);
cv::Mat shift = (cv::Mat_<float>(3, 3) << 0, 0, procr_shift(0), 0, 0, procr_shift(1), 0 , 0, 1);
hom_2d_transform = shift * scale * rot;
return hom_2d_transform;
}
// cv::Mat getHomSilhouetteTransform(Pose sil_pose, cv::Mat procr_trans) {
// }
// cv::Vec2f centerOf(Silhouettef &sil) {
// throw std::runtime_error("Not implemented");
// }
float getPlaneDepth(Plane &plane, cv::Point2f uv) {
// throw std::runtime_error("Not implemented");
return 10;
}
std::pair<cv::Mat, cv::Vec3f> map2dto3d(Camera &cam, Silhouettef &sil, Pose &sil_pose, cv::Mat transf_2d, Plane &plane) {
// cv::Mat similarity_trans = getHomSilhouetteTransform(sil_pose, transf_2d);
cv::Mat similarity_trans = transf_2d;
assert(similarity_trans.at<float>(2, 2) == 1);
cv::Point2f uv(similarity_trans.at<float>(0, 2), similarity_trans.at<float>(1, 2));
float plane_z = getPlaneDepth(plane, uv);
cv::Mat K = cam.matrix;
cv::Mat R_z = cv::Mat::eye(3, 3, CV_32FC1);
float t_x{0}, t_y{0}, t_z{plane_z};
// TODO: solve equation (1/z) * similarity_trans * K * (x, y , plane_z).t() = 1/(plane_z + t_z) * K * R_z * (x, y, plane_z).t() + (t_x, t_y, t_z)
// for R_z, t_x, t_y, t_z;
cv::Mat R_y_R_x;
cv::Rodrigues(sil_pose.rot, R_y_R_x);
cv::Mat rot = R_z * R_y_R_x;
cv::Vec3f shift(t_x, t_y, t_z);
return {rot, shift};
}
cv::Point3f mul(cv::Mat &M, const cv::Point3f &pt) {
cv::Mat vec(4, 1, CV_32FC1);
vec.at<float>(0, 0) = pt.x;
vec.at<float>(1, 0) = pt.y;
vec.at<float>(2, 0) = pt.z;
vec.at<float>(3, 0) = 1.f;
cv::Mat dst = M * vec;
return cv::Point3f(dst.at<float>(0, 0), dst.at<float>(1, 0), dst.at<float>(2, 0));
}
cv::Vec3f mul(cv::Mat &M, const cv::Vec3f &vec) {
cv::Point3f pt(vec[0], vec[1], vec[2]);
return mul(M, pt);
}
void drawMesh(cv::Mat &dst, Camera &cam, Mesh &mesh, cv::Mat cam_sp_transform) {
std::vector<cv::Point3f> vertice;
std::vector<cv::Vec3f> normal;
vertice.reserve(mesh.points.size());
normal.reserve(mesh.normals.size());
assert(vertice.size() == normal.size());
auto rect33 = cv::Rect(0, 0, 3, 3);
cv::Mat cam_sp_rot = cv::Mat::eye(3, 4, CV_32FC1);
cam_sp_transform(rect33).copyTo(cam_sp_rot(rect33));
for (const auto &vtx : mesh.points)
vertice.push_back(mul(cam_sp_transform, vtx));
for (const auto &nrm : mesh.normals)
normal.push_back(mul(cam_sp_rot, nrm));
std::vector<cv::Point2f> vertice_2d;
// FIXME: shift and scale points to dst size
cv::Mat draw_cam_matrix = cv::Mat::eye(3, 3, CV_32FC1);
draw_cam_matrix.at<float>(0, 2) = dst.cols/2.f;
draw_cam_matrix.at<float>(1, 2) = dst.rows/2.f;
draw_cam_matrix.at<float>(0, 0) = dst.cols/2.f;
draw_cam_matrix.at<float>(1, 1) = dst.cols/2.f;
cv::projectPoints(vertice, cv::Vec3f(), cv::Vec3f(), draw_cam_matrix, {}, vertice_2d);
cv::Vec3f light = cv::normalize(cv::Vec3f(1, 1, 1));
float alpha = 0.3f;
for (const auto &tri : mesh.triangles) {
cv::Vec3f avg_normal = (normal[tri[0]] + normal[tri[1]] + normal[tri[2]]) / 3;
float brightness = avg_normal.dot(light);
cv::Scalar color = cv::Scalar(255*brightness, 255*brightness, 255*brightness);
std::vector<cv::Point2i> poly{
vertice_2d[tri[0]],
vertice_2d[tri[1]],
vertice_2d[tri[2]]};
cv::Mat mask = cv::Mat::zeros(dst.size(), CV_8UC3);
cv::fillConvexPoly(mask, poly, color);
dst = dst + mask*alpha;
}
}
// Pose getPoseEstimation()
int main() {
cv::Mat rgb = cv::imread("color_4.png");
Mesh cup_mesh = readMesh("monkey.ply");
Pose sil_pose;
Silhouettef sil;
Silhouettef segment;
cv::Vec2f shift;
cv::Vec3f rot;
float scale;
// std::tie(shift, scale, rot) = procrFit(sil, segment);
cv::Mat transform_2d = mergeProcrustesTransform(shift, scale, rot);
Camera cam;
Plane plane;
auto pose_3d = map2dto3d(cam, sil, sil_pose, transform_2d, plane);
cv::Mat pose_3d_mat = cv::Mat::eye(3, 4, CV_32FC1);
pose_3d_mat.at<float>(0, 3) = pose_3d.second[0];
pose_3d_mat.at<float>(1, 3) = pose_3d.second[1];
pose_3d_mat.at<float>(2, 3) = pose_3d.second[2];
pose_3d.first.copyTo(pose_3d_mat.colRange(0, 3));
drawMesh(rgb, cam, cup_mesh, pose_3d_mat);
cv::imshow("Mesh", rgb);
while ((cv::waitKey(100) & 255 ) != 27);
return 0;
} | ed9432b8774c01ed3e69badecc1b1f27af9bbb8e | [
"CMake",
"C++"
] | 5 | C++ | klokik/PlaygroundGSoC | a8d0de12c36ebe64b6ff1a83df4da4f5bc7acfdc | 1c61443ae7c29920b66b6896cb050601f98c102e |
refs/heads/master | <file_sep># Getting-Cleaning-Data-Course-Project
Peer-graded assignment of Coursera Getting and Cleaning Data by Johns Hopkins University
# Data Source
Data collected from the accelerometers from the Samsung Galaxy S smartphone.
A full description is available [at the site](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones).
[Data for the project](https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip).
# Files
`codebook.md` describes the variables, summaries and data manipulations.
`run_analysis.R` does the following:
* Downloads and puts the file in the data folder
* Unzips the data file
* Lists the files in the folder `UCI HAR Dataset`
* Assigns variables
* Merges the training and the test sets
* Concatenates the tables by rows
* Sets variables' names
* Merges columns to get the data frame
* Extracts only the measurements on the mean and standard deviation for each measurement
* Subsets the data frame allData by extracted matches names of features
* Reads descriptive activity names from `activity_labels.txt`
* Labels the data set with descriptive names of variables
* Creates a tidy data set using `dplyr` package
`tidydata.txt` is output file of independent tidy data set with the average of each variable for each activity and each subject.
<file_sep>#Download and put the file in the data folder
if(!file.exists("C:/Users/<NAME>/Documents/data"))
{dir.create("./data")}
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(fileUrl, destfile = "./data/Dataset.zip", method = "curl")
#Unzip the data file
unzip(zipfile = "./data/Dataset.zip", exdir = "./data")
#List the files in the folder UCI HAR Dataset
path_f <- file.path("./data" , "UCI HAR Dataset")
files <- list.files(path_f, recursive = TRUE)
files
#Assign variables
dataActivityTest <- read.table(file.path(path_f, "test" , "Y_test.txt" ), header = FALSE)
dataActivityTrain <- read.table(file.path(path_f, "train", "Y_train.txt"), header = FALSE)
dataFeaturesTest <- read.table(file.path(path_f, "test" , "X_test.txt" ), header = FALSE)
dataFeaturesTrain <- read.table(file.path(path_f, "train", "X_train.txt"), header = FALSE)
dataSubjectTest <- read.table(file.path(path_f, "test" , "subject_test.txt"), header = FALSE)
dataSubjectTrain <- read.table(file.path(path_f, "train", "subject_train.txt"), header = FALSE)
#Check variables
str(dataActivityTest)
str(dataActivityTrain)
str(dataFeaturesTest)
str(dataFeaturesTrain)
str(dataSubjectTrain)
str(dataSubjectTest)
#Merges the training and the test sets
#Concatenate the tables by rows
dataActivity <- rbind(dataActivityTest, dataActivityTrain)
dataFeatures <- rbind(dataFeaturesTest, dataFeaturesTrain)
dataSubject <- rbind(dataSubjectTest, dataSubjectTrain)
#Set variables' names
names(dataActivity) <- c("activity")
FeaturesNames <- read.table(file.path(path_f, "features.txt"), head = FALSE)
names(dataFeatures) <- FeaturesNames$V2
names(dataSubject) <- c("subject")
#Merge columns to get the data frame
allData <- cbind(dataActivity, dataFeatures, dataSubject)
#Extracts only the measurements on the mean and standard deviation for each measurement
subFeaturesNames <- FeaturesNames$V2[grep("mean\\(\\)|std\\(\\)", FeaturesNames$V2)]
#Subset the data frame allData by extracted matches names of Features
allData <- subset(allData, select = c(as.character(subFeaturesNames), "subject", "activity"))
#Check the data frame structure
str(allData)
#Read descriptive activity names from "activity_labels.txt"
activityLabels <- read.table(file.path(path_f, "activity_labels.txt"), header = FALSE)
#Labels the data set with descriptive variable names
names(allData) <- gsub("^t", "time", names(allData))
names(allData) <- gsub("^f", "frequency", names(allData))
names(allData) <- gsub("Acc", "Accelerometer", names(allData))
names(allData) <- gsub("Gyro", "Gyroscope", names(allData))
names(allData) <- gsub("Mag", "Magnitude", names(allData))
names(allData) <- gsub("BodyBody", "Body", names(allData))
#Check naming
names(allData)
#Create a tidy data set using dplyr package
library(dplyr)
tidyData <- aggregate(. ~subject + activity, allData, mean)
tidyData <- tidyData[order(tidyData$subject, tidyData$activity),]
write.table(tidyData, file = "tidydata.txt", row.name = FALSE)
#Check and review the tidy data set
str(tidyData)
summary(tidyData)
View(tidyData)
<file_sep>
# Code Book
## Subject
The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years.
## Variables
1. Values of Variable Activity consist of data from “Y_train.txt” and “Y_test.txt”
1. Values of Variable Subject consist of data from “subject_train.txt” and subject_test.txt"
1. Values of Variables Features consist of data from “X_train.txt” and “X_test.txt”
1. Names of Variables Features come from “features.txt”
1. Levels of Variable Activity come from “activity_labels.txt”
The set of variables that were estimated from these signals are:
* `mean()`: Mean value
* `std()`: Standard deviation
`run_analysis.R` uses Activity, Features and Subject as part of descriptive variable names for data in data frame.
## Identifiers
`subject` - The ID of the test subject ranged form 1 to 30. The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years.
`activity` - The type of activity performed when the corresponding measurements were taken.
## Activity Labels
* `WALKING` (value `1`): subject was walking during the test.
* `WALKING_UPSTAIRS` (value `2`): subject was walking up a staircase during the test.
* `WALKING_DOWNSTAIRS` (value `3`): subject was walking down a staircase during the test.
* `SITTING` (value `4`): subject was sitting during the test.
* `STANDING` (value `5`): subject was standing during the test.
* `LAYING` (value `6`): subject was laying down during the test.
## Measurements
* `BodyAcc-mean()-X `
* `tBodyAcc-mean()-Y `
* `tBodyAcc-mean()-Z `
* `tBodyAcc-std()-X `
* `tBodyAcc-std()-Y `
* `tBodyAcc-std()-Z `
* `tGravityAcc-mean()-X `
* `tGravityAcc-mean()-Y `
* `tGravityAcc-mean()-Z `
* `tGravityAcc-std()-X `
* `tGravityAcc-std()-Y `
* `tGravityAcc-std()-Z `
* `tBodyAccJerk-mean()-X `
* `tBodyAccJerk-mean()-Y `
* `tBodyAccJerk-mean()-Z `
* `tBodyAccJerk-std()-X `
* `tBodyAccJerk-std()-Y `
* `tBodyAccJerk-std()-Z `
* `tBodyGyro-mean()-X `
* `tBodyGyro-mean()-Y `
* `tBodyGyro-mean()-Z `
* `tBodyGyro-std()-X `
* `tBodyGyro-std()-Y `
* `tBodyGyro-std()-Z `
* `tBodyGyroJerk-mean()-X `
* `tBodyGyroJerk-mean()-Y `
* `tBodyGyroJerk-mean()-Z `
* `tBodyGyroJerk-std()-X `
* `tBodyGyroJerk-std()-Y `
* `tBodyGyroJerk-std()-Z `
* `tBodyAccMag-mean() `
* `tBodyAccMag-std() `
* `tGravityAccMag-mean() `
* `tGravityAccMag-std() `
* `tBodyAccJerkMag-mean() `
* `tBodyAccJerkMag-std() `
* `tBodyGyroMag-mean() `
* `tBodyGyroMag-std() `
* `tBodyGyroJerkMag-mean() `
* `tBodyGyroJerkMag-std() `
* `fBodyAcc-mean()-X `
* `fBodyAcc-mean()-Y `
* `fBodyAcc-mean()-Z `
* `fBodyAcc-std()-X `
* `fBodyAcc-std()-Y `
* `fBodyAcc-std()-Z `
* `fBodyAccJerk-mean()-X `
* `fBodyAccJerk-mean()-Y `
* `fBodyAccJerk-mean()-Z `
* `fBodyAccJerk-std()-X `
* `fBodyAccJerk-std()-Y `
* `fBodyAccJerk-std()-Z `
* `fBodyGyro-mean()-X `
* `fBodyGyro-mean()-Y `
* `fBodyGyro-mean()-Z `
* `fBodyGyro-std()-X `
* `fBodyGyro-std()-Y `
* `fBodyGyro-std()-Z `
* `fBodyAccMag-mean() `
* `fBodyAccMag-std() `
* `fBodyBodyAccJerkMag-mean() `
* `fBodyBodyAccJerkMag-std() `
* `fBodyBodyGyroMag-mean() `
* `fBodyBodyGyroMag-std() `
* `fBodyBodyGyroJerkMag-mean()`
* `fBodyBodyGyroJerkMag-std() `
* `subject `
* `activity `
## Tidy Data Structure
* `subject`
* `activity`
* `timeBodyAccelerometer-mean()-X `
* `timeBodyAccelerometer-mean()-Y `
* `timeBodyAccelerometer-mean()-Z `
* `timeBodyAccelerometer-std()-X `
* `timeBodyAccelerometer-std()-Y `
* `timeBodyAccelerometer-std()-Z `
* `timeGravityAccelerometer-mean()-X `
* `timeGravityAccelerometer-mean()-Y `
* `timeGravityAccelerometer-mean()-Z `
* `timeGravityAccelerometer-std()-X `
* `timeGravityAccelerometer-std()-Y `
* `timeGravityAccelerometer-std()-Z `
* `timeBodyAccelerometerJerk-mean()-X `
* `timeBodyAccelerometerJerk-mean()-Y `
* `timeBodyAccelerometerJerk-mean()-Z `
* `timeBodyAccelerometerJerk-std()-X `
* `timeBodyAccelerometerJerk-std()-Y `
* `timeBodyAccelerometerJerk-std()-Z `
* `timeBodyGyroscope-mean()-X `
* `timeBodyGyroscope-mean()-Y `
* `timeBodyGyroscope-mean()-Z `
* `timeBodyGyroscope-std()-X `
* `timeBodyGyroscope-std()-Y `
* `timeBodyGyroscope-std()-Z `
* `timeBodyGyroscopeJerk-mean()-X `
* `timeBodyGyroscopeJerk-mean()-Y `
* `timeBodyGyroscopeJerk-mean()-Z `
* `timeBodyGyroscopeJerk-std()-X `
* `timeBodyGyroscopeJerk-std()-Y `
* `timeBodyGyroscopeJerk-std()-Z `
* `timeBodyAccelerometerMagnitude-mean() `
* `timeBodyAccelerometerMagnitude-std() `
* `timeGravityAccelerometerMagnitude-mean() `
* `timeGravityAccelerometerMagnitude-std() `
* `timeBodyAccelerometerJerkMagnitude-mean() `
* `timeBodyAccelerometerJerkMagnitude-std() `
* `timeBodyGyroscopeMagnitude-mean() `
* `timeBodyGyroscopeMagnitude-std() `
* `timeBodyGyroscopeJerkMagnitude-mean() `
* `timeBodyGyroscopeJerkMagnitude-std() `
* `frequencyBodyAccelerometer-mean()-X `
* `frequencyBodyAccelerometer-mean()-Y `
* `frequencyBodyAccelerometer-mean()-Z `
* `frequencyBodyAccelerometer-std()-X `
* `frequencyBodyAccelerometer-std()-Y `
* `frequencyBodyAccelerometer-std()-Z `
* `frequencyBodyAccelerometerJerk-mean()-X `
* `frequencyBodyAccelerometerJerk-mean()-Y `
* `frequencyBodyAccelerometerJerk-mean()-Z `
* `frequencyBodyAccelerometerJerk-std()-X `
* `frequencyBodyAccelerometerJerk-std()-Y `
* `frequencyBodyAccelerometerJerk-std()-Z `
* `frequencyBodyGyroscope-mean()-X `
* `frequencyBodyGyroscope-mean()-Y `
* `frequencyBodyGyroscope-mean()-Z `
* `frequencyBodyGyroscope-std()-X `
* `frequencyBodyGyroscope-std()-Y `
* `frequencyBodyGyroscope-std()-Z `
* `frequencyBodyAccelerometerMagnitude-mean() `
* `frequencyBodyAccelerometerMagnitude-std() `
* `frequencyBodyAccelerometerJerkMagnitude-mean()`
* `frequencyBodyAccelerometerJerkMagnitude-std() `
* `frequencyBodyGyroscopeMagnitude-mean() `
* `frequencyBodyGyroscopeMagnitude-std() `
* `frequencyBodyGyroscopeJerkMagnitude-mean() `
* `frequencyBodyGyroscopeJerkMagnitude-std()`
## Final Dataset
* str(tidyData)
* summary(tidyData)
* View(tidyData)
| 4e79b5109567e45a6d956cfe138e449e819da5b1 | [
"Markdown",
"R"
] | 3 | Markdown | alekseidudin/Getting-Cleaning-Data-Course-Project | c4210da28ce558dce1a171937c5f7ac27e50c5ec | f3c818c77ec787c8efdcff503b76de8b5e4922b1 |
refs/heads/master | <file_sep>#!/usr/bin/env python
#*********************************************************************
#*
#* Copyright (c) 2014-2016
#* All rights reserved.
#*
#* Software License Agreement (BSD License)
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions
#* are met:
#*
#* * Redistributions of source code must retain the above copyright
#* notice, this list of conditions and the following disclaimer.
#* * Redistributions in binary form must reproduce the above
#* copyright notice, this list of conditions and the following
#* disclaimer in the documentation and/or other materials provided
#* the distribution.
#* * Neither the name of the author nor the names of its
#* contributors may be used to endorse or promote products derived
#* from this software without specific prior written permission.
#*
#* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
#* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#* POSSIBILITY OF SUCH DAMAGE.
#*
#* Author: <NAME> on Mar, 2016
#*********************************************************************/
from controllers.control_position import ControlPosition
import thread
import threading
import time
import rospy
from math import *
from mavros import setpoint as SP
from tf.transformations import quaternion_from_euler
class ControlPositionPX4(ControlPosition):
"""
This class sends position targets to FCU's position controller
"""
def __init__(self, tollerance=0.05, rate=10, topic='/mavros/local_position/pose', name='pos_controller'):
ControlPosition.__init__(self, tollerance, rate, topic, name)
# publisher for mavros/setpoint_position/local
self.pub = SP.get_pub_position_local(queue_size=10)
try:
thread.start_new_thread(self.control_loop, ())
except:
fault("Error: Unable to start thread")
# TODO(simon): Clean this up.
self.done = False
self.done_evt = threading.Event()
def control_loop(self):
rate = rospy.Rate(self.rate) # 10hz
msg = SP.PoseStamped(
header=SP.Header(
frame_id="base_footprint", # no matter, plugin don't use TF
stamp=rospy.Time.now()), # stamp should update
)
while not rospy.is_shutdown():
msg.pose.position.x = self.x_ref
msg.pose.position.y = self.y_ref
msg.pose.position.z = self.z_ref
# For demo purposes we will lock yaw/heading to north.
yaw_degrees = 0 # North
yaw = radians(yaw_degrees)
quaternion = quaternion_from_euler(0, 0, yaw)
msg.pose.orientation = SP.Quaternion(*quaternion)
self.pub.publish(msg)
rate.sleep()
def set(self, x, y, z, delay=0.0, wait=True):
self.done = False
self.x_ref = x
self.y_ref = y
self.z_ref = z
if wait:
rate = rospy.Rate(5)
t_init = rospy.Time.now()
while not self.done and not rospy.is_shutdown():
elapsed_time = rospy.Time.now() - t_init
if elapsed_time >= delay:
self.done = True
rate.sleep()
#time.sleep(delay)
<file_sep>cmake_minimum_required(VERSION 2.8.3)
project(mavros_controllers)
find_package(catkin REQUIRED COMPONENTS
mavros
roscpp
rospy
tf
dynamic_reconfigure
message_generation
)
catkin_python_setup()
## Generate dynamic reconfigure parameters in the 'cfg' folder
generate_dynamic_reconfigure_options(
cfg/mavros_controllers.cfg
#cfg/DynReconf2.cfg
)
catkin_package(
INCLUDE_DIRS
# LIBRARIES mavros_controllers
CATKIN_DEPENDS mavros roscpp rospy tf message_runtime
# DEPENDS system_lib
)
include_directories(
${catkin_INCLUDE_DIRS}
)
<file_sep>#!/usr/bin/env python
#*********************************************************************
#*
#* Copyright (c) 2014-2016
#* All rights reserved.
#*
#* Software License Agreement (BSD License)
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions
#* are met:
#*
#* * Redistributions of source code must retain the above copyright
#* notice, this list of conditions and the following disclaimer.
#* * Redistributions in binary form must reproduce the above
#* copyright notice, this list of conditions and the following
#* disclaimer in the documentation and/or other materials provided
#* the distribution.
#* * Neither the name of the author nor the names of its
#* contributors may be used to endorse or promote products derived
#* from this software without specific prior written permission.
#*
#* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
#* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#* POSSIBILITY OF SUCH DAMAGE.
#*
#* Author: <NAME> on Mar, 2016
#*********************************************************************/
import rospy
import mavros
import thread
import threading
from math import *
from mavros import setpoint as SP
from geometry_msgs.msg import TransformStamped
from mavros import command
import os
import xmlrpclib
class ControlPosition:
"""
This class sends velocity targets to FCU's position controller
"""
def __init__(self, tolerance=0.05, rate=10, topic='/mavros/local_position/pose', name='pos_controller'):
self.tolerance = tolerance #meters
self.rate = rate #rate
self.name = name #name
self.wp_reached = True
self.task_done = True
self.done_evt = threading.Event()
self.x_ref = 0.0
self.y_ref = 0.0
self.z_ref = 0.0
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.pose_top = 0
self.transf_top = 0
self.m = xmlrpclib.ServerProxy(os.environ['ROS_MASTER_URI'])
code, statusMessage, topicTypes = self.m.getTopicTypes(self.name)
#print topicTypes
for topic_pair in topicTypes:
if topic_pair[0] == topic:
if topic_pair[1] == 'geometry_msgs/TransformStamped':
self.transf_top = 1
break
if topic_pair[1] == 'geometry_msgs/PoseStamped':
self.pose_top = 1
break
if not self.pose_top and not self.transf_top:
rospy.logerr("ERROR: topic %s has a wrong data type", topic)
rospy.loginfo("Controller input on topic: %s", topic)
rospy.loginfo("transf_top: %d", self.transf_top)
rospy.loginfo("pose_top: %d", self.pose_top)
# publisher for mavros/setpoint_velocity/cmd_vel
self.pub = None #empty publisher to be defined in the child class
mavros.set_namespace()
# subscriber for mavros/local_position/local
if self.pose_top:
self.sub = rospy.Subscriber(topic,#topic must be a pose topic!
SP.PoseStamped, self.local_pos_callback)
else:
self.sub = rospy.Subscriber(topic,#topic must be a pose topic!
TransformStamped, self.local_pos_callback)
def __enter__(self):
return self
def __exit__(self, *err):
return True
def control_loop(self):
print "virtual method"
"""
This method sends reference targets to FCU
"""
def _arm(self, state):
try:
ret = command.arming(value=state)
except rospy.ServiceException as ex:
fault(ex)
if not ret.success:
fault("Request failed. Check mavros logs")
return ret
def set(self):
print "virtual method"
"""
This method sets the position reference
"""
def local_pos_callback(self, topic):
if self.pose_top:
#print 'I am in the callback!'
self.x = topic.pose.position.x
self.y = topic.pose.position.y
self.z = topic.pose.position.z
else:
#print 'I am in the callback!'
self.x = topic.transform.translation.x
self.y = topic.transform.translation.y
self.z = topic.transform.translation.z
rospy.loginfo("Following values read -- x: %f y: %f z: %f", self.x, self.y, self.z)
rospy.loginfo("Errors: %f %f %f", self.x - self.x_ref, self.y - self.y_ref, self.z - self.z_ref)
if self.is_near('X', self.x, self.x_ref, self.tolerance) and \
self.is_near('Y', self.y, self.y_ref, self.tolerance) and \
self.is_near('Z', self.z, self.z_ref, self.tolerance) :
self.wp_reached = True
self.done_evt.set()
def is_near(self, msg, x, y, tolerance):
rospy.logdebug("Position %s: local: %d, target: %d, abs diff: %d",
msg, x, y, abs(x - y))
#print("Position %s: local: %d, target: %d, abs diff: %d",
# msg, x, y, abs(x - y))
return abs(x - y) < tolerance
def get_x(self):
return self.x
def get_y(self):
return self.y
def get_z(self):
return self.z
def is_reached(self):
return self.wp_reached
def is_done(self):
return self.task_done
<file_sep>#!/usr/bin/env python
#*********************************************************************
#*
#* Copyright (c) 2014-2016
#* All rights reserved.
#*
#* Software License Agreement (BSD License)
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions
#* are met:
#*
#* * Redistributions of source code must retain the above copyright
#* notice, this list of conditions and the following disclaimer.
#* * Redistributions in binary form must reproduce the above
#* copyright notice, this list of conditions and the following
#* disclaimer in the documentation and/or other materials provided
#* the distribution.
#* * Neither the name of the author nor the names of its
#* contributors may be used to endorse or promote products derived
#* from this software without specific prior written permission.
#*
#* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
#* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#* POSSIBILITY OF SUCH DAMAGE.
#*
#* Author: <NAME>, <NAME>, and <NAME> on Mar, 2016
#*********************************************************************/
from tools.pid import PID
from controllers.control_position import ControlPosition
import thread
#import threading
import time
#from math import *
import rospy
from mavros import setpoint as SP
from tf.transformations import euler_from_quaternion
class ControlPositionPid(ControlPosition):
"""
This class sends velocity targets to FCU's position controller
"""
def __init__(self, XY_P, XY_I, XY_D, Z_P, Z_I, Z_D, tolerance=0.05, rate=10, sample_time=0.1, topic='/mavros/local_position/pose', name='pos_controller'):
ControlPosition.__init__(self, tolerance, rate, topic, name)
self.sample_time = sample_time
# publisher for mavros/setpoint_velocity/cmd_vel
self.pub = SP.get_pub_velocity_cmd_vel(queue_size=10)
self.pidx = PID(XY_P, XY_I, XY_D)
self.pidy = PID(XY_P, XY_I, XY_D)
self.pidz = PID(Z_P, Z_I, Z_D)
self.pidx.setSampleTime(self.sample_time)
self.pidy.setSampleTime(self.sample_time)
self.pidz.setSampleTime(self.sample_time)
self.x = 0.0
self.y = 0.0
self.z = 0.0
try:
thread.start_new_thread(self.control_loop, ())
except:
fault("Error: Unable to start thread")
def control_loop(self):
rate = rospy.Rate(self.rate) # 10hz
msg = SP.TwistStamped(
header=SP.Header(
frame_id="base_footprint", # no matter, plugin don't use TF
stamp=rospy.Time.now()), # stamp should update
)
#while not self.task_done:
while not rospy.is_shutdown():
if not self.task_done:
self.pidx.update(self.x)
self.pidy.update(self.y)
self.pidz.update(self.z)
msg.twist.linear.x = self.pidx.output
msg.twist.linear.y = self.pidy.output
msg.twist.linear.z = self.pidz.output
#print self.name + " is publishing"
self.pub.publish(msg)
rate.sleep()
def set(self, x, y, z, delay=0.0):
self.task_done = False
self.wp_reached = False
self.x_ref = x
self.y_ref = y
self.z_ref = z
self.pidx.SetPoint=self.x_ref
self.pidy.SetPoint=self.y_ref
self.pidz.SetPoint=self.z_ref
rate = rospy.Rate(self.rate)
#going to the wp
while not self.wp_reached and not rospy.is_shutdown():
rate.sleep()
#stay in the wp
wp_duration = rospy.Duration.from_sec(delay)
t_init = rospy.Time.now()
#print 'waypoint reached'
while not self.task_done and not rospy.is_shutdown():
elapsed_time = rospy.Time.now() - t_init
if elapsed_time >= wp_duration:
self.task_done = True
rate.sleep()
#print 'task done'
def update_gains(self, P_Z, I_Z, D_Z, P_XY, I_XY, D_XY):
self.pidz.setKp(P_Z)
self.pidz.setKi(I_Z)
self.pidz.setKd(D_Z)
self.pidx.setKp(P_XY)
self.pidx.setKi(I_XY)
self.pidx.setKd(D_XY)
self.pidy.setKp(P_XY)
self.pidy.setKi(I_XY)
self.pidy.setKd(D_XY)
<file_sep>#!/usr/bin/env python
# coding=utf-8
#*********************************************************************
#* MIT License
#*
#* Copyright (c) 2016 <NAME>
#*
#* Permission is hereby granted, free of charge, to any person obtaining a copy
#* of this software and associated documentation files (the "Software"), to deal
#* in the Software without restriction, including without limitation the rights
#* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#* copies of the Software, and to permit persons to whom the Software is
#* furnished to do so, subject to the following conditions:
#*
#* The above copyright notice and this permission notice shall be included in all
#* copies or substantial portions of the Software.
#*
#* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#* SOFTWARE.
#*********************************************************************
PKG = 'mavros_controllers'
NAME = 'waypoint_navigation'
import rospy
import time
import csv
from std_msgs.msg import String
from visualization_msgs.msg import MarkerArray, Marker
import rospkg
from collections import namedtuple
from controllers.control_position_pid import ControlPositionPid
from controllers.control_position_i_pd import ControlPositionIPD
from controllers.control_position_px4 import ControlPositionPX4
from controllers.control_position_pid_w_dist import ControlPositionPidWithDistance
#from controllers.control_position_cr import ControlPositionCR
def read_wp_from_csv():
# get an instance of RosPack with the default search paths
rospack = rospkg.RosPack()
filename = rospy.get_param('filename', rospack.get_path(PKG) + '/cfg/waypoints.csv')
#rospy.loginfo("loading waypoints from %s",filename)
print "loading waypoints from " + filename
wps = namedtuple('Waypoint', 'id x, y, z, yaw, time')
reader = csv.reader(open(filename, "rb"))
next(reader) #parse the first line
waypoints = []
for wp in map(wps._make, reader):
print 'waypoint --> x:' + wp.x + '\ty:' + wp.y + '\tz:' + wp.z + '\tyaw:' + wp.yaw + '\ttime:' + wp.time
waypoints.append(wp)
return waypoints;
def choose_pos_controller(pos_controller_type='PX4', tolerance=0.05, rate=10):
print 'controller ' + pos_controller_type + ' chosen..'
if pos_controller_type == 'PX4':
controller = ControlPositionPX4(tolerance, rate)
elif pos_controller_type == 'PID':
XY_P = rospy.get_param('XY_P',1.25)
XY_I = rospy.get_param('XY_I', 0.0)
XY_D = rospy.get_param('XY_D', 0.1)
Z_P = rospy.get_param('Z_P', 1.25)
Z_I = rospy.get_param('Z_I', 0.001)
Z_D = rospy.get_param('Z_D', 0.1)
controller = ControlPositionPid(XY_P, XY_I, XY_D, Z_P, Z_I, Z_D, tolerance, rate)
elif pos_controller_type == 'PIDwD':
XY_P = rospy.get_param('XY_P',1.25)
XY_I = rospy.get_param('XY_I', 0.0)
XY_D = rospy.get_param('XY_D', 0.1)
Z_P = rospy.get_param('Z_P', 1.25)
Z_I = rospy.get_param('Z_I', 0.001)
Z_D = rospy.get_param('Z_D', 0.1)
controller = ControlPositionPidWithDistance(XY_P, XY_I, XY_D, Z_P, Z_I, Z_D, tolerance, rate)
elif pos_controller_type == 'I-PD':
XY_P = rospy.get_param('XY_P',1.25)
XY_I = rospy.get_param('XY_I', 0.0)
XY_D = rospy.get_param('XY_D', 0.1)
Z_P = rospy.get_param('Z_P', 1.25)
Z_I = rospy.get_param('Z_I', 0.001)
Z_D = rospy.get_param('Z_D', 0.1)
controller = ControlPositionIPD(XY_P, XY_I, XY_D, Z_P, Z_I, Z_D, tolerance, rate)
else:
rospy.logerr('controller ' + pos_controller_type + ' not found')
raise NameError('controller ' + pos_controller_type + ' not found')
#rospy.signal_shutdown('controller ' + pos_controller_type + ' not found')
print 'controller ' + pos_controller_type + ' loaded..'
return controller;
def main_loop():
rospy.init_node(NAME)
tolerance = rospy.get_param('tolerance', 0.1)
rate = rospy.get_param('rate', 10)
#pos_controller_type = rospy.get_param('pos_controller_type', 'PX4')
wayps = read_wp_from_csv()
#controller = ControlPositionPidWithDistance(1.25, 0.0, 0.1, 2.0, 0.0, 0.2, tolerance, rate)#choose_pos_controller(pos_controller_type, tolerance, rate)
#takeoff_controller = ControlPositionPid(1.25, 0.0, 0.1, 2.0, 0.0, 0.2, 0.3, rate)
if(safety_check.isSafe()):
#take-off
takeoff_controller = ControlPositionPid(1.25, 0.0, 0.1, 1.0, 0.0, 0.0, 0.3, rate)
time.sleep(0.5)
print 'take-off waypoint --> x:' + str(takeoff_controller.get_x()) + '\ty:' + str(takeoff_controller.get_y())
takeoff_controller.set(takeoff_controller.get_x(), takeoff_controller.get_y(), 1.0, 0.2)
takeoff_controller.done = True
#waypoints
with ControlPositionPidWithDistance(1.25, 0.0, 0.1, 2.0, 0.0, 0.2, tolerance, rate) as controller:
#with ControlPositionCR('PIDwD', tolerance, rate, 1.25, 0.0, 0.1, 2.0, 0.0, 0.2) as controller:
for wp in wayps:
print 'UAV moving to WP: ' + wp.id
controller.set(float(wp.x), float(wp.y), float(wp.z), float(wp.time))
controller.done = True
# Simulate a slow landing.
controller.set(0.0, 0.0, 0.8, 0.02)
controller.set(0.0, 0.0, 0.3, 0.02)
controller.set(0.0, 0.0, 0.2, 0.02)
controller.set(0.0, 0.0, 0.1, 0.02)
controller.set(0.0, 0.0, 0.0, 0.02)
controller.set(0.0, 0.0, -0.1, 0.02)
rospy.loginfo("Bye!")
if __name__ == '__main__':
try:
main_loop()
except rospy.ROSInterruptException:
pass
<file_sep>#!/usr/bin/env python
#*********************************************************************
#*
#* Copyright (c) 2014-2016
#* All rights reserved.
#*
#* Software License Agreement (BSD License)
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions
#* are met:
#*
#* * Redistributions of source code must retain the above copyright
#* notice, this list of conditions and the following disclaimer.
#* * Redistributions in binary form must reproduce the above
#* copyright notice, this list of conditions and the following
#* disclaimer in the documentation and/or other materials provided
#* the distribution.
#* * Neither the name of the author nor the names of its
#* contributors may be used to endorse or promote products derived
#* from this software without specific prior written permission.
#*
#* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
#* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
#* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#* POSSIBILITY OF SUCH DAMAGE.
#*
#* Author: <NAME> and <NAME> on Mar, 2016
#*********************************************************************/
from tools.ipd import IPD
from controllers.control_position import ControlPosition
#import thread
#import threading
import thread
import threading
import time
#from math import *
import rospy
from mavros import setpoint as SP
from tf.transformations import euler_from_quaternion
class ControlPositionIPD(ControlPosition):
"""
This class sends velocity targets to FCU's position controller
"""
def __init__(self, XY_P, XY_I, XY_D, Z_P, Z_I, Z_D, tollerance=0.05, rate=10, sample_time=0.1, topic='/mavros/local_position/pose', name='pos_controller'):
ControlPosition.__init__(self, tollerance, rate, topic, name)
self.sample_time = sample_time
# publisher for mavros/setpoint_velocity/cmd_vel
self.pub = SP.get_pub_velocity_cmd_vel(queue_size=10)
self.ipdx = IPD(XY_P, XY_I, XY_D)
self.ipdy = IPD(XY_P, XY_I, XY_D)
self.ipdz = IPD(Z_P, Z_I, Z_D)
self.x = 0.0
self.y = 0.0
self.z = 0.0
try:
thread.start_new_thread(self.control_loop, ())
except:
fault("Error: Unable to start thread")
# TODO(simon): Clean this up.
self.done = False
self.done_evt = threading.Event()
def control_loop(self):
self.ipdx.setSampleTime(self.sample_time)
self.ipdy.setSampleTime(self.sample_time)
self.ipdz.setSampleTime(self.sample_time)
rate = rospy.Rate(self.rate) # 10hz
msg = SP.TwistStamped(
header=SP.Header(
frame_id="base_footprint", # no matter, plugin don't use TF
stamp=rospy.Time.now()), # stamp should update
)
while not rospy.is_shutdown():
self.ipdx.update(self.x)
self.ipdy.update(self.y)
self.ipdz.update(self.z)
msg.twist.linear.x = self.ipdx.output
msg.twist.linear.y = self.ipdy.output
msg.twist.linear.z = self.ipdz.output
self.pub.publish(msg)
rate.sleep()
def set(self, x, y, z, delay=0.0, wait=True):
self.done = False
self.x_ref = x
self.y_ref = y
self.z_ref = z
self.ipdx.SetPoint=self.x_ref
self.ipdy.SetPoint=self.y_ref
self.ipdz.SetPoint=self.z_ref
if wait:
rate = rospy.Rate(5)
while not self.done and not rospy.is_shutdown():
rate.sleep()
time.sleep(delay)
def update_gains(self, P_Z, I_Z, D_Z, P_XY, I_XY, D_XY):
self.ipdz.setKp(P_Z)
self.ipdz.setKi(I_Z)
self.ipdz.setKd(D_Z)
self.ipdx.setKp(P_XY)
self.ipdx.setKi(I_XY)
self.ipdx.setKd(D_XY)
self.ipdy.setKp(P_XY)
self.ipdy.setKi(I_XY)
self.ipdy.setKd(D_XY)
<file_sep>#!/usr/bin/env python
PACKAGE = "issia_control_uav"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
gen.add("PC_P_Z", double_t, 0, "PID position control, proportional gain on z axis", 1.0, 0, 10)
gen.add("PC_I_Z", double_t, 0, "PID position control, integrative gain on z axis", 0.0, 0, 10)
gen.add("PC_D_Z", double_t, 0, "PID position control, derivative gain on z axis", 0.0, 0, 10)
gen.add("PC_P_XY", double_t, 0, "PID position control, proportional gain on xy axes", 1.0, 0, 10)
gen.add("PC_I_XY", double_t, 0, "PID position control, integrative gain on xy axes", 0.00, 0, 10)
gen.add("PC_D_XY", double_t, 0, "PID position control, derivative gain on xy axes", 0.0, 0, 10)
exit(gen.generate(PACKAGE, "issia_control_uav", "issia_control_uav"))
<file_sep># mavros_controllers
This ROS package implements several position controllers for Micro Aerial Vehicles.
| 567eba73caa58da4fb88968ac4d687e35666d975 | [
"Markdown",
"Python",
"CMake"
] | 8 | Python | gitAnto/mavros_controllers | 2e6967a9e9ab65fc457afdbc591603728f2a6b63 | 66034c807032815e3f7a444132e272ff71c75a7b |
refs/heads/master | <file_sep>$(function(){
$('#image').dblclick(function(){//appel de la fonction au double clic sur l'image
$('#image').css('width', '500px')//change la taille de l'image à 500px
})
})
| b14aebddc0dab48dea293c2f40564062417b1c53 | [
"JavaScript"
] | 1 | JavaScript | Tonyio83/exercice2JQuery2 | bd76936ed8645d2e469b904618e2a0d11a9b2029 | 186637728acd79f1144ff1345614774d622017bd |
refs/heads/master | <repo_name>lukeyoung92/Silverado<file_sep>/a3/checkout_page.php
<?php include_once('Functions/checkout_functions.php');?>
<!DOCTYPE html>
<html>
<head>
<?php include_once('Includes/head_data.php');?>
<title>Checkout Page</title>
</head>
<body>
<?php include_once('Includes/header.php');include_once('Includes/navbar.php');?>
<main>
<div class="block1">
<h1>Customer Details</h1>
<div class="block2">
<form action='' method='post'>
First Name:<br>
<input type="text" name="fname" pattern="^[A-Za-z]+$" required>
<br><br>
Last Name:<br>
<input type="text" name="lname" pattern="^[A-Za-z]+$" required>
<br><br>
Email Address:<br>
<input type="email" name="email" required>
<br><br>
Phone Number:<br>
<input type="text" name="phone" pattern="^[04][0-9]{9}|[04][0-9]{2}[ ]{1}[0-9]{3}[ ]{1}[0-9]{3}$" required>
<br><br>
<li><input type="submit"></li>
</form>
<li><form action="http://titan.csit.rmit.edu.au/~s3330458/wp/a3/shoppingcart_page.php">
<input type='submit' value='Return to Cart'/>
</form></li>
<?php saveData(); ?>
</div>
</div>
</main>
<?php include_once('Includes/footer.php');?>
</body>
</html><file_sep>/a3/reservation_page.php
<?php include_once('Functions/reservation_functions.php');?>
<!DOCTYPE html>
<html>
<head>
<?php include_once('Includes/head_data.php');?>
<title>Reservation Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<?php include_once('Includes/reservation_js.php');?>
</head>
<body>
<?php include_once('Includes/header.php');include_once('Includes/navbar.php');?>
<main>
<div class="block1">
<? print_r($_SESSION['cart']);?>
<h1>Book Screening</h1>
<div class="block2">
<?php echo $bookingMessage; ?>
<form action='reservation_page.php' method='get'>
<p>Movie<br>
<select name='movie' id='movie'>
<option value=''>All movies</option>
<option value='AC'>MI: Rouge Nation</option>
<option value='AF'>Girlhood</option>
<option value='CH'>Inside Out</option>
<option value='RC'>Trainwreck</option>
</select>
</p>
<p>
Day<br>
<select name='day' id="day">
<option value=''>Please Select</option>
<option value='Monday'>Monday</option>
<option value='Tuesday'>Tuesday</option>
<option value='Wednesday'>Wednesday</option>
<option value='Thursday'>Thursday</option>
<option value='Friday'>Friday</option>
<option value='Saturday'>Saturday</option>
<option value='Sunday'>Sunday</option>
</select>
</p>
<p>
Time<br>
<select name='time' id="time">
<option value=''>Please Select</option>
<option value='1PM'>1PM</option>
<option value='3PM'>3PM</option>
<option value='6PM'>6PM</option>
<option value='9PM'>9PM</option>
<option value='12PM'>12PM</option>
</select>
</p>
<p>
Adult seats<br>
<select name='seat[Adult]'>
<option value=''>Please Select</option>
<?php for ($i=1;$i<=10;$i++) echo "<option value=$i>$i</option>"; ?>
</select>
</p>
<p>
Child seats<br>
<select name='seat[Concession]'>
<option value='0'>Please Select</option>
<?php for ($i=1;$i<=10;$i++) echo "<option value=$i>$i</option>"; ?>
</select>
</p>
<p>
First Class - Adult seats<br>
<select name='seat[FAdult]'>
<option value='0'>Please Select</option>
<?php for ($i=1;$i<=10;$i++) echo "<option value=$i>$i</option>"; ?>
</select>
</p>
<p>
First Class - Child seats<br>
<select name='seat[FChild]'>
<option value='0'>Please Select</option>
<?php for ($i=1;$i<=10;$i++) echo "<option value=$i>$i</option>"; ?>
</select>
</p>
<p>
Beanbag - Two Adults<br>
<select name='seat[BeanbagT1]'>
<option value='0'>Please Select</option>
<?php for ($i=1;$i<=10;$i++) echo "<option value=$i>$i</option>"; ?>
</select>
</p>
<p>
Beanbag - One Adult + One Child<br>
<select name='seat[BeanbagT2]'>
<option value='0'>Please Select</option>
<?php for ($i=1;$i<=10;$i++) echo "<option value=$i>$i</option>"; ?>
</select>
</p>
<p>
Beanbag - Three Children<br>
<select name='seat[BeanbagT3]'>
<option value='0'>Please Select</option>
<?php for ($i=1;$i<=10;$i++) echo "<option value=$i>$i</option>"; ?>
</select>
</p>
<p>
<li><input type='submit' value='Book Tickets'/></li>
</p>
</form>
<?php
if(isset($_SESSION['cart'][0]))
{
echo "<li><form action='http://titan.csit.rmit.edu.au/~s3330458/wp/a3/shoppingcart_page.php'>
<input type='submit' value='Go to Cart'/>
</form></li>";
}
;?>
</div>
</div>
</main>
<?php include_once('Includes/footer.php');?>
</body>
</html><file_sep>/a3/moviesselection_page.php
<?php session_start();?>
<!DOCTYPE html>
<html>
<head>
<?php include_once('Includes/head_data.php');?>
<link href="selectstyle.css" rel="stylesheet" type="text/css" />
<title>Movies Selection Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<?php include_once('Includes/moviesselection_js.php');?>
</head>
<body>
<?php include_once('Includes/header.php');include_once('Includes/navbar.php');?>
<main>
<div class="block1">
<select id='movie'>
<option value=''>All movies</option>
<option value='AC'>MI: Rouge Nation</option>
<option value='AF'>Girlhood</option>
<option value='CH'>Inside Out</option>
<option value='RC'>Trainwreck</option>
</select>
<select id='day'>
<option value=''>Any Day</option>
<option value='Monday'>Monday</option>
<option value='Tuesday'>Tuesday</option>
<option value='Wednesday'>Wednesday</option>
<option value='Thursday'>Thursday</option>
<option value='Saturday'>Saturday</option>
<option value='Sunday'>Sunday</option>
</select>
<button id='movie-search'>Search for movies</button>
<div id='data'>
</div>
</div>
</main>
<?php include_once('Includes/footer.php');?>
</body>
</html><file_sep>/a3/printtickets_page.php
<?php include_once('Functions/printtickets_functions.php');?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="A2 Silverado">
<meta name="author" content="<NAME>">
<?php
for($i=0; $i<count($_SESSION['cart']); $i++)
{
printTicketHead($i); printTicketParts($i,'Adult'); printTicketParts($i,'Concession'); printTicketParts($i,'FAdult'); printTicketParts($i,'FChild'); printTicketParts($i,'BeanbagT1'); printTicketParts($i,'BeanbagT2'); printTicketParts($i,'BeanbagT3');
}
; ?>
<?php $_SESSION = array(); ?>
<?php include_once('ticketstyle.css');?>
</html><file_sep>/a2/javascript.js
function calculatePrice(button)
{
var numSeats;
var seatprice;
seatprice=12;
if(button == '-')
{
numSeats = parseInt(document.getElementById('seats').value);
if(numSeats>0)
{
document.getElementById('seats').value--;
numSeats = parseInt(document.getElementById('seats').value);
document.getElementById('price').value = numSeats*seatprice;
document.getElementById('total').value = document.getElementById('price').value;
}
}
else if(button == '+')
{
document.getElementById('seats').value++;
numSeats = parseInt(document.getElementById('seats').value);
document.getElementById('price').value = numSeats*seatprice;
document.getElementById('total').value = document.getElementById('price').value;
}
else if(button == '-1')
{
numSeats = parseInt(document.getElementById('seats1').value);
if(numSeats>0)
{
document.getElementById('seats1').value--;
}
}
else if(button == '+1')
{
document.getElementById('seats1').value++;
}
else if(button == '-2')
{
numSeats = parseInt(document.getElementById('seats2').value);
if(numSeats>0)
{
document.getElementById('seats2').value--;
}
}
else if(button == '+2')
{
document.getElementById('seats2').value++;
}
else if(button == '-3')
{
numSeats = parseInt(document.getElementById('seats3').value);
if(numSeats>0)
{
document.getElementById('seats3').value--;
}
}
else if(button == '+3')
{
document.getElementById('seats3').value++;
}
else if(button == '-4')
{
numSeats = parseInt(document.getElementById('seats4').value);
if(numSeats>0)
{
document.getElementById('seats4').value--;
}
}
else if(button == '+4')
{
document.getElementById('seats4').value++;
}
else if(button == '-5')
{
numSeats = parseInt(document.getElementById('seats5').value);
if(numSeats>0)
{
document.getElementById('seats5').value--;
}
}
else if(button == '+5')
{
document.getElementById('seats5').value++;
}
else if(button == '-6')
{
numSeats = parseInt(document.getElementById('seats6').value);
if(numSeats>0)
{
document.getElementById('seats6').value--;
}
}
else if(button == '+6')
{
document.getElementById('seats6').value++;
}
else if(button == '-7')
{
numSeats = parseInt(document.getElementById('seats7').value);
if(numSeats>0)
{
document.getElementById('seats7').value--;
}
}
else if(button == '+7')
{
document.getElementById('seats7').value++;
}
}
$(document).ready(function(){
$("#movie").change(function()
{
if ($(this).val() == 'AC')
{
$("#monday").hide();
$("#tuesday").hide();
$("#wednesday").show();
$("#thursday").show();
$("#friday").show();
$("#saturday").show();
$("#sunday").show();
}
if ($(this).val() == 'CH')
{
$("#monday").show();
$("#tuesday").show();
$("#wednesday").show();
$("#thursday").show();
$("#friday").show();
$("#saturday").show();
$("#sunday").show();
}
if ($(this).val() == 'AF')
{
$("#monday").show();
$("#tuesday").show();
$("#wednesday").hide();
$("#thursday").hide();
$("#friday").hide();
$("#saturday").show();
$("#sunday").show();
}
if ($(this).val() == 'RC')
{
$("#monday").show();
$("#tuesday").show();
$("#wednesday").show();
$("#thursday").show();
$("#friday").show();
$("#saturday").show();
$("#sunday").show();
}
});
$("#movie").change(function()
{
if ($(this).val() == 'monday')
{
if ($("#movie").val == 'AC')
{
}
}
});
});<file_sep>/a3/Functions/printtickets_functions.php
<?php session_start();
function printCartStatus()
{
if ( empty($_SESSION['cart']) )
{
echo "<p class='msg'>Nothing in the cart</p>";
}
else
{
echo "<p class='msg'>Server has added form data</p>";
echo "<pre class='msg'>\$_SESSION['cart']: ";
print_r($_SESSION);
echo "</pre>";
}
}
function getMovieName($i)
{
if($_SESSION['cart'][$i]['movie'] == "AC")
{
return "MI: Rouge Nation";
}
if($_SESSION['cart'][$i]['movie'] == "CH")
{
return "Inside Out";
}
if($_SESSION['cart'][$i]['movie'] == "RC")
{
return "Trainwreck";
}
if($_SESSION['cart'][$i]['movie'] == "AF")
{
return "Girlhood";
}
}
function getSeatQty($i, $seatType)
{
return ($_SESSION['cart'][$i]['seat'][$seatType]);
}
function getCostSubtotal($i, $seatType)
{
$cost = 0.00;
if (!empty($_SESSION['cart'][$i]['seat'][$seatType]))
{
if ($seatType == 'Adult')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 18.00;
}
if ($seatType == 'Concession')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 12.00;
}
if ($seatType == 'FAdult')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 25.00;
}
if ($seatType == 'FChild')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 20.00;
}
if ($seatType == 'BeanbagT1')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 30.00;
}
if ($seatType == 'BeanbagT2')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 30.00;
}
if ($seatType == 'BeanbagT3')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 30.00;
}
}
return $cost;
}
function printTicketHead($i)
{
if (!empty($_SESSION['cart'][$i]))
{
echo
'<div>'.
$_SESSION['fname'].' '.$_SESSION['lname'].'<br>'.
$_SESSION['email'].'<br>'.
$_SESSION['phone'].'<br><br>Silverado<br>'.
getMovieName($i).'<br>'.
$_SESSION['cart'][$i]['day'].', '.
$_SESSION['cart'][$i]['time'].'<br><br>';
if (!empty($_SESSION['cart'][$i]['seat']['Adult']))
{
echo
$_SESSION['cart'][$i]['seat']['Adult'].' x Adult: '."$".getCostSubtotal($i, 'Adult').'<br>';
}
if (!empty($_SESSION['cart'][$i]['seat']['Concession']))
{
echo
$_SESSION['cart'][$i]['seat']['Concession'].' x Concession: '."$".getCostSubtotal($i, 'Concession').'<br>';
}
if (!empty($_SESSION['cart'][$i]['seat']['FAdult']))
{
echo
$_SESSION['cart'][$i]['seat']['FAdult'].' x First Class - Adult: '."$".getCostSubtotal($i, 'FAdult').'<br>';
}
if (!empty($_SESSION['cart'][$i]['seat']['FChild']))
{
echo
$_SESSION['cart'][$i]['seat']['FChild'].' x First Class - Child: '."$".getCostSubtotal($i, 'FChild').'<br>';
}
if (!empty($_SESSION['cart'][$i]['seat']['BeanbagT1']))
{
echo
$_SESSION['cart'][$i]['seat']['BeanbagT1'].' x Beanbag - Two Adults: '."$".getCostSubtotal($i, 'BeanbagT1').'<br>';
}
if (!empty($_SESSION['cart'][$i]['seat']['BeanbagT2']))
{
echo
$_SESSION['cart'][$i]['seat']['BeanbagT2'].' x Beanbag - One Adult + One Child: '."$".getCostSubtotal($i, 'BeanbagT2').'<br>';
}
if (!empty($_SESSION['cart'][$i]['seat']['BeanbagT3']))
{
echo
$_SESSION['cart'][$i]['seat']['BeanbagT3'].' x Beanbag - Three Children: '."$".getCostSubtotal($i, 'BeanbagT3').'<br>';
}
echo
'<br>Total: $'.$_SESSION['cart'][$i]['subtotal'].'</div>';
}
}
function printTicketParts($i, $seatType)
{
if (!empty($_SESSION['cart'][$i]['seat'][$seatType]))
{
for($j=0; $j < getSeatQty($i, $seatType); $j++)
{
echo
'<div>
Silverado<br>'.
getMovieName($i).'<br>'.
$_SESSION['cart'][$i]['day'].', '.
$_SESSION['cart'][$i]['time'].'<br><br>'.$seatType.
'</div>';
}
}
}
;?><file_sep>/a3/Functions/reservation_functions.php
<?php
session_start();
function printGetStatus()
{
if (empty($_GET))
{
echo "<p class='msg'>User coming to page for first time</p>";
} else {
echo "<p class='msg'>User has submitted form data</p>";
echo "<pre class='msg'>\$_GET: ";
print_r($_GET);
echo "</pre>";
}
}
function printCartStatus()
{
if ( empty($_SESSION['cart']) )
{
echo "<p class='msg'>Nothing in the cart</p>";
} else {
echo "<p class='msg'>Server has added form data</p>";
echo "<pre class='msg'>\$_SESSION['cart']: ";
print_r($_SESSION['cart']);
echo "</pre>";
}
}
$bookingMessage='';
if (!empty($_GET))
{
$booking=$_GET; // lazy approach: add everything, even empty data
$countSeats=0;
// Check to see if any seats have been booked
foreach ($booking['seat'] as $seatType => $quantity)
{
if (!empty($quantity))
$countSeats+=$quantity;
else
{
unset($booking['seat'][$seatType]); // remove unbooked seat types
}
}
// Add booking to cart if seats have been booked
if ($countSeats>0)
{
$_SESSION['cart'][]=$booking;
$bookingMessage .= "<p class='msg'>$countSeats seat(s) added to the cart</p>";
}
}
?><file_sep>/a3/Includes/reservation_js.php
<script>
$(document).ready(function(){
$("#movie").change(function(){
console.log($(this).val());
if ($(this).val() == 'AC')
{
$("#day option[value='Monday']").hide();
$("#day option[value='Tuesday']").hide();
$("#day option[value='Wednesday']").show();
$("#day option[value='Thursday']").show();
$("#day option[value='Friday']").show();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
$("#time option[value='1PM']").hide();
$("#time option[value='3PM']").hide();
$("#time option[value='6PM']").hide();
$("#time option[value='9PM']").show();
$("#time option[value='12PM']").hide();
}
else if ($(this).val() == 'AF')
{
$("#day option[value='Monday']").show();
$("#day option[value='Tuesday']").show();
$("#day option[value='Wednesday']").hide();
$("#day option[value='Thursday']").hide();
$("#day option[value='Friday']").hide();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
$("#time option[value='1PM']").hide();
$("#time option[value='3PM']").hide();
$("#time option[value='6PM']").show();
$("#time option[value='9PM']").hide();
$("#time option[value='12PM']").hide();
}
else if ($(this).val() == 'CH')
{
$("#day option[value='Monday']").show();
$("#day option[value='Tuesday']").show();
$("#day option[value='Wednesday']").show();
$("#day option[value='Thursday']").show();
$("#day option[value='Friday']").show();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
$("#time option[value='1PM']").show();
$("#time option[value='3PM']").hide();
$("#time option[value='6PM']").show();
$("#time option[value='9PM']").hide();
$("#time option[value='12PM']").show();
}
else if ($(this).val() == 'RC')
{
$("#day option[value='Monday']").show();
$("#day option[value='Tuesday']").show();
$("#day option[value='Wednesday']").show();
$("#day option[value='Thursday']").show();
$("#day option[value='Friday']").show();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
$("#time option[value='1PM']").show();
$("#time option[value='3PM']").hide();
$("#time option[value='6PM']").show();
$("#time option[value='9PM']").show();
$("#time option[value='12PM']").hide();
}
})
})
</script><file_sep>/a3/Functions/shoppingcart_functions.php
<?php session_start();
$total = 0;
function printCartStatus()
{
if ( empty($_SESSION['cart']) )
{
echo "<p class='msg'>Nothing in the cart</p>";
}
else
{
echo "<p class='msg'>Server has added form data</p>";
echo "<pre class='msg'>\$_SESSION['cart']: ";
print_r($_SESSION['cart']);
echo "</pre>";
}
}
function getMovieName($i)
{
if($_SESSION['cart'][$i]['movie'] == "AC")
{
return "MI: Rouge Nation";
}
if($_SESSION['cart'][$i]['movie'] == "CH")
{
return "Inside Out";
}
if($_SESSION['cart'][$i]['movie'] == "RC")
{
return "Trainwreck";
}
if($_SESSION['cart'][$i]['movie'] == "AF")
{
return "Girlhood";
}
}
function getSeatType($i, $seatType)
{
print_r($_SESSION['cart'][$i]['seat'][$seatType]);
}
function getSeatCost($i, $seatType)
{
$cost = 0.00;
if ($seatType == 'Adult')
{
$cost = 18.00;
}
if ($seatType == 'Concession')
{
$cost = 12.00;
}
if ($seatType == 'FAdult')
{
$cost = 25.00;
}
if ($seatType == 'FChild')
{
$cost = 20.00;
}
if ($seatType == 'BeanbagT1')
{
$cost = 30.00;
}
if ($seatType == 'BeanbagT2')
{
$cost = 30.00;
}
if ($seatType == 'BeanbagT3')
{
$cost = 30.00;
}
return $cost;
}
function getCostSubtotal($i, $seatType)
{
$cost = 0.00;
if (!empty($_SESSION['cart'][$i]['seat'][$seatType]))
{
if ($seatType == 'Adult')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 18.00;
}
if ($seatType == 'Concession')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 12.00;
}
if ($seatType == 'FAdult')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 25.00;
}
if ($seatType == 'FChild')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 20.00;
}
if ($seatType == 'BeanbagT1')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 30.00;
}
if ($seatType == 'BeanbagT2')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 30.00;
}
if ($seatType == 'BeanbagT3')
{
$cost = $_SESSION['cart'][$i]['seat'][$seatType] * 30.00;
}
}
return $cost;
}
function getCostTotal()
{
$total = 0.00;
for($i=0; $i<count($_SESSION['cart']); $i++)
{
$total += getCostSubtotal($i, 'Adult');
$total += getCostSubtotal($i, 'Concession');
$total += getCostSubtotal($i, 'FAdult');
$total += getCostSubtotal($i, 'FChild');
$total += getCostSubtotal($i, 'BeanbagT1');
$total += getCostSubtotal($i, 'BeanbagT2');
$total += getCostSubtotal($i, 'BeanbagT3');
}
$_SESSION['total'] = $total;
return $total;
}
function getCostGrandTotal()
{
$grandtotal = 0.00;
if(isset($_POST['voucher']))
{
$voucher = $_POST['voucher'];
if(checkVoucher($voucher) == true)
{
$grandtotal = getCostTotal() * 0.8;
}
else
{
$grandtotal = getCostTotal();
}
}
else
{
$grandtotal = getCostTotal();
}
$_SESSION['grand-total'] = $grandtotal;
return $grandtotal;
}
function getSeatQty($i, $seatType)
{
return $_SESSION['cart'][$i]['seat'][$seatType];
}
function addSeatQty($i, $seatType)
{
$_SESSION['cart'][$i]['seat'][$seatType] += 1;
}
function subSeatQty($i, $seatType)
{
if($_SESSION['cart'][$i]['seat'][$seatType] != 0)
{
$_SESSION['cart'][$i]['seat'][$seatType] -= 1;
}
if($_SESSION['cart'][$i]['seat'][$seatType] == 0)
{
unset($_SESSION['cart'][$i]['seat'][$seatType]);
}
if(empty($_SESSION['cart'][$i]['seat']))
{
unset($_SESSION['cart'][$i]);
}
}
function createAddButton($i, $seatType)
{
echo
'<li><form action="" method="post">
<input type="submit" class="addmin" name="add" value="+">
</form></li>';
}
function createSubButton($i, $seatType)
{
echo
'<li><form action="" method="post">
<input type="submit" class="addmin" name="sub" value="-">
</form></li>';
}
function printTicketDetails($i)
{
$time = $_SESSION['cart'][$i]['time'];
$movie = $_SESSION['cart'][$i]['movie'];
$day = $_SESSION['cart'][$i]['day'];
echo "<p>";
print_r(getMovieName($i)); print_r(", ");
print_r($day); print_r(", ");
print_r($time);
echo "</p>";
}
function emptyCart()
{
$_SESSION['cart'] = Array();;
}
function deleteFromCart($i)
{
array_splice($_SESSION['cart'], $i, 1);
}
function printTicketTable($i,$total)
{
$subtotal=0.00;
echo "<table>
<tr>
<td>Ticket Type</td>
<td>Cost</td>
<td>Qty</td>
<td>Subtotal</td>
</tr>";
if(!empty($_SESSION['cart'][$i]['seat']['Adult']))
{
$seatType='Adult';
echo "<tr>
<td>";
print_r($seatType);
echo "</td>
<td>";
print_r("$".getSeatCost($i, $seatType));
echo "</td>
<td>";
createSubButton($i, $seatType);
print_r(getSeatQty($i, $seatType));
createAddButton($i, $seatType);
echo "</td>
<td>";
print_r("$".getCostSubtotal($i, $seatType));
$subtotal = $subtotal + getCostSubtotal($i, $seatType);
echo "</td>
</tr>";
}
if(!empty($_SESSION['cart'][$i]['seat']['Concession']))
{
$seatType='Concession';
echo "<tr>
<td>";
print_r($seatType);
echo "</td>
<td>";
print_r("$".getSeatCost($i, $seatType));
echo "</td>
<td>";
print_r(getSeatQty($i, $seatType));
echo "</td>
<td>";
print_r("$".getCostSubtotal($i, $seatType));
$subtotal = $subtotal + getCostSubtotal($i, $seatType);
echo "</td>
</tr>";
}
if(!empty($_SESSION['cart'][$i]['seat']['FAdult']))
{
$seatType='FAdult';
echo "<tr>
<td>";
print_r($seatType);
echo "</td>
<td>";
print_r("$".getSeatCost($i, $seatType));
echo "</td>
<td>";
print_r(getSeatQty($i, $seatType));
echo "</td>
<td>";
print_r("$".getCostSubtotal($i, $seatType));
$subtotal = $subtotal + getCostSubtotal($i, $seatType);
echo "</td>
</tr>";
}
if(!empty($_SESSION['cart'][$i]['seat']['FChild']))
{
$seatType='FChild';
echo "<tr>
<td>";
print_r($seatType);
echo "</td>
<td>";
print_r("$".getSeatCost($i, $seatType));
echo "</td>
<td>";
print_r(getSeatQty($i, $seatType));
echo "</td>
<td>";
print_r("$".getCostSubtotal($i, $seatType));
$subtotal = $subtotal + getCostSubtotal($i, $seatType);
echo "</td>
</tr>";
}
if(!empty($_SESSION['cart'][$i]['seat']['BeanbagT1']))
{
$seatType='BeanbagT1';
echo "<tr>
<td>";
print_r($seatType);
echo "</td>
<td>";
print_r("$".getSeatCost($i, $seatType));
echo "</td>
<td>";
print_r(getSeatQty($i, $seatType));
echo "</td>
<td>";
print_r("$".getCostSubtotal($i, $seatType));
$subtotal = $subtotal + getCostSubtotal($i, $seatType);
echo "</td>
</tr>";
}
if(!empty($_SESSION['cart'][$i]['seat']['BeanbagT2']))
{
$seatType='BeanbagT2';
echo "<tr>
<td>";
print_r($seatType);
echo "</td>
<td>";
print_r("$".getSeatCost($i, $seatType));
echo "</td>
<td>";
print_r(getSeatQty($i, $seatType));
echo "</td>
<td>";
print_r("$".getCostSubtotal($i, $seatType));
$subtotal = $subtotal + getCostSubtotal($i, $seatType);
echo "</td>
</tr>";
}
if(!empty($_SESSION['cart'][$i]['seat']['BeanbagT3']))
{
$seatType='BeanbagT3';
echo "<tr>
<td>";
print_r($seatType);
echo "</td>
<td>";
print_r("$".getSeatCost($i, $seatType));
echo "</td>
<td>";
print_r(getSeatQty($i, $seatType));
echo "</td>
<td>";
print_r("$".getCostSubtotal($i, $seatType));
$subtotal = $subtotal + getCostSubtotal($i, $seatType);
echo "</td>
</tr>";
}
echo "<tr>
<td></td>
<td></td>
<td>Sub Total:</td>
<td>";
print_r("$".$subtotal);
$_SESSION['cart'][$i]['subtotal'] = $subtotal;
echo "</td>
</tr>";
echo "</table>";
}
function checkVoucher($voucher)
{
$v1 = (($voucher[0] * $voucher[1] + $voucher[2])
* $voucher[3] + $voucher[4]) % 26 ;
$v2 = (($voucher[6] * $voucher[7] + $voucher[8])
* $voucher[9] + $voucher[10]) % 26;
if($v1 == (ord($voucher[12]) - 65) && $v2 == ord($voucher[13]) - 65)
{
return true;
}
return false;
}
?><file_sep>/a3/Includes/moviesselection_js.php
<script>
$(document).ready(function () {
$("#movie-search").click(function () {
$.post("https://titan.csit.rmit.edu.au/~e54061/wp/moviesHTML.php", {
movie: $("#movie").val(),
day: $("#day").val(),
},
function (data) {
$('#data').html(data);
$( "#MS_MOVIE_RC" ).append( "<details> <summary>View More</summary> <p>Screenings: <br> Monday: 9PM <br> Tuesday: 9PM <br> Wednesday: 1PM <br> Thursday: 1PM <br> Friday: 1PM <br> Saturday: 6PM <br> Sunday: 6PM </p> <video src='https://titan.csit.rmit.edu.au/~e54061/wp/movie-service/RC.mp4' controls> </details>" + "<a href='http://titan.csit.rmit.edu.au/~s3330458/wp/a3/reservation_page.php'>Reservation</a>" );
$( "#MS_MOVIE_CH" ).append( "<details> <summary>View More</summary> <p>Screenings: <br> Monday: 1PM <br> Tuesday: 1PM <br> Wednesday: 6PM <br> Thursday: 6PM <br> Friday: 6PM <br> Saturday: 12PM <br> Sunday: 12PM </p> <video src='https://titan.csit.rmit.edu.au/~e54061/wp/movie-service/CH.mp4' controls> </details>" + "<a href='http://titan.csit.rmit.edu.au/~s3330458/wp/a3/reservation_page.php'>Reservation</a>" );
$( "#MS_MOVIE_AC" ).append( "<details> <summary>View More</summary> <p>Screenings: <br> Monday: Not Showing <br> Tuesday: Not Showing <br> Wednesday: 9PM <br> Thursday: 9PM <br> Friday: 9PM <br> Saturday: 9PM <br> Sunday: 9PM</p> <video src='https://titan.csit.rmit.edu.au/~e54061/wp/movie-service/AC.mp4' controls> </details>" + "<a href='http://titan.csit.rmit.edu.au/~s3330458/wp/a3/reservation_page.php'>Reservation</a>" );
$( "#MS_MOVIE_AF" ).append( "<details> <summary>View More</summary> <p>Screenings: <br> Monday: 6PM <br> Tuesday: 6PM <br> Wednesday: Not Showing <br> Thursday: Not Showing <br> Friday: Not Showing <br> Saturday: 6PM <br> Sunday: 6PM </p> <video src='https://titan.csit.rmit.edu.au/~e54061/wp/movie-service/AF.mp4' controls> </details>" + "<a href='http://titan.csit.rmit.edu.au/~s3330458/wp/a3/reservation_page.php'>Reservation</a>" );
});
});
$("#movie").change(function(){
console.log($(this).val());
if ($(this).val() == 'AC')
{
$("#day option[value='Monday']").hide();
$("#day option[value='Tuesday']").hide();
$("#day option[value='Wednesday']").show();
$("#day option[value='Thursday']").show();
$("#day option[value='Friday']").show();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
}
else if ($(this).val() == 'AF')
{
$("#day option[value='Monday']").show();
$("#day option[value='Tuesday']").show();
$("#day option[value='Wednesday']").hide();
$("#day option[value='Thursday']").hide();
$("#day option[value='Friday']").hide();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
}
else if ($(this).val() == 'CH')
{
$("#day option[value='Monday']").show();
$("#day option[value='Tuesday']").show();
$("#day option[value='Wednesday']").show();
$("#day option[value='Thursday']").show();
$("#day option[value='Friday']").show();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
}
else if ($(this).val() == 'RC')
{
$("#day option[value='Monday']").show();
$("#day option[value='Tuesday']").show();
$("#day option[value='Wednesday']").show();
$("#day option[value='Thursday']").show();
$("#day option[value='Friday']").show();
$("#day option[value='Saturday']").show();
$("#day option[value='Sunday']").show();
}
})
});
</script><file_sep>/a3/Functions/checkout_functions.php
<?php session_start();
function printCartStatus()
{
if ( empty($_SESSION['cart']) )
{
echo "<p class='msg'>Nothing in the cart</p>";
}
else
{
echo "<p class='msg'>Server has added form data</p>";
echo "<pre class='msg'>\$_SESSION['cart']: ";
print_r($_SESSION);
echo "</pre>";
}
}
function saveData()
{
if (!empty($_POST))
{
$firstname = "First Name: ".$_POST['fname'];
$lastname = "Last Name: ".$_POST['lname'];
$emails = "Email: ".$_POST['email'];
$phoneno = "Phone No.:".$_POST['phone'];
$_SESSION['fname'] = $_POST['fname'];
$_SESSION['lname'] = $_POST['lname'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['phone'] = $_POST['phone'];
echo
'<br><span style="color: darkgreen; font-weight: bold;">' .
'Tickets have been ordered.' .
'</span>';
echo
'<br><br><form action="http://titan.csit.rmit.edu.au/~s3330458/wp/a3/printtickets_page.php" target="_blank"><input type="submit" value="Print Tickets" />';
$file = fopen("data.txt", "w");
fwrite($file, $firstname);
fwrite($file, "\n");
fwrite($file, $lastname);
fwrite($file, "\n");
fwrite($file, $emails);
fwrite($file, "\n");
fwrite($file, $phoneno);
fwrite($file, "\n\n");
$i = 0;
while(isset($_SESSION['cart'][$i]))
{
$cartNo = "Screening: ".$i;
$pmovie = "Movie: ".$_SESSION['cart'][$i]['movie'];
$pday = "Day: ".$_SESSION['cart'][$i]['day'];
$ptime = "Time: ".$_SESSION['cart'][$i]['time'];
$screenCost = "Screening Cost: ".$_SESSION['cart'][$i]['subtotal'];
fwrite($file, $cartNo);
fwrite($file, "\n");
fwrite($file, $pmovie);
fwrite($file, "\n");
fwrite($file, $pday);
fwrite($file, "\n");
fwrite($file, $ptime);
fwrite($file, "\n");
fwrite($file, $screenCost);
fwrite($file, "\n");
if (!empty($_SESSION['cart'][$i]['seat']['Adult']))
{
$pseat = "Adult No.: ".$_SESSION['cart'][$i]['seat']['Adult'];
fwrite($file, $pseat);
fwrite($file, "\n");
}
if (!empty($_SESSION['cart'][$i]['seat']['Concession']))
{
$pseat = "Concession No.: ".$_SESSION['cart'][$i]['seat']['Concession'];
fwrite($file, $pseat);
fwrite($file, "\n");
}
if (!empty($_SESSION['cart'][$i]['seat']['FAdult']))
{
$pseat = "FAdult No.: ".$_SESSION['cart'][$i]['seat']['FAdult'];
fwrite($file, $pseat);
fwrite($file, "\n");
}
if (!empty($_SESSION['cart'][$i]['seat']['FChild']))
{
$pseat = "FChild No.: ".$_SESSION['cart'][$i]['seat']['FChild'];
fwrite($file, $pseat);
fwrite($file, "\n");
}
if (!empty($_SESSION['cart'][$i]['seat']['BeanbagT1']))
{
$pseat = "BeanbagT1 No.: ".$_SESSION['cart'][$i]['seat']['BeanbagT1'];
fwrite($file, $pseat);
fwrite($file, "\n");
}
if (!empty($_SESSION['cart'][$i]['seat']['BeanbagT2']))
{
$pseat = "BeanbagT2 No.: ".$_SESSION['cart'][$i]['seat']['BeanbagT2'];
fwrite($file, $pseat);
fwrite($file, "\n");
}
if (!empty($_SESSION['cart'][$i]['seat']['BeanbagT3']))
{
$pseat = "BeanbagT3 No.: ".$_SESSION['cart'][$i]['seat']['BeanbagT3'];
fwrite($file, $pseat);
fwrite($file, "\n");
}
fwrite($file, "\n");
$i++;
}
$pgrandtotal = "Grand Total: ".$_SESSION['grand-total'];
fwrite($file, $pgrandtotal);
fwrite($file, "\n");
if(isset($_SESSION['voucher']))
{
$pvoucher = "Voucher: ".$_SESSION['voucher'];
fwrite($file, $pvoucher);
fwrite($file, "\n");
}
}
}
;?><file_sep>/a3/shoppingcart_page.php
<?php include_once('Functions/shoppingcart_functions.php');?>
<!DOCTYPE html>
<html>
<head>
<?php include_once('Includes/head_data.php');?>
<title>Shopping Cart Page</title>
</head>
<body>
<?php include_once('Includes/header.php');include_once('Includes/navbar.php');?>
<main>
<div class="block1">
<h1>Shopping Cart</h1>
<?php
if (isset($_SESSION['cart']))
{
for($i=0; $i<count($_SESSION['cart']); $i++)
{
echo '<div class="block2">';
printTicketDetails($i);
printTicketTable($i,$total);
echo '<br><form action="" method="post">
<input type="submit" name="'.$i.'" value="Delete From Cart">
</form>';
echo '</div>';
}
}
?>
<?php for($i=0; $i<count($_SESSION['cart']); $i++)
{
if (isset($_POST[$i]))
{
deleteFromCart($i);
Header("location:shoppingcart_page.php");
}
}
; ?>
<div class="block2">
<p>Total: <?php print_r("$".getCostTotal()); ?></p>
<p>Meal and Movie Deal Voucher:</p>
<p>Grand Total: <?php print_r("$".getCostGrandTotal()); ?></p>
<p><form action="" method="post">
Voucher Code:
<input type="text" name="voucher" pattern="^\d{5}-\d{5}-[A-Z]{2}$">
<input type='submit'/>
</form></p>
<?php
if(isset($_POST['voucher']))
{
$voucher = $_POST['voucher'];
if(checkVoucher($voucher) == true)
{
echo
'<span style="color: darkgreen; font-weight: bold;">' .
'Voucher is valid' .
'</span>';
$_SESSION['voucher'] = $voucher;
}
else
{
echo
'<span style="color: darkred; font-weight: bold;">' .
'Voucher is invalid' .
'</span>';
}
}
?>
<li><form action="" method="post">
<input type="submit" name="empty_cart" value="Empty Cart">
</form></li>
<?php if (isset($_POST["empty_cart"]))
{
$_SESSION = array();
Header("location:reservation_page.php");
}
; ?>
<?php if (isset($_POST["add"]))
{
addSeatQty(0, 'Adult');
}
if (isset($_POST["sub"]))
{
subSeatQty(0, 'Adult');
}
; ?>
<li><form action="http://titan.csit.rmit.edu.au/~s3330458/wp/a3/checkout_page.php">
<input type='submit' value='Checkout'/>
</form></li>
</div>
</div>
</main>
<?php include_once('Includes/footer.php');?>
</body>
</html><file_sep>/a3/index.php
<?php session_start()?>
<!DOCTYPE html>
<html>
<head>
<?php include_once('Includes/head_data.php');?>
<title>Homepage</title>
</head>
<body>
<?php include_once('Includes/header.php');include_once('Includes/navbar.php');?>
<main>
<div class="block1">
<h1>
Silverado Grand Re-opening!
</h1>
<div class="block2">
<p>
At long last, your local cinema the Silverado opens its doors and welcomes you back to experience the magic of movies in style.
<br><br>
We present to you our new range of seating that will offer you more options style and comfort in an effort to provide our loyal and new customers alike with a premium movie expreience.
</p>
<!-- Original image below sourced for educational purposes: http://images.entertainment.ie/images_content/rectangle/620x372/beanbagcinema.jpg -->
<img src="http://titan.csit.rmit.edu.au/~s3330458/wp/a2/Images/seat1.png" alt="Bean Bag Seat" width="30%">
<!-- Original image below sourced for educational purposes: http://www.figueras.com/images/product/products_45_13764056594.jpg -->
<img src="http://titan.csit.rmit.edu.au/~s3330458/wp/a2/Images/seat2.png" alt="Premium Seat" width="30%">
<!-- Original image below sourced for educational purposes: http://fercoseating.com/v2/wp-content/uploads/2012/04/milano-crop.jpg -->
<img src="http://titan.csit.rmit.edu.au/~s3330458/wp/a2/Images/seat3.png" alt="Standard Seat" width="30%">
</div class="news2">
</div>
<div class="block1">
<h1>
Renovations In Progress
</h1>
<div class="block2">
<!-- Original image below sourced for educational purposes: http://chiphouston.com/wp-content/uploads/2015/03/work-in-progress.png -->
<img src="http://titan.csit.rmit.edu.au/~s3330458/wp/a2/Images/wip.png" alt="Work In Progress" width="50%">
<p>
Renovations are underway and the Silverado plans to bring you he lates and greatest in cinema and film technology. We plan to introduce new seat designs for a more comfortable viewing experience, 3D projection technology that will allow us to offer more types of movies and give the you more choices than ever and integrate a Dolby Sound System that will take your audio visual journey to the next level.
</p>
</div>
</div>
<div class="block1" id="newslast">
<h1>
Website Redesign
</h1>
<div class="block2">
<p>
Silverado Cinema presents to you its sleek new website design.
</p>
</div>
</div>
</main>
<?php include_once('Includes/footer.php');?>
</body>
</html> | 3b7e05990c1c0a65a0d766222afefb4d5de60cf8 | [
"JavaScript",
"PHP"
] | 13 | PHP | lukeyoung92/Silverado | 2a88ba854d9357451cf51108a56905c02ff6d4f7 | 257c7123d7271b0470022b63e524add521436afd |
refs/heads/master | <file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
namespace modauthopenid {
using namespace opkele;
using namespace std;
// This class keeps track of cookie based sessions
class SessionManager {
public:
// storage_location is db location
SessionManager(const string& storage_location);
~SessionManager() { close(); };
// get session with id session_id and set values in session
// if session doesn't exist, don't do anything
void get_session(const string& session_id, session_t& session);
// store given session information in a new session entry
// if lifespan is 0, let it expire in a day. otherwise, expire in "lifespan" seconds
// See issue 16 - http://trac.butterfat.net/public/mod_auth_openid/ticket/16
void store_session(const string& session_id, const string& hostname, const string& path, const string& identity, const string& username, int lifespan);
// print session table to stdout
void print_table();
// close database
void close();
private:
sqlite3 *db;
// delete all expired sessions
void ween_expired();
// db status
bool is_closed;
// test sqlite query result - print any errors to stderr
bool test_result(int result, const string& context);
};
}
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
#include <iostream>
#include <sys/stat.h>
#include <time.h>
#include "mod_auth_openid.h"
using namespace std;
using namespace modauthopenid;
void print_databases(string db_location) {
cout << "Current time: " << time(0) << endl;
SessionManager s(db_location);
s.print_table();
s.close();
MoidConsumer c(db_location, "blah", "balh");
c.print_tables();
c.close();
};
int main(int argc, char **argv) {
if(argc != 2) {
cout << "usage: " << argv[0] << " <sqlite database location>\n";
return -1;
}
if(access(argv[1], 0) == -1) {
cout << "File \"" << argv[1] << "\" does not exist or cannot be read.\n";
return -1;
}
print_databases(string(argv[1]));
return 0;
}
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
#include "mod_auth_openid.h"
namespace modauthopenid {
using namespace std;
void debug(string s) {
#ifdef DEBUG
string time_s = "";
time_t rawtime = time(NULL);
tm *tm_t = localtime(&rawtime);
char rv[40];
if(strftime(rv, sizeof(rv)-1, "%a %b %d %H:%M:%S %Y", tm_t))
time_s = "[" + string(rv) + "] ";
s = time_s + "[" + string(PACKAGE_NAME) + "] " + s + "\n";
// escape %'s
string cleaned_s = "";
vector<string> parts = explode(s, "%");
for(unsigned int i=0; i<parts.size()-1; i++)
cleaned_s += parts[i] + "%%";
cleaned_s += parts[parts.size()-1];
// stderr is redirected by apache to apache's error log
fputs(cleaned_s.c_str(), stderr);
fflush(stderr);
#endif
};
// get a descriptive string for an error; a short string is used as a GET param
// value in the style of OpenID get params - short, no space, ...
string error_to_string(error_result_t e, bool use_short_string) {
string short_string, long_string;
switch(e) {
case no_idp_found:
short_string = "no_idp_found";
long_string = "There was either no identity provider found for the identity given"
" or there was trouble connecting to it.";
break;
case invalid_id:
short_string = "invalid_id";
long_string = "The identity given is not a valid identity.";
break;
case idp_not_trusted:
short_string = "idp_not_trusted";
long_string = "The identity provider for the identity given is not trusted.";
break;
case invalid_nonce:
short_string = "invalid_nonce";
long_string = "Invalid nonce; error while authenticating.";
break;
case canceled:
short_string = "canceled";
long_string = "Identification process has been canceled.";
break;
case unauthorized:
short_string = "unauthorized";
long_string = "User is not authorized to access this location.";
break;
case ax_bad_response:
short_string = "ax_bad_response";
long_string = "Error while reading user profile data.";
break;
default: // unspecified
short_string = "unspecified";
long_string = "There has been an error while attempting to authenticate.";
break;
}
return (use_short_string) ? short_string : long_string;
};
string str_replace(string needle, string replacement, string haystack) {
vector<string> v = explode(haystack, needle);
string r = "";
for(vector<string>::size_type i=0; i < v.size()-1; i++)
r += v[i] + replacement;
r += v[v.size()-1];
return r;
};
vector<string> explode(string s, string e) {
vector<string> ret;
int iPos = s.find(e, 0);
int iPit = e.length();
while(iPos>-1) {
if(iPos!=0)
ret.push_back(s.substr(0,iPos));
s.erase(0,iPos+iPit);
iPos = s.find(e, 0);
}
if(s!="")
ret.push_back(s);
return ret;
};
pcre * make_regex(string pattern) {
const char * error;
int erroffset;
return pcre_compile(pattern.c_str(), 0, &error, &erroffset, NULL);
}
bool regex_match(string subject, pcre * re) {
return (pcre_exec(re, NULL, subject.c_str(), subject.size(), 0, 0, NULL, 0) >= 0);
};
void strip(string& s) {
while(!s.empty() && s.substr(0,1) == " ") s.erase(0,1);
while(!s.empty() && s.substr(s.size()-1, 1) == " ") s.erase(s.size()-1,1);
};
// make a random alpha-numeric string size characters long
void make_rstring(int size, string& s) {
s = "";
const char *cs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for(int index=0; index<size; index++)
s += cs[true_random()%62];
}
void print_sqlite_table(sqlite3 *db, string tablename) {
fprintf(stdout, "Printing table: %s. ", tablename.c_str());
string sql = "SELECT * FROM " + tablename;
int rc, nr, nc, size;
char **table;
rc = sqlite3_get_table(db, sql.c_str(), &table, &nr, &nc, 0);
fprintf(stdout, "There are %d rows.\n", nr);
size = (nr * nc) + nc;
for(int i=0; i<size; i++) {
fprintf(stdout, "%s\t", table[i]);
if(((i+1) % nc) == 0)
fprintf(stdout, "\n");
}
fprintf(stdout, "\n");
sqlite3_free_table(table);
};
bool test_sqlite_return(sqlite3 *db, int result, const string& context) {
if(result != SQLITE_OK){
string msg = "SQLite Error - " + context + ": %s\n";
fprintf(stderr, msg.c_str(), sqlite3_errmsg(db));
return false;
}
return true;
};
string exec_error_to_string(exec_result_t e, string exec_location, string id) {
string error;
switch(e) {
case fork_failed:
error = "Could not fork to exec program: " + exec_location + "when attempting to auth " + id;
break;
case child_no_return:
error = "Problem waiting for child " + exec_location + " to return when authenticating " + id;
break;
case id_refused:
error = id + " not authenticated by " + exec_location;
break;
default: // unspecified
error = "Error while attempting to authenticate " + id + " using the program " + exec_location;
break;
}
return error;
}
exec_result_t exec_auth(string exec_location, string username) {
if(exec_location.size() > 255)
exec_location.resize(255);
if(username.size() > 255)
username.resize(255);
char *const argv[] = { (char *) exec_location.c_str(), (char *) username.c_str(), NULL };
exec_result_t result = id_refused;
int rvalue = 0;
pid_t pid = fork();
switch(pid) {
case -1:
// Fork failed
result = fork_failed;
break;
case 0:
// congrats, you're a kid
execv(exec_location.c_str(), argv);
// if we make it here, exec failed, exit from kid with rvalue 1
exit(1);
default:
// you're an adult parent, act responsibly
if(waitpid(pid, &rvalue, 0) == -1)
result = child_no_return;
else
result = (rvalue == 0) ? id_accepted : id_refused;
break;
}
return result;
};
/* true_random -- generate a crypto-quality random number. Taken from apr-util's getuuid.c file */
int true_random() {
#if APR_HAS_RANDOM
unsigned char buf[2];
if (apr_generate_random_bytes(buf, 2) == APR_SUCCESS)
return (buf[0] << 8) | buf[1];
#endif
apr_uint64_t time_now = apr_time_now();
srand((unsigned int)(((time_now >> 32) ^ time_now) & 0xffffffff));
return rand() & 0x0FFFF;
};
} // end namespace
<file_sep># Security Advisory 1201
Summary : Session stealing
Date : May 2012
Affected versions : all versions prior to mod_auth_openid-0.7
ID : mod_auth_openid-1201
CVE reference : CVE-2012-2760
# Details
Session ids are stored insecurely in /tmp/mod_auth_openid.db (default filename). The db is world readable and the session ids are stored unencrypted.
# Impact
If a user has access to the filesystem on the mod_auth_openid server, they can steal all of the current openid authenticated sessions
# Workarounds
A quick improvement of the situation is to chmod 0400 the DB file. Default location is /tmp/mod_auth_openid.db unless another location has been configured in AuthOpenIDDBLocation.
# Solution
Upgrade to mod_auth_openid-0.7 or later: http://findingscience.com/mod_auth_openid/releases
# Credits
This vulnerability was reported by <NAME>, ptr at groupon dot com. Fixed by <NAME> bmuller at gmail dot com
# References
mod_auth_openid project: http://findingscience.com/mod_auth_openid/
# History
15 May 2012
Discovered the vulnerability. Created private patch.
16 May 2012
Notified maintainer.
Obtained CVE-id
22 May 2012
Fixed by <NAME> (bmuller at gmail dot com) in mod_auth_openid-0.7 - https://github.com/bmuller/mod_auth_openid/blob/master/ChangeLog
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
namespace modauthopenid {
using namespace opkele;
using namespace std;
// Send the string s as to the client (type text/html). On success,
// send either the value of the parameter success_rvalue or OK by
// default
int http_sendstring(request_rec *r, string s, int success_rvalue = OK);
//send Location header to given location
int http_redirect(request_rec *r, string location);
// show login page with given message string
int show_html_input(request_rec *r, string msg);
// get session id from cookie, if it exists, and put in session_id string - return if no cookie
// with given name
void get_session_id(request_rec *r, string cookie_name, string& session_id);
// get the base location of the url (everything up to the last '/')
void base_dir(string path, string& s);
// return a url without the query string
string get_queryless_url(string url);
// remove all openid.*, modauthopenid.* parameters (except sreg and ax params)
void remove_openid_vars(params_t& params);
// html escape a string (used for putting get params into a page as hidden inputs)
string html_escape(string s);
// create a params_t object from a query string
params_t parse_query_string(const string& str);
// url decode a string
string url_decode(const string& str);
// create the cookie string that will be sent out in a header
void make_cookie_value(string& cookie_value, const string& name, const string& session_id, const string& path, int cookie_lifespan, bool secure_cookie);
// Get the extension parameters from the parameter list and put them in
// extparams
void get_extension_params(params_t &extparams, params_t ¶ms);
// for each key/value in params_one, set params_two[key] = value
void merge_params(params_t& params_one, params_t& params_two);
// Get request parameters - whether POST or GET
void get_request_params(request_rec *r, params_t& params);
// Get the post query string from a HTTP POST
bool get_post_data(request_rec *r, string& query_string);
};
<file_sep># Basic Installation
First, you'll need a few prerequisites.
* the latest libopkele from http://kin.klever.net/libopkele (C++ implementation of important OpenID functions)
* libsqlite from http://www.sqlite.org (SQLite C libs)
Next, run:
./configure
or
./configure --help
to see additional options that can be specified.
Next, run:
make
su root
make install
Make sure that the file /tmp/mod_auth_openid.db is owned by the user running Apache.
You can do this by (assuming www-data is the user running apache):
su root
touch /tmp/mod_auth_openid.db
chown www-data /tmp/mod_auth_openid.db
Or you can specify an alternate location that the user running apache has write
privieges on (see the docs for the AuthOpenIDDBLocation directive on the homepage).
# Usage
In either a Directory, Location, or File directive in httpd.conf, place the following directive:
AuthType OpenID
Require valid-user
There are also additional, optional directives. See the homepage for a list and docs.
The user's identity URL will be available in the REMOTE_USER cgi environment variable after
authentication.
See [the project page](http://findingscience.com/mod_auth_openid) for more information.
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
namespace modauthopenid {
using namespace opkele;
using namespace std;
// Class to handle tasks of consumer - authentication session is based on a nonce id that is thrown in with
// the params list
class MoidConsumer : public prequeue_RP {
public:
// storage location is db location, _asnonceid is the association session nonce, and serverurl is
// the return to value (url initially requested by user)
MoidConsumer(const string& storage_location, const string& _asnonceid, const string& _serverurl);
virtual ~MoidConsumer() { close(); };
// store a new assocation
assoc_t store_assoc(const string& server,const string& handle,const string& type,const secret_t& secret,int expires_in);
// retrieve an association
assoc_t retrieve_assoc(const string& server,const string& handle);
// invalidate assocation - deletes from db
void invalidate_assoc(const string& server,const string& handle);
// find any association for the given server OP
assoc_t find_assoc(const string& server);
// This is called with the openid.response_nonce - if isn't already in db, is stored for same amount of time
// as the association, at which point a replay attack is impossible since assocation key is deleted
void check_nonce(const string& OP,const string& nonce);
// delete authentication session with the constructor param nonce if it exists
void begin_queueing();
// store the given endpoint - there actually is no queue - we just keep track of the first one
// given - all subsequent calls are ignored
void queue_endpoint(const openid_endpoint_t& ep);
// get the endpoint set in queue_endpoint
const openid_endpoint_t& get_endpoint() const;
// same as begin_queuing
void next_endpoint();
// set the normalized id for this authentication session
void set_normalized_id(const string& nid);
// get id set in set_normalized_id
const string get_normalized_id() const;
// get the url that was given as a constructor parameter
const string get_this_url() const;
// check to see if a session exists with the nonce session id given in the constructor
bool session_exists();
// print all tables to stdout
void print_tables();
// close db
void close();
// delete session with given session nonce id in constructor param list
void kill_session();
private:
sqlite3 *db;
// delete all expired sessions
void ween_expired();
// test result from sqlite query - print error to stderr if there is one
bool test_result(int result, const string& context);
// strings for the nonce based authentication session and the server's url (the originally
// requested url)
string asnonceid, serverurl;
// booleans for the database state and whether any endpoint has been set yet
bool is_closed, endpoint_set;
// The normalized id the user has attempted to use
mutable string normalized_id;
// the endpoint for the user's identity
mutable openid_endpoint_t endpoint;
};
}
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
#include "mod_auth_openid.h"
namespace modauthopenid {
using namespace std;
int http_sendstring(request_rec *r, string s, int success_rvalue) {
// no idea why the following line only sometimes worked.....
//apr_table_setn(r->headers_out, "Content-Type", "text/html");
ap_set_content_type(r, "text/html");
const char *c_s = s.c_str();
conn_rec *c = r->connection;
apr_bucket *b;
apr_bucket_brigade *bb = apr_brigade_create(r->pool, c->bucket_alloc);
b = apr_bucket_transient_create(c_s, strlen(c_s), c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, b);
b = apr_bucket_eos_create(c->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(bb, b);
if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
return HTTP_INTERNAL_SERVER_ERROR;
return success_rvalue;
};
int send_form_post(request_rec *r, string location) {
string::size_type last = location.find('?', 0);
string url = (last != string::npos) ? location.substr(0, last) : location;
params_t params;
if(url.size() < location.size())
params = parse_query_string(location.substr(url.size()+1));
string inputs = "";
map<string,string>::iterator iter;
for(iter = params.begin(); iter != params.end(); iter++) {
string key(iter->first);
inputs += "<input type=\"hidden\" name=\"" + key + "\" value=\"" + params[key] + "\" />";
}
string result =
"<html><head><title>redirection</title></head><body onload=\"document.getElementById('form').submit();\">"
"This page will automatically redirect you to your identity provider. "
"If you are not immediately redirected, click the submit button below."
"<form id=\"form\" action=\"" + url + "\" method=\"post\">" + inputs + "<input type=\"submit\" value=\"submit\">"
"</form></body></html>";
// return HTTP_UNAUTHORIZED so that no further modules can produce output
return http_sendstring(r, result, HTTP_UNAUTHORIZED);
};
int http_redirect(request_rec *r, string location) {
// Because IE is retarded, we have to do a form post if the URL is too big (over 2048 characters)
if(location.size() > 2000) {
debug("Redirecting via POST to: " + location);
return send_form_post(r, location);
} else {
debug("Redirecting via HTTP_MOVED_TEMPORARILY to: " + location);
apr_table_set(r->headers_out, "Location", location.c_str());
apr_table_setn(r->headers_out, "Cache-Control", "no-cache");
return HTTP_MOVED_TEMPORARILY;
}
};
int show_html_input(request_rec *r, string msg) {
opkele::params_t params;
if(r->args != NULL)
params = parse_query_string(string(r->args));
string identity = params.has_param("openid_identifier") ? params.get_param("openid_identifier") : "";
remove_openid_vars(params);
map<string,string>::iterator iter;
string args = "";
string key, value;
for(iter = params.begin(); iter != params.end(); iter++) {
key = html_escape(iter->first);
value = html_escape(iter->second);
args += "<input type=\"hidden\" name=\"" + key + "\" value = \"" + value + "\" />";
}
string result =
"<html><head><title>Protected Location</title><style type=\"text/css\">"
"#msg { border: 1px solid #ff0000; background: #ffaaaa; font-weight: bold; padding: 10px; }\n"
"a { text-decoration: none; }\n"
"a:hover { text-decoration: underline; }\n"
"#desc { border: 1px solid #000; background: #ccc; padding: 10px; }\n"
"#sig { text-align: center; font-style: italic; margin-top: 50px; color: #777; font-size: .7em; }\n"
"#sig a { color: #222; }\n"
".loginbox { background: url(http://www.openid.net/login-bg.gif) no-repeat; background-color: #fff; " // logo location is in 1.1 spec, should stay same
" background-position: 0 50%; color: #000; padding-left: 18px; }\n"
"form { margin: 15px; }\n"
"</style></head><body>"
"<h1>Protected Location</h1>"
"<p id=\"desc\">This site is protected and requires that you identify yourself with an "
"<a href=\"http://openid.net\">OpenID</a> url. To find out how it works, see "
"<a href=\"http://openid.net/what/\">http://openid.net/what/</a>. You can sign up for "
"an identity on one of the sites listed <a href=\"http://openid.net/get/\">here</a>.</p>"
+ (msg.empty()?"":"<div id=\"msg\">"+msg+"</div>") +
"<form action=\"\" method=\"get\">"
"<b>Identity URL:</b> <input type=\"text\" name=\"openid_identifier\" value=\""+identity+"\" size=\"30\" class=\"loginbox\" />"
"<input type=\"submit\" value=\"Log In\" />" + args +
"</form>"
"<div id=\"sig\">protected by <a href=\"" + PACKAGE_URL + "\">" + PACKAGE_STRING + "</a></div>"
"<body></html>";
// return HTTP_UNAUTHORIZED so that no further modules can produce output
return http_sendstring(r, result, HTTP_UNAUTHORIZED);
};
void get_session_id(request_rec *r, string cookie_name, string& session_id) {
const char * cookies_c = apr_table_get(r->headers_in, "Cookie");
if(cookies_c == NULL)
return;
string cookies(cookies_c);
vector<string> pairs = explode(cookies, ";");
for(string::size_type i = 0; i < pairs.size(); i++) {
vector<string> pair = explode(pairs[i], "=");
if(pair.size() == 2) {
string key = pair[0];
strip(key);
string value = pair[1];
strip(value);
debug("cookie sent by client: \""+key+"\"=\""+value+"\"");
if(key == cookie_name) {
session_id = pair[1];
return;
}
}
}
};
// get the base directory of the url
void base_dir(string path, string& s) {
// guaranteed that path will at least be "/" - but just to be safe...
if(path.size() == 0)
return;
string::size_type q = path.find('?', 0);
int i;
if(q != string::npos)
i = path.find_last_of('/', q);
else
i = path.find_last_of('/');
s = path.substr(0, i+1);
};
// assuming the url given will begin with http(s):// - worst case, return blank string
string get_queryless_url(string url) {
if(url.size() < 8)
return "";
if(url.find("http://",0) != string::npos || url.find("https://",0) != string::npos) {
string::size_type last = url.find('?', 8);
if(last != string::npos)
return url.substr(0, last);
return url;
}
return "";
};
void remove_openid_vars(params_t& params) {
map<string,string>::iterator iter, iter_next;
for(iter = params.begin(); iter != params.end(); ) {
iter_next = iter;
++iter_next;
string param_key(iter->first);
// if starts with openid. or modauthopenid. (for the nonce) or openid_identifier (the login) remove it
if((param_key.substr(0, 7) == "openid." || param_key.substr(0, 14) == "modauthopenid." || param_key == "openid_identifier")) {
params.erase(iter); // invalidates iter, but its successor iter_next is still valid
}
iter = iter_next;
}
};
void get_extension_params(params_t& extparams, params_t& params) {
map<string,string>::iterator iter;
extparams.reset_fields();
for(iter = params.begin(); iter != params.end(); iter++) {
string param_key(iter->first);
vector<string> parts = explode(param_key, ".");
// if there is more than one "." in the param name then we're
// dealing with an extension parameter
if(parts.size() > 2)
extparams[param_key] = params[param_key];
}
};
// for each key/value in params_one, set params_two[key] = value
void merge_params(params_t& params_one, params_t& params_two) {
map<string,string>::iterator iter;
for(iter = params_one.begin(); iter != params_one.end(); iter++) {
string param_key(iter->first);
params_two[param_key] = params_one[param_key];
}
};
// This isn't a true html_escape function, but rather escapes just enough to get by for
// quoted values - <blah name="stuff to be escaped">
string html_escape(string s) {
s = str_replace("&", "&", s);
s = str_replace("'", "'", s);
s = str_replace("\"", """, s);
s = str_replace("<", "<", s);
s = str_replace(">", ">", s);
return s;
};
string url_decode(const string& str) {
// if +'s aren't replaced with %20's then curl won't unescape to spaces properly
string url = str_replace("+", "%20", str);
CURL *curl = curl_easy_init();
if(!curl)
throw failed_conversion(OPKELE_CP_ "failed to curl_easy_init()");
char * t = curl_easy_unescape(curl, url.c_str(), url.length(), NULL);
if(!t)
throw failed_conversion(OPKELE_CP_ "failed to curl_unescape()");
string rv(t);
curl_free(t);
curl_easy_cleanup(curl);
return rv;
};
params_t parse_query_string(const string& str) {
params_t p;
if(str.size() == 0) return p;
vector<string> pairs = explode(str, "&");
for(unsigned int i=0; i < pairs.size(); i++) {
string::size_type loc = pairs[i].find( "=", 0 );
// if loc found and loc isn't last char in string
if( loc != string::npos && loc != str.size()-1) {
string key = url_decode(pairs[i].substr(0, loc));
string value = url_decode(pairs[i].substr(loc+1));
p[key] = value;
}
}
return p;
};
void make_cookie_value(string& cookie_value, const string& name, const string& session_id, const string& path, int cookie_lifespan, bool secure_cookie) {
cookie_value = name + "=" + session_id + "; path=" + path + "; HttpOnly";
if(cookie_lifespan != 0) {
time_t t;
t = time(NULL) + cookie_lifespan;
struct tm *tmp;
tmp = gmtime(&t);
char expires[200];
strftime(expires, sizeof(expires), "%a, %d-%b-%Y %H:%M:%S GMT", tmp);
cookie_value += "; expires=" + string(expires);
}
if (secure_cookie) {
cookie_value += "; Secure";
}
};
// Get the post query string from a HTTP POST
bool get_post_data(request_rec *r, string& qs) {
// check to make sure the right content type was used
const char *type = apr_table_get(r->headers_in, "Content-Type");
if (strcasecmp(type, DEFAULT_POST_ENCTYPE) != 0)
return false;
apr_bucket_brigade *bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
apr_status_t ret;
int seen_eos, child_stopped_reading;
seen_eos = child_stopped_reading = 0;
char *query_string = NULL;
do {
ret = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES, APR_BLOCK_READ, 8192);
if(ret != APR_SUCCESS)
return false;
apr_bucket *bucket;
for(bucket=APR_BRIGADE_FIRST(bb); bucket!=APR_BRIGADE_SENTINEL(bb); bucket=APR_BUCKET_NEXT(bucket)) {
apr_size_t len;
const char *data;
if(APR_BUCKET_IS_EOS(bucket)) {
seen_eos = 1;
break;
}
if(APR_BUCKET_IS_FLUSH(bucket))
continue;
if(child_stopped_reading)
continue;
ret = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
if(ret != APR_SUCCESS) {
child_stopped_reading = 1;
} else {
if (query_string == NULL)
query_string = apr_pstrndup(r->pool, data, len);
else
query_string = apr_pstrcat(r->pool, query_string, apr_pstrndup(r->pool, data, len), NULL);
}
}
apr_brigade_cleanup(bb);
} while (!seen_eos);
qs = (query_string == NULL) ? "" : string(query_string);
return true;
};
// Get request parameters - whether POST or GET
void get_request_params(request_rec *r, params_t& params) {
string query;
if(r->method_number == M_GET && r->args != NULL) {
debug("Request GET params: " + string(r->args));
params = parse_query_string(string(r->args));
} else if(r->method_number == M_POST && get_post_data(r, query)) {
debug("Request POST params: " + query);
params = parse_query_string(query);
if (r->args != NULL) {
params_t get_params;
get_params = parse_query_string(string(r->args));
merge_params(get_params, params);
}
}
};
}
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
namespace modauthopenid {
using namespace opkele;
using namespace std;
enum error_result_t { no_idp_found, invalid_id, idp_not_trusted, invalid_nonce, canceled, unspecified, unauthorized, ax_bad_response };
enum exec_result_t { id_accepted, fork_failed, child_no_return, id_refused };
typedef struct session {
string session_id;
string hostname; // name of server (this is in case there are virtual hosts on this server)
string path;
string identity;
string username; // optional - set by AuthOpenIDAXUsername
int expires_on; // exact moment it expires
} session_t;
// Wrapper for basic_openid_message - just so it works with openid namespace
class modauthopenid_message_t : public params_t {
public:
modauthopenid_message_t(params_t& _bom) { bom = _bom; };
bool has_field(const string& n) const { return bom.has_param("openid."+n); };
const string& get_field(const string& n) const { return bom.get_param("openid."+n); };
bool has_ns(const string& uri) const { return bom.has_ns(uri); };
string get_ns(const string& uri) const { return bom.get_ns(uri); };
fields_iterator fields_begin() const { return bom.fields_begin(); };
fields_iterator fields_end() const { return bom.fields_end(); };
void reset_fields() { bom.reset_fields(); };
void set_field(const string& n,const string& v) { bom.set_field(n, v); };
void reset_field(const string& n) { bom.reset_field(n); };
private:
params_t bom;
};
}
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
#include "mod_auth_openid.h"
#define APDEBUG(r, msg, ...) ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, msg, __VA_ARGS__);
#define APWARN(r, msg, ...) ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, msg, __VA_ARGS__);
#define APERR(r, msg, ...) ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, msg, __VA_ARGS__);
extern "C" module AP_MODULE_DECLARE_DATA authopenid_module;
typedef struct {
const char *db_location;
char *trust_root;
const char *cookie_name;
char *login_page;
bool use_cookie;
apr_array_header_t *trusted;
apr_array_header_t *distrusted;
int cookie_lifespan;
bool secure_cookie;
char *server_name;
char *auth_program;
char *cookie_path;
bool use_auth_program;
bool use_ax;
apr_array_header_t *ax_attrs;
apr_table_t *ax_attr_uris;
apr_table_t *ax_attr_patterns;
bool use_ax_username;
char *ax_username_attr;
bool use_single_idp;
char *single_idp_url;
} modauthopenid_config;
typedef const char *(*CMD_HAND_TYPE) ();
static void *create_modauthopenid_config(apr_pool_t *p, char *s) {
modauthopenid_config *newcfg;
newcfg = (modauthopenid_config *) apr_pcalloc(p, sizeof(modauthopenid_config));
newcfg->db_location = "/tmp/mod_auth_openid.db";
newcfg->use_cookie = true;
newcfg->cookie_name = "open_id_session_id";
newcfg->cookie_path = NULL;
newcfg->trusted = apr_array_make(p, 5, sizeof(char *));
newcfg->distrusted = apr_array_make(p, 5, sizeof(char *));
newcfg->trust_root = NULL;
newcfg->cookie_lifespan = 0;
newcfg->secure_cookie = false;
newcfg->server_name = NULL;
newcfg->auth_program = NULL;
newcfg->use_auth_program = false;
newcfg->use_ax = false;
newcfg->ax_attrs = apr_array_make(p, 5, sizeof(char *));
newcfg->ax_attr_uris = apr_table_make(p, 5);
newcfg->ax_attr_patterns = apr_table_make(p, 5);
newcfg->use_ax_username = false;
newcfg->ax_username_attr = NULL;
newcfg->use_single_idp = false;
newcfg->single_idp_url = NULL;
return (void *) newcfg;
}
static const char *set_modauthopenid_db_location(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->db_location = (char *) arg;
return NULL;
}
static const char *set_modauthopenid_cookie_path(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->cookie_path = (char *) arg;
return NULL;
}
static const char *set_modauthopenid_trust_root(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->trust_root = (char *) arg;
return NULL;
}
static const char *set_modauthopenid_login_page(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->login_page = (char *) arg;
return NULL;
}
static const char *set_modauthopenid_cookie_name(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->cookie_name = (char *) arg;
return NULL;
}
static const char *set_modauthopenid_usecookie(cmd_parms *parms, void *mconfig, int flag) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->use_cookie = (bool) flag;
return NULL;
}
static const char *set_modauthopenid_cookie_lifespan(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->cookie_lifespan = atoi(arg);
return NULL;
}
static const char *set_modauthopenid_secure_cookie(cmd_parms *parms, void *mconfig, int flag) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->secure_cookie = (bool) flag;
return NULL;
}
static const char *add_modauthopenid_trusted(cmd_parms *cmd, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
*(const char **)apr_array_push(s_cfg->trusted) = arg;
return NULL;
}
static const char *add_modauthopenid_distrusted(cmd_parms *cmd, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
*(const char **)apr_array_push(s_cfg->distrusted) = arg;
return NULL;
}
static const char *set_modauthopenid_server_name(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->server_name = (char *) arg;
return NULL;
}
static const char *set_modauthopenid_auth_program(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->auth_program = (char *) arg;
s_cfg->use_auth_program = true;
return NULL;
}
static const char *set_modauthopenid_ax_require(cmd_parms *parms, void *mconfig, const char *alias,
const char *uri,
const char *pattern) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->use_ax = true;
*(const char **)apr_array_push(s_cfg->ax_attrs) = alias;
apr_table_set(s_cfg->ax_attr_uris, alias, uri);
apr_table_set(s_cfg->ax_attr_patterns, alias, pattern);
return NULL;
}
static const char *set_modauthopenid_ax_username(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->use_ax_username = true;
s_cfg->ax_username_attr = (char *) arg;
return NULL;
}
static const char *set_modauthopenid_single_idp(cmd_parms *parms, void *mconfig, const char *arg) {
modauthopenid_config *s_cfg = (modauthopenid_config *) mconfig;
s_cfg->use_single_idp = true;
s_cfg->single_idp_url = (char *) arg;
return NULL;
}
static const command_rec mod_authopenid_cmds[] = {
AP_INIT_TAKE1("AuthOpenIDCookieLifespan", (CMD_HAND_TYPE) set_modauthopenid_cookie_lifespan, NULL, OR_AUTHCFG,
"AuthOpenIDCookieLifespan <number seconds>"),
AP_INIT_TAKE1("AuthOpenIDDBLocation", (CMD_HAND_TYPE) set_modauthopenid_db_location, NULL, OR_AUTHCFG,
"AuthOpenIDDBLocation <string>"),
AP_INIT_TAKE1("AuthOpenIDLoginPage", (CMD_HAND_TYPE) set_modauthopenid_login_page, NULL, OR_AUTHCFG,
"AuthOpenIDLoginPage <url string>"),
AP_INIT_TAKE1("AuthOpenIDTrustRoot", (CMD_HAND_TYPE) set_modauthopenid_trust_root, NULL, OR_AUTHCFG,
"AuthOpenIDTrustRoot <trust root to use>"),
AP_INIT_TAKE1("AuthOpenIDCookieName", (CMD_HAND_TYPE) set_modauthopenid_cookie_name, NULL, OR_AUTHCFG,
"AuthOpenIDCookieName <name of cookie to use>"),
AP_INIT_TAKE1("AuthOpenIDCookiePath", (CMD_HAND_TYPE) set_modauthopenid_cookie_path, NULL, OR_AUTHCFG,
"AuthOpenIDCookiePath <path of cookie to use>"),
AP_INIT_FLAG("AuthOpenIDUseCookie", (CMD_HAND_TYPE) set_modauthopenid_usecookie, NULL, OR_AUTHCFG,
"AuthOpenIDUseCookie <On | Off> - use session auth?"),
AP_INIT_FLAG("AuthOpenIDSecureCookie", (CMD_HAND_TYPE) set_modauthopenid_secure_cookie, NULL, OR_AUTHCFG,
"AuthOpenIDSecureCookie <On | Off> - restrict session cookie to HTTPS connections"),
AP_INIT_ITERATE("AuthOpenIDTrusted", (CMD_HAND_TYPE) add_modauthopenid_trusted, NULL, OR_AUTHCFG,
"AuthOpenIDTrusted <a list of trusted identity providers>"),
AP_INIT_ITERATE("AuthOpenIDDistrusted", (CMD_HAND_TYPE) add_modauthopenid_distrusted, NULL, OR_AUTHCFG,
"AuthOpenIDDistrusted <a blacklist list of identity providers>"),
AP_INIT_TAKE1("AuthOpenIDServerName", (CMD_HAND_TYPE) set_modauthopenid_server_name, NULL, OR_AUTHCFG,
"AuthOpenIDServerName <server name and port prefix>"),
AP_INIT_TAKE1("AuthOpenIDUserProgram", (CMD_HAND_TYPE) set_modauthopenid_auth_program, NULL, OR_AUTHCFG,
"AuthOpenIDUserProgram <full path to authentication program>"),
AP_INIT_TAKE3("AuthOpenIDAXRequire", (CMD_HAND_TYPE) set_modauthopenid_ax_require, NULL, OR_AUTHCFG,
"Add AuthOpenIDAXRequire <alias> <URI> <regex>"),
AP_INIT_TAKE1("AuthOpenIDAXUsername", (CMD_HAND_TYPE) set_modauthopenid_ax_username, NULL, OR_AUTHCFG,
"AuthOpenIDAXUsername <alias>"),
AP_INIT_TAKE1("AuthOpenIDSingleIdP", (CMD_HAND_TYPE) set_modauthopenid_single_idp, NULL, OR_AUTHCFG,
"AuthOpenIDSingleIdP <IdP URL>"),
{NULL}
};
// Get the full URI of the request_rec's request location
// clean_params specifies whether or not all openid.* and modauthopenid.* params should be cleared
static void full_uri(request_rec *r, std::string& result, modauthopenid_config *s_cfg, bool clean_params=false) {
std::string hostname(r->hostname);
std::string uri(r->uri);
apr_port_t i_port = ap_get_server_port(r);
// Fetch the APR function for determining if we are looking at an https URL
APR_OPTIONAL_FN_TYPE(ssl_is_https) *using_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https);
std::string prefix = (using_https != NULL && using_https(r->connection)) ? "https://" : "http://";
char *port = apr_psprintf(r->pool, "%lu", (unsigned long) i_port);
std::string s_port = (i_port == 80 || i_port == 443) ? "" : ":" + std::string(port);
std::string args;
if(clean_params) {
opkele::params_t params;
if(r->args != NULL) params = modauthopenid::parse_query_string(std::string(r->args));
modauthopenid::remove_openid_vars(params);
args = params.append_query("", "");
} else {
args = (r->args == NULL) ? "" : "?" + std::string(r->args);
}
if(s_cfg->server_name == NULL)
result = prefix + hostname + s_port + uri + args;
else
result = std::string(s_cfg->server_name) + uri + args;
}
static int show_input(request_rec *r, modauthopenid_config *s_cfg, modauthopenid::error_result_t e) {
if(s_cfg->login_page == NULL) {
std::string msg = modauthopenid::error_to_string(e, false);
return modauthopenid::show_html_input(r, msg);
}
opkele::params_t params;
if(r->args != NULL)
params = modauthopenid::parse_query_string(std::string(r->args));
modauthopenid::remove_openid_vars(params);
std::string uri_location;
full_uri(r, uri_location, s_cfg, true);
params["modauthopenid.referrer"] = uri_location;
params["modauthopenid.error"] = modauthopenid::error_to_string(e, true);
return modauthopenid::http_redirect(r, params.append_query(s_cfg->login_page, ""));
}
static int show_input(request_rec *r, modauthopenid_config *s_cfg) {
if(s_cfg->login_page == NULL)
return modauthopenid::show_html_input(r, "");
opkele::params_t params;
if(r->args != NULL)
params = modauthopenid::parse_query_string(std::string(r->args));
modauthopenid::remove_openid_vars(params);
std::string uri_location;
full_uri(r, uri_location, s_cfg, true);
params["modauthopenid.referrer"] = uri_location;
return modauthopenid::http_redirect(r, params.append_query(s_cfg->login_page, ""));
}
static bool is_trusted_provider(modauthopenid_config *s_cfg, std::string url, request_rec *r) {
if(apr_is_empty_array(s_cfg->trusted))
return true;
char **trusted_sites = (char **) s_cfg->trusted->elts;
std::string base_url = modauthopenid::get_queryless_url(url);
for (int i = 0; i < s_cfg->trusted->nelts; i++) {
pcre * re = modauthopenid::make_regex(trusted_sites[i]);
if(re == NULL) {
APERR(r, "regex compilation failed for regex: %s", trusted_sites[i]);
} else if(modauthopenid::regex_match(base_url, re)) {
modauthopenid::debug(base_url + " is a trusted identity provider");
pcre_free(re);
return true;
} else {
pcre_free(re);
}
}
APWARN(r, "%s is NOT a trusted identity provider", base_url.c_str());
return false;
}
static bool is_distrusted_provider(modauthopenid_config *s_cfg, std::string url, request_rec *r) {
if(apr_is_empty_array(s_cfg->distrusted))
return false;
char **distrusted_sites = (char **) s_cfg->distrusted->elts;
std::string base_url = modauthopenid::get_queryless_url(url);
for (int i = 0; i < s_cfg->distrusted->nelts; i++) {
pcre * re = modauthopenid::make_regex(distrusted_sites[i]);
if(re == NULL) {
APERR(r, "regex compilation failed for regex: %s", distrusted_sites[i]);
} else if(modauthopenid::regex_match(base_url, re)) {
APWARN(r, "%s is a distrusted (on black list) identity provider", base_url.c_str());
pcre_free(re);
return true;
} else {
pcre_free(re);
}
}
APDEBUG(r, "%s is NOT a distrusted identity provider (not blacklisted)", base_url.c_str());
return false;
};
static bool has_valid_session(request_rec *r, modauthopenid_config *s_cfg) {
// test for valid session - if so, return DECLINED
std::string session_id = "";
modauthopenid::get_session_id(r, std::string(s_cfg->cookie_name), session_id);
if(session_id != "" && s_cfg->use_cookie) {
modauthopenid::debug("found session_id in cookie: " + session_id);
modauthopenid::session_t session;
modauthopenid::SessionManager sm(std::string(s_cfg->db_location));
sm.get_session(session_id, session);
sm.close();
// if session found
if(session.identity != "") {
std::string uri_path;
modauthopenid::base_dir(std::string(r->uri), uri_path);
std::string valid_path(session.path);
// if found session has a valid path
if(valid_path == uri_path.substr(0, valid_path.size()) && strcmp(session.hostname.c_str(), r->hostname)==0) {
const char* idchar = s_cfg->use_ax_username
? session.username.c_str()
: session.identity.c_str();
APDEBUG(r, "setting REMOTE_USER to %s", idchar);
r->user = apr_pstrdup(r->pool, idchar);
return true;
} else {
APDEBUG(r, "session found for different path or hostname (cookie was for %s)", session.hostname.c_str());
}
}
}
return false;
};
static int start_authentication_session(request_rec *r, modauthopenid_config *s_cfg, opkele::params_t& params,
std::string& return_to, std::string& trust_root) {
// remove all openid GET query params (openid.*) - we don't want that maintained through
// the redirection process. We do, however, want to keep all other GET params.
// also, add a nonce for security
std::string identity = s_cfg->use_single_idp
? s_cfg->single_idp_url
: params.get_param("openid_identifier");
APDEBUG(r, "identity = %s, use_single_idp = %s", identity.c_str(), s_cfg->use_single_idp ? "true" : "false");
// pull out the extension parameters before we get rid of openid.*
opkele::params_t ext_params;
modauthopenid::get_extension_params(ext_params, params);
modauthopenid::remove_openid_vars(params);
// if attribute directives are set, add AX stuff to extension params
if(s_cfg->use_ax)
{
ext_params["openid.ns." DEFAULT_AX_NAMESPACE_ALIAS] = AX_NAMESPACE;
ext_params["openid." DEFAULT_AX_NAMESPACE_ALIAS ".mode"] = "fetch_request";
std::string required = "";
bool first_alias = true;
for(int i = 0; i < s_cfg->ax_attrs->nelts; ++i) {
std::string alias = APR_ARRAY_IDX(s_cfg->ax_attrs, i, const char *);
std::string uri = apr_table_get(s_cfg->ax_attr_uris, alias.c_str());
ext_params["openid." DEFAULT_AX_NAMESPACE_ALIAS ".type." + alias] = uri;
if(first_alias) {
first_alias = false;
} else {
required += ',';
}
required += alias;
}
ext_params["openid." DEFAULT_AX_NAMESPACE_ALIAS ".required"] = required;
}
// add a nonce and reset what return_to is
std::string nonce, re_direct;
modauthopenid::make_rstring(10, nonce);
modauthopenid::MoidConsumer consumer(std::string(s_cfg->db_location), nonce, return_to);
params["modauthopenid.nonce"] = nonce;
full_uri(r, return_to, s_cfg, true);
return_to = params.append_query(return_to, "");
// get identity provider and redirect
try {
consumer.initiate(identity);
opkele::openid_message_t cm;
re_direct = consumer.checkid_(cm, opkele::mode_checkid_setup, return_to, trust_root).append_query(consumer.get_endpoint().uri);
re_direct = ext_params.append_query(re_direct, "");
} catch (opkele::failed_xri_resolution &e) {
consumer.close();
return show_input(r, s_cfg, modauthopenid::invalid_id);
} catch (opkele::failed_discovery &e) {
consumer.close();
return show_input(r, s_cfg, modauthopenid::invalid_id);
} catch (opkele::bad_input &e) {
consumer.close();
return show_input(r, s_cfg, modauthopenid::invalid_id);
} catch (opkele::exception &e) {
consumer.close();
APERR(r, "Error while fetching idP location: %s", e.what());
return show_input(r, s_cfg, modauthopenid::no_idp_found);
}
consumer.close();
if(!is_trusted_provider(s_cfg , re_direct, r) || is_distrusted_provider(s_cfg, re_direct, r))
return show_input(r, s_cfg, modauthopenid::idp_not_trusted);
return modauthopenid::http_redirect(r, re_direct);
};
static int set_session_cookie(request_rec *r, modauthopenid_config *s_cfg, opkele::params_t& params, std::string identity, std::string username) {
// now set auth cookie, if we're doing session based auth
std::string session_id, hostname, path, cookie_value, redirect_location, args;
if(s_cfg->cookie_path != NULL)
path = std::string(s_cfg->cookie_path);
else
modauthopenid::base_dir(std::string(r->uri), path);
modauthopenid::make_rstring(32, session_id);
modauthopenid::make_cookie_value(cookie_value, std::string(s_cfg->cookie_name), session_id, path, s_cfg->cookie_lifespan, s_cfg->secure_cookie);
APDEBUG(r, "Setting cookie after authentication of user %s", identity.c_str());
apr_table_set(r->err_headers_out, "Set-Cookie", cookie_value.c_str());
hostname = std::string(r->hostname);
// save session values
modauthopenid::SessionManager sm(std::string(s_cfg->db_location));
sm.store_session(session_id, hostname, path, identity, username, s_cfg->cookie_lifespan);
sm.close();
opkele::params_t ext_params;
modauthopenid::get_extension_params(ext_params, params);
modauthopenid::remove_openid_vars(params);
modauthopenid::merge_params(ext_params, params);
args = params.append_query("", "").substr(1);
if(args.length() == 0)
r->args = NULL;
else
apr_cpystrn(r->args, args.c_str(), 1024);
full_uri(r, redirect_location, s_cfg);
return modauthopenid::http_redirect(r, redirect_location);
};
static int validate_authentication_session(request_rec *r, modauthopenid_config *s_cfg, opkele::params_t& params, std::string& return_to) {
// make sure nonce is present
if(!params.has_param("modauthopenid.nonce"))
return show_input(r, s_cfg, modauthopenid::invalid_nonce);
modauthopenid::MoidConsumer consumer(std::string(s_cfg->db_location), params.get_param("modauthopenid.nonce"), return_to);
try {
consumer.id_res(modauthopenid::modauthopenid_message_t(params));
// if no exception raised, check nonce
if(!consumer.session_exists()) {
consumer.close();
return show_input(r, s_cfg, modauthopenid::invalid_nonce);
}
// if we did an AX query, check the result
std::string ax_username;
if(s_cfg->use_ax) {
// get the AX namespace alias
std::string ns_pfx = "openid.ns.";
std::string ax_value_pfx;
for(opkele::params_t::iterator iter = params.begin(); iter != params.end(); ++iter) {
if(iter->second == AX_NAMESPACE) {
size_t pos = iter->first.find(ns_pfx);
if (pos == 0) {
ax_value_pfx = "openid." + iter->first.substr(pos + ns_pfx.length()) + ".value.";
break;
}
}
}
if (ax_value_pfx.empty()) {
APERR(r, "No AX namespace alias found in response%s", "");
consumer.close();
return show_input(r, s_cfg, modauthopenid::ax_bad_response);
} else {
APDEBUG(r, "AX value param name prefix: %s", ax_value_pfx.c_str());
}
// try to find and validate value params for each attribute in our config
for(int i = 0; i < s_cfg->ax_attrs->nelts; ++i) {
const char *attr = APR_ARRAY_IDX(s_cfg->ax_attrs, i, const char *);
std::string param_name = ax_value_pfx + attr;
std::map<std::string, std::string>::iterator param = params.find(param_name);
if(param == params.end())
{
APERR(r, "AX: attribute %s not found", attr);
consumer.close();
return show_input(r, s_cfg, modauthopenid::ax_bad_response);
}
std::string& value = param->second;
std::string pattern = apr_table_get(s_cfg->ax_attr_patterns, attr);
pcre *re = modauthopenid::make_regex(pattern);
bool match = modauthopenid::regex_match(value, re);
pcre_free(re);
if(!match) {
consumer.close();
APERR(r, "AX: %s attribute %s didn't match %s", attr, value.c_str(), pattern.c_str());
return show_input(r, s_cfg, modauthopenid::unauthorized);
} else {
APDEBUG(r, "AX: %s attribute %s matched %s", attr, value.c_str(), pattern.c_str());
if(s_cfg->use_ax_username && strcmp(attr, s_cfg->ax_username_attr) == 0) {
ax_username = value;
}
}
}
if(s_cfg->use_ax_username) {
if(ax_username.empty()) {
consumer.close();
APERR(r, "AX: username attribute %s not found", s_cfg->ax_username_attr);
return show_input(r, s_cfg, modauthopenid::unauthorized);
} else {
APDEBUG(r, "AX: username = %s", ax_username.c_str());
}
}
}
// if we should be using a user specified auth program, run it to see if user is authorized
if(s_cfg->use_auth_program) {
std::string username = consumer.get_claimed_id();
std::string progname = std::string(s_cfg->auth_program);
modauthopenid::exec_result_t eresult = modauthopenid::exec_auth(progname, username);
if(eresult != modauthopenid::id_accepted) {
std::string error = modauthopenid::exec_error_to_string(eresult, progname, username);
APERR(r, "Error in authentication: %s", error.c_str());
consumer.close();
return show_input(r, s_cfg, modauthopenid::unauthorized);
} else {
APDEBUG(r, "Authenticated %s using %s", username.c_str(), progname.c_str());
}
}
// Make sure that identity is set to the original one given by the user (in case of delegation
// this will be different than openid_identifier GET param
std::string identity = consumer.get_claimed_id();
consumer.kill_session();
consumer.close();
if(s_cfg->use_cookie)
return set_session_cookie(r, s_cfg, params, identity, ax_username);
std::string remote_user = s_cfg->use_ax_username
? ax_username
: identity;
// if we're not setting cookie - don't redirect, just show page
APDEBUG(r, "Setting REMOTE_USER to %s", remote_user.c_str());
r->user = apr_pstrdup(r->pool, remote_user.c_str());
return DECLINED;
} catch(opkele::exception &e) {
APERR(r, "Error in authentication: %s", e.what());
consumer.close();
return show_input(r, s_cfg, modauthopenid::unspecified);
}
};
static int mod_authopenid_method_handler(request_rec *r) {
modauthopenid_config *s_cfg;
s_cfg = (modauthopenid_config *) ap_get_module_config(r->per_dir_config, &authopenid_module);
// if we're not enabled for this location/dir, decline doing anything
const char *current_auth = ap_auth_type(r);
if (!current_auth || strcasecmp(current_auth, "openid"))
return DECLINED;
// make a record of our being called
APDEBUG(r, "*** %s module has been called ***", PACKAGE_STRING);
// if user has a valid session, they are authorized (OK)
if(has_valid_session(r, s_cfg))
return OK;
// parse the get/post params
opkele::params_t params;
modauthopenid::get_request_params(r, params);
// get our current url and trust root
std::string return_to, trust_root;
full_uri(r, return_to, s_cfg);
if(s_cfg->trust_root == NULL)
modauthopenid::base_dir(return_to, trust_root);
else
trust_root = std::string(s_cfg->trust_root);
if(params.has_param("openid.assoc_handle")) {
// user has been redirected, authenticate them and set cookie
return validate_authentication_session(r, s_cfg, params, return_to);
} else if(params.has_param("openid.mode") && params.get_param("openid.mode") == "cancel") {
// authentication cancelled, display message
return show_input(r, s_cfg, modauthopenid::canceled);
} else if(params.has_param("openid_identifier") || s_cfg->use_single_idp) {
// user is posting id URL, or we're in single OP mode and already have one, so try to authenticate
return start_authentication_session(r, s_cfg, params, return_to, trust_root);
} else {
// display an input form
return show_input(r, s_cfg);
}
}
static int mod_authopenid_check_user_access(request_rec *r) {
modauthopenid_config *s_cfg;
s_cfg = (modauthopenid_config *) ap_get_module_config(r->per_dir_config, &authopenid_module);
char *user = r->user;
int m = r->method_number;
int required_user = 0;
register int x;
const char *t, *w;
const apr_array_header_t *reqs_arr = ap_requires(r);
require_line *reqs;
if (!reqs_arr)
return DECLINED;
reqs = (require_line *)reqs_arr->elts;
for (x = 0; x < reqs_arr->nelts; x++) {
if (!(reqs[x].method_mask & (AP_METHOD_BIT << m)))
continue;
t = reqs[x].requirement;
w = ap_getword_white(r->pool, &t);
if (!strcasecmp(w, "valid-user"))
return OK;
if (!strcasecmp(w, "user")) {
required_user = 1;
while (t[0]) {
w = ap_getword_conf(r->pool, &t);
if (!strcmp(user, w))
return OK;
}
}
}
if (!required_user)
return DECLINED;
APERR(r, "Access to %s failed: user '%s' invalid", r->uri, user);
ap_note_auth_failure(r);
return HTTP_UNAUTHORIZED;
}
static void mod_authopenid_register_hooks (apr_pool_t *p) {
ap_hook_check_user_id(mod_authopenid_method_handler, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_auth_checker(mod_authopenid_check_user_access, NULL, NULL, APR_HOOK_MIDDLE);
}
//module AP_MODULE_DECLARE_DATA
module AP_MODULE_DECLARE_DATA authopenid_module = {
STANDARD20_MODULE_STUFF,
create_modauthopenid_config,
NULL, // config merge function - default is to override
NULL,
NULL,
mod_authopenid_cmds,
mod_authopenid_register_hooks,
};
<file_sep>SUBDIRS = src
EXTRA_DIST = UPGRADE
ACLOCAL_AMFLAGS = -I acinclude.d
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
#include "mod_auth_openid.h"
namespace modauthopenid {
using namespace std;
SessionManager::SessionManager(const string& storage_location) {
is_closed = false;
// open db file as user rw only
::mode_t old = umask(S_IRWXO|S_IRWXG);
int rc = sqlite3_open(storage_location.c_str(), &db);
umask(old);
if(!test_result(rc, "problem opening database"))
return;
sqlite3_busy_timeout(db, 5000);
string query = "CREATE TABLE IF NOT EXISTS sessionmanager "
"(session_id VARCHAR(33), hostname VARCHAR(255), path VARCHAR(255), identity VARCHAR(255), username VARCHAR(255), expires_on INT)";
rc = sqlite3_exec(db, query.c_str(), 0, 0, 0);
test_result(rc, "problem creating table if it didn't exist already");
};
void SessionManager::get_session(const string& session_id, session_t& session) {
ween_expired();
const char *query = "SELECT session_id,hostname,path,identity,username,expires_on FROM sessionmanager WHERE session_id=%Q LIMIT 1";
char *sql = sqlite3_mprintf(query, session_id.c_str());
int nr, nc;
char **table;
int rc = sqlite3_get_table(db, sql, &table, &nr, &nc, 0);
sqlite3_free(sql);
test_result(rc, "problem fetching session with id " + session_id);
if(nr==0) {
session.identity = "";
debug("could not find session id " + session_id + " in db: session probably just expired");
} else {
session.session_id = string(table[6]);
session.hostname = string(table[7]);
session.path = string(table[8]);
session.identity = string(table[9]);
session.username = string(table[10]);
session.expires_on = strtol(table[11], 0, 0);
}
sqlite3_free_table(table);
};
bool SessionManager::test_result(int result, const string& context) {
if(result != SQLITE_OK){
string msg = "SQLite Error in Session Manager - " + context + ": %s\n";
fprintf(stderr, msg.c_str(), sqlite3_errmsg(db));
sqlite3_close(db);
is_closed = true;
return false;
}
return true;
};
void SessionManager::store_session(const string& session_id, const string& hostname, const string& path, const string& identity, const string& username, int lifespan) {
ween_expired();
time_t rawtime;
time (&rawtime);
// lifespan will be 0 if not specified by user in config - so lasts as long as browser is open. In this case, make it last for up to a day.
int expires_on = (lifespan == 0) ? (rawtime + 86400) : (rawtime + lifespan);
const char* url = "INSERT INTO sessionmanager (session_id,hostname,path,identity,username,expires_on) VALUES(%Q,%Q,%Q,%Q,%Q,%d)";
char *query = sqlite3_mprintf(url, session_id.c_str(), hostname.c_str(), path.c_str(), identity.c_str(), username.c_str(), expires_on);
debug(query);
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem inserting session into db");
};
void SessionManager::ween_expired() {
time_t rawtime;
time (&rawtime);
char *query = sqlite3_mprintf("DELETE FROM sessionmanager WHERE %d > expires_on", rawtime);
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem weening expired sessions from table");
};
// This is a method to be used by a utility program, never the apache module
void SessionManager::print_table() {
ween_expired();
print_sqlite_table(db, "sessionmanager");
};
void SessionManager::close() {
if(is_closed)
return;
is_closed = true;
test_result(sqlite3_close(db), "problem closing database");
};
}
<file_sep>noinst_LTLIBRARIES = libmodauthopenid.la
noinst_PROGRAMS = db_info
noinst_DATA = mod_auth_openid.la
INCLUDES = ${APACHE_CFLAGS} ${OPKELE_CFLAGS} ${SQLITE3_CFLAGS} ${PCRE_CFLAGS} ${CURL_CFLAGS}
AM_LDFLAGS = ${OPKELE_LIBS} ${SQLITE3_LDFLAGS} ${PCRE_LIBS} ${CURL_LIBS} ${APR_LDFLAGS}
libmodauthopenid_la_SOURCES = mod_auth_openid.cpp MoidConsumer.cpp moid_utils.cpp http_helpers.cpp \
SessionManager.cpp config.h http_helpers.h mod_auth_openid.h MoidConsumer.h moid_utils.h \
SessionManager.h types.h
db_info_SOURCES = db_info.cpp
db_info_LDFLAGS = -lmodauthopenid
db_info_DEPENDENCIES = libmodauthopenid.la
AM_CXXFLAGS = -Wall
if NITPICK
AM_CXXFLAGS += -Wextra -Wundef -Wshadow -Wunsafe-loop-optimizations -Wconversion -Wmissing-format-attribute
AM_CXXFLAGS += -Wredundant-decls -ansi -Wmissing-noreturn
endif
if DEBUG
AM_CXXFLAGS += -DDEBUG
endif
install-exec-local:
${APXS} -i -a -n 'authopenid' mod_auth_openid.la
mod_auth_openid.la: libmodauthopenid.la
${APXS} -c -o $@ $< ${APACHE_CFLAGS} ${OPKELE_CFLAGS} ${OPKELE_LIBS} \
${SQLITE3_CFLAGS} ${PCRE_LIBS} ${CURL_LIBS}
<file_sep>#! /bin/sh
libtoolize -f -c && aclocal -I ./acinclude.d -I /usr/share/aclocal && autoheader && automake -ac -Woverride && autoconf && ./configure "$@"
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
/* Apache includes. */
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_request.h"
#include "apr_strings.h"
#include "http_protocol.h"
#include "http_main.h"
#include "util_script.h"
#include "ap_config.h"
#include "http_log.h"
#include "mod_ssl.h"
#include "apr.h"
#include "apr_general.h"
#include "apr_time.h"
/* other general lib includes */
#include <curl/curl.h>
#include <pcre.h>
#include <sqlite3.h>
#include <ctime>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <algorithm>
#include <string>
#include <vector>
/* opkele includes */
#include <opkele/exception.h>
#include <opkele/types.h>
#include <opkele/util.h>
#include <opkele/association.h>
#include <opkele/prequeue_rp.h>
/* overwrite package vars set by apache */
#undef PACKAGE_BUGREPORT
#undef PACKAGE_NAME
#undef PACKAGE_STRING
#undef PACKAGE_TARNAME
#undef PACKAGE_VERSION
#undef PACKAGE_URL
/* Header enctype for POSTed form data */
#define DEFAULT_POST_ENCTYPE "application/x-www-form-urlencoded"
/* Attribute Exchange */
#define AX_NAMESPACE "http://openid.net/srv/ax/1.0"
#define DEFAULT_AX_NAMESPACE_ALIAS "ax"
/* mod_auth_openid includes */
#include "config.h"
#include "types.h"
#include "http_helpers.h"
#include "moid_utils.h"
#include "SessionManager.h"
#include "MoidConsumer.h"
<file_sep>AC_INIT([mod_auth_openid], [0.7], [<EMAIL>])
AC_DEFINE([PACKAGE_URL],["http://findingscience.com/mod_auth_openid"],[project url])
AM_CONFIG_HEADER(src/config.h)
AM_INIT_AUTOMAKE()
AC_CONFIG_MACRO_DIR([acinclude.d])
AC_PROG_CXX
AC_PROG_CXXCPP
AC_LANG_CPLUSPLUS
AC_CANONICAL_HOST
AC_PROG_INSTALL
AM_PROG_LIBTOOL
AC_HEADER_STDC
# provide flag --enable-debug
AC_ARG_ENABLE([debug],
[ --enable-debug Enable debugging output to Apache error log],
[case "${enableval}" in
yes) debug=true ;;
no) debug=false ;;
*) AC_MSG_ERROR([bad value ${enableval} for --enable-debug]) ;;
esac],[debug=false])
AM_CONDITIONAL([DEBUG], [test x$debug = xtrue])
# this will look for apxs command - put it in $APXS, fail on failure
AX_WITH_APXS()
# find apr-config binary
AC_ARG_WITH(apr_config, AC_HELP_STRING([[--with-apr-config=FILE]], [Path to apr-config program]),
[ apr_config="$withval" ],
[AC_PATH_PROGS(apr_config,
[apr-config apr-0-config apr-1-config],
[no],
[$PATH:/usr/sbin/:/usr/local/apache2/bin]
)]
)
if test "$apr_config" = "no"; then
AC_MSG_ERROR(Could not find the apr-config program. You can specify a location with the --with-apr-config=FILE option. It may be named apr-0-config or apr-1-config and can be found in your apache2 bin directory.)
fi
$apr_config --cppflags &> /dev/null
if test "$?" != "0"; then
AC_MSG_ERROR($apr_config is not a valid apr-config program)
fi
AX_LIB_SQLITE3([3.3.0])
if test "$SQLITE3_VERSION" == ""; then
AC_MSG_ERROR([No sqlite 3 (http://www.sqlite.org) library found.])
fi
APR_LDFLAGS="`${apr_config} --link-ld --libs`"
AC_SUBST(APR_LDFLAGS)
APACHE_CFLAGS="-I`${APXS} -q INCLUDEDIR` -I`${apr_config} --includedir`"
AC_SUBST(APACHE_CFLAGS)
PKG_CHECK_MODULES([OPKELE],[libopkele >= 2.0],,[
AC_MSG_ERROR([no libopkele library found (version 2.0 or higher). get one from http://kin.klever.net/libopkele/])
])
# These next few are prerequisites for libopekele, but it's possible they've been removed since that install....
# Check for pcre
AX_PATH_LIB_PCRE([], [ AC_MSG_ERROR([No pcre library found. You can get it at http://www.pcre.org]) ])
AC_SUBST(PCRE_LIBS)
AC_SUBST(PCRE_CFLAGS)
# Check for curl
AC_CHECK_CURL([7], [], [ AC_MSG_ERROR([No curl library found. You can get it at http://curl.haxx.se]) ])
AC_SUBST(CURL_CFLAGS)
AC_SUBST(CURL_LIBS)
# Idea taken from libopekele
nitpick=false
AC_ARG_ENABLE([nitpicking],
AC_HELP_STRING([--enable-nitpicking],[make compiler warn about possible problems]),
[ test "$enableval" = "no" || nitpick=true ]
)
AM_CONDITIONAL(NITPICK, test x$nitpick = xtrue)
AC_CONFIG_FILES([
Makefile
src/Makefile
])
AC_OUTPUT
echo " ***"
echo " *** You are now ready to build mod_auth_openid:"
echo " *** Enter the following commands:"
echo " ***"
echo " *** $> make"
echo " *** $> su root"
echo " *** $> make install"
echo " ***"
echo " *** Report bugs at http://github.com/bmuller/mod_auth_openid/issues"
echo " *** Thanks for using free (as in speech and beer) software."
echo " ***"
echo
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
namespace modauthopenid {
using namespace opkele;
using namespace std;
// get the appropriate error string for the given error
string error_to_string(error_result_t e, bool use_short_string);
// explode string s into parts, split based on occurance of e
vector<string> explode(string s, string e);
// replace needle with replacement in haystack
string str_replace(string needle, string replacement, string haystack);
// Should be using ap_log_error, but that would mean passing a server_rec* or request_rec* around.....
// gag.... I'm just assuming that if you're going to be debugging it shouldn't really matter, since
// apache redirects stderr to the error log anyway.
void debug(string s);
// return true if pattern found in subject
bool regex_match(string subject, pcre * re);
// create a regular expression from the given pattern
pcre * make_regex(string pattern);
// strip any spaces before or after actual string in s
void strip(string& s);
// make a random string of size size
void make_rstring(int size, string& s);
// print an sqlite table to stdout
void print_sqlite_table(sqlite3 *db, string tablename);
// test a sqlite return value, print error if there is one to stdout and return false,
// return true on no error
bool test_sqlite_return(sqlite3 *db, int result, const string& context);
// Exec a program located at exec_location with a single parameter of username
// program should return a exec_result_t value.
// NOTE: if program hangs, so does apache
exec_result_t exec_auth(string exec_location, string username);
// convert a exec_result_t value to a meaningful error message
string exec_error_to_string(exec_result_t e, string exec_location, string id);
// Generate a random integer - taken from getuuid.c file in apr-util program
int true_random();
}
<file_sep>/*
Copyright (C) 2007-2010 Butterfat, LLC (http://butterfat.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Created by bmuller <<EMAIL>>
*/
#include "mod_auth_openid.h"
namespace modauthopenid {
using namespace std;
using namespace opkele;
MoidConsumer::MoidConsumer(const string& storage_location, const string& _asnonceid, const string& _serverurl) :
asnonceid(_asnonceid), serverurl(_serverurl), is_closed(false), endpoint_set(false), normalized_id("") {
// open db file as user rw only
::mode_t old = umask(S_IRWXO|S_IRWXG);
int rc = sqlite3_open(storage_location.c_str(), &db);
umask(old);
if(!test_result(rc, "problem opening database"))
return;
sqlite3_busy_timeout(db, 5000);
string query = "CREATE TABLE IF NOT EXISTS authentication_sessions "
"(nonce VARCHAR(255), uri VARCHAR(255), claimed_id VARCHAR(255), local_id VARCHAR(255), normalized_id VARCHAR(255), expires_on INT)";
rc = sqlite3_exec(db, query.c_str(), 0, 0, 0);
test_result(rc, "problem creating sessions table if it didn't exist already");
query = "CREATE TABLE IF NOT EXISTS associations "
"(server VARCHAR(255), handle VARCHAR(100), encryption_type VARCHAR(50), secret VARCHAR(30), expires_on INT)";
rc = sqlite3_exec(db, query.c_str(), 0, 0, 0);
test_result(rc, "problem creating associations table if it didn't exist already");
query = "CREATE TABLE IF NOT EXISTS response_nonces "
"(server VARCHAR(255), response_nonce VARCHAR(100), expires_on INT)";
rc = sqlite3_exec(db, query.c_str(), 0, 0, 0);
test_result(rc, "problem creating response_nonces table if it didn't exist already");
};
assoc_t MoidConsumer::store_assoc(const string& server,const string& handle,const string& type,const secret_t& secret,int expires_in) {
debug("Storing association for \"" + server + "\" and handle \"" + handle + "\" in db");
ween_expired();
time_t rawtime;
time (&rawtime);
int expires_on = rawtime + expires_in;
const char *query = "INSERT INTO associations (server, handle, secret, expires_on, encryption_type) VALUES(%Q,%Q,%Q,%d,%Q)";
char *sql = sqlite3_mprintf(query,
server.c_str(),
handle.c_str(),
util::encode_base64(&(secret.front()),secret.size()).c_str(),
expires_on,
type.c_str());
int rc = sqlite3_exec(db, sql, 0, 0, 0);
sqlite3_free(sql);
test_result(rc, "problem storing association in associations table");
return assoc_t(new association(server, handle, type, secret, expires_on, false));
};
assoc_t MoidConsumer::retrieve_assoc(const string& server, const string& handle) {
ween_expired();
debug("looking up association: server = " + server + " handle = " + handle);
const char *query = "SELECT server,handle,secret,expires_on,encryption_type FROM associations WHERE server=%Q AND handle=%Q LIMIT 1";
char *sql = sqlite3_mprintf(query, server.c_str(), handle.c_str());
int nr, nc;
char **table;
int rc = sqlite3_get_table(db, sql, &table, &nr, &nc, 0);
sqlite3_free(sql);
test_result(rc, "problem fetching association");
if(nr ==0) {
debug("could not find server \"" + server + "\" and handle \"" + handle + "\" in db.");
sqlite3_free_table(table);
throw failed_lookup(OPKELE_CP_ "Could not find association.");
}
// resulting row has table indexes:
// server handle secret expires_on encryption_type
// 5 6 7 8 9
secret_t secret;
util::decode_base64(table[7], secret);
assoc_t result = assoc_t(new association(table[5], table[6], table[9], secret, strtol(table[8], 0, 0), false));
sqlite3_free_table(table);
return result;
};
void MoidConsumer::invalidate_assoc(const string& server,const string& handle) {
debug("invalidating association: server = " + server + " handle = " + handle);
char *query = sqlite3_mprintf("DELETE FROM associations WHERE server=%Q AND handle=%Q", server.c_str(), handle.c_str());
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem invalidating assocation for server \"" + server + "\" and handle \"" + handle + "\"");
};
assoc_t MoidConsumer::find_assoc(const string& server) {
ween_expired();
debug("looking up association: server = " + server);
const char *query = "SELECT server,handle,secret,expires_on,encryption_type FROM associations WHERE server=%Q LIMIT 1";
char *sql = sqlite3_mprintf(query, server.c_str());
int nr, nc;
char **table;
int rc = sqlite3_get_table(db, sql, &table, &nr, &nc, 0);
sqlite3_free(sql);
test_result(rc, "problem fetching association");
if(nr==0) {
debug("could not find handle for server \"" + server + "\" in db.");
sqlite3_free_table(table);
throw failed_lookup(OPKELE_CP_ "Could not find association.");
} else {
debug("found a handle for server \"" + server + "\" in db.");
}
// resulting row has table indexes:
// server handle secret expires_on encryption_type
// 5 6 7 8 9
secret_t secret;
util::decode_base64(table[7], secret);
assoc_t result = assoc_t(new association(table[5], table[6], table[9], secret, strtol(table[8], 0, 0), false));
sqlite3_free_table(table);
return result;
};
bool MoidConsumer::test_result(int result, const string& context) {
if(result != SQLITE_OK){
string msg = "SQLite Error in MoidConsumer - " + context + ": %s\n";
fprintf(stderr, msg.c_str(), sqlite3_errmsg(db));
sqlite3_close(db);
is_closed = true;
return false;
}
return true;
};
void MoidConsumer::ween_expired() {
time_t rawtime;
time (&rawtime);
char *query = sqlite3_mprintf("DELETE FROM associations WHERE %d > expires_on", rawtime);
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem weening expired associations from table");
query = sqlite3_mprintf("DELETE FROM authentication_sessions WHERE %d > expires_on", rawtime);
rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem weening expired authentication sessions from table");
query = sqlite3_mprintf("DELETE FROM response_nonces WHERE %d > expires_on", rawtime);
rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem weening expired response nonces from table");
};
void MoidConsumer::check_nonce(const string& server, const string& nonce) {
debug("checking nonce " + nonce);
int nr, nc;
char **table;
char *query = sqlite3_mprintf("SELECT nonce FROM response_nonces WHERE server=%Q AND response_nonce=%Q", server.c_str(), nonce.c_str());
int rc = sqlite3_get_table(db, query, &table, &nr, &nc, 0);
sqlite3_free(query);
if(nr != 0) {
debug("found preexisting nonce - could be a replay attack");
sqlite3_free_table(table);
throw opkele::id_res_bad_nonce(OPKELE_CP_ "old nonce used again - possible replay attack");
}
sqlite3_free_table(table);
// so, old nonce not found, insert it into nonces table. Expiration time will be based on association
int expires_on = find_assoc(server)->expires_in() + time(0);
const char *sql = "INSERT INTO response_nonces (server,response_nonce,expires_on) VALUES(%Q,%Q,%d)";
query = sqlite3_mprintf(sql, server.c_str(), nonce.c_str(), expires_on);
rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem adding new nonce to resposne_nonces table");
};
bool MoidConsumer::session_exists() {
char *query = sqlite3_mprintf("SELECT nonce FROM authentication_sessions WHERE nonce=%Q LIMIT 1", asnonceid.c_str());
int nr, nc;
char **table;
int rc = sqlite3_get_table(db, query, &table, &nr, &nc, 0);
sqlite3_free(query);
test_result(rc, "problem fetching authentication session by nonce");
bool exists = true;
if(nr==0) {
debug("could not find authentication session \"" + asnonceid + "\" in db.");
exists = false;
}
sqlite3_free_table(table);
return exists;
};
void MoidConsumer::begin_queueing() {
endpoint_set = false;
char *query = sqlite3_mprintf("DELETE FROM authentication_sessions WHERE nonce=%Q", asnonceid.c_str());
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem reseting authentication session");
};
void MoidConsumer::queue_endpoint(const openid_endpoint_t& ep) {
if(!endpoint_set) {
debug("Queueing endpoint " + ep.claimed_id + " : " + ep.local_id + " @ " + ep.uri);
time_t rawtime;
time (&rawtime);
int expires_on = rawtime + 3600; // allow nonce to exist for up to one hour without being returned
const char *query = "INSERT INTO authentication_sessions (nonce,uri,claimed_id,local_id,expires_on) VALUES(%Q,%Q,%Q,%Q,%d)";
char *sql = sqlite3_mprintf(query, asnonceid.c_str(), ep.uri.c_str(), ep.claimed_id.c_str(), ep.local_id.c_str(), expires_on);
debug(string(sql));
int rc = sqlite3_exec(db, sql, 0, 0, 0);
sqlite3_free(sql);
test_result(rc, "problem queuing endpoint");
endpoint_set = true;
}
}
const openid_endpoint_t& MoidConsumer::get_endpoint() const {
debug("Fetching endpoint");
char *query = sqlite3_mprintf("SELECT uri,claimed_id,local_id FROM authentication_sessions WHERE nonce=%Q LIMIT 1", asnonceid.c_str());
int nr, nc;
char **table;
int rc = sqlite3_get_table(db, query, &table, &nr, &nc, 0);
sqlite3_free(query);
test_sqlite_return(db, rc, "problem fetching authentication session");
if(nr==0) {
debug("could not find an endpoint for authentication session \"" + asnonceid + "\" in db.");
sqlite3_free_table(table);
throw opkele::exception(OPKELE_CP_ "No more endpoints queued");
}
// resulting row has table indexes:
// uri claimed_id local_id
// 3 4 5
endpoint.uri = string(table[3]);
endpoint.claimed_id = string(table[4]);
endpoint.local_id = string(table[5]);
sqlite3_free_table(table);
return endpoint;
};
void MoidConsumer::next_endpoint() {
debug("Clearing all session information - we're only storing one endpoint, can't get next one, cause we didn't store it.");
char *query = sqlite3_mprintf("DELETE FROM authentication_sessions WHERE nonce=%Q", asnonceid.c_str());
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem in next_endpoint()");
endpoint_set = false;
};
void MoidConsumer::kill_session() {
char *query = sqlite3_mprintf("DELETE FROM authentication_sessions WHERE nonce=%Q", asnonceid.c_str());
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem killing session");
};
void MoidConsumer::set_normalized_id(const string& nid) {
debug("Set normalized id to: " + nid);
normalized_id = nid;
char *query = sqlite3_mprintf("UPDATE authentication_sessions SET normalized_id=%Q WHERE nonce=%Q", normalized_id.c_str(), asnonceid.c_str());
debug(string(query));
int rc = sqlite3_exec(db, query, 0, 0, 0);
sqlite3_free(query);
test_result(rc, "problem settting normalized id");
};
const string MoidConsumer::get_normalized_id() const {
if(normalized_id != "") {
debug("getting normalized id - " + normalized_id);
return normalized_id;
}
char *query = sqlite3_mprintf("SELECT normalized_id FROM authentication_sessions WHERE nonce=%Q LIMIT 1", asnonceid.c_str());
int nr, nc;
char **table;
int rc = sqlite3_get_table(db, query, &table, &nr, &nc, 0);
sqlite3_free(query);
test_sqlite_return(db, rc, "problem fetching authentication session");
if(nr==0) {
debug("could not find an normalized_id for authentication session \"" + asnonceid + "\" in db.");
sqlite3_free_table(table);
throw opkele::exception(OPKELE_CP_ "cannot get normalized id");
}
normalized_id = string(table[1]);
sqlite3_free_table(table);
debug("getting normalized id - " + normalized_id);
return normalized_id;
};
const string MoidConsumer::get_this_url() const {
return serverurl;
};
// This is a method to be used by a utility program, never the apache module
void MoidConsumer::print_tables() {
ween_expired();
print_sqlite_table(db, "authentication_sessions");
print_sqlite_table(db, "response_nonces");
print_sqlite_table(db, "associations");
};
void MoidConsumer::close() {
if(is_closed)
return;
is_closed = true;
test_result(sqlite3_close(db), "problem closing database");
};
}
| db242a170adc727ae19944e375d711f01b0e03fe | [
"Markdown",
"Makefile",
"M4Sugar",
"C++",
"Shell"
] | 18 | C++ | paranoid/mod_auth_openid | b7d6ce77b5469083ee80d578693273e5fe618c83 | 64c9aac801eaab6ffcd085e346c4ffde0122fbf1 |
refs/heads/master | <file_sep>import React from 'react'
import { Link } from 'react-router-dom'
import { motion } from 'framer-motion'
import { FiX } from 'react-icons/fi'
import './styles.css'
import Bar from '../../../assets/bar.jpg'
import Hoteis from '../../../assets/hoteis.jpg'
import Restaurantes from '../../../assets/restaurantes.jpg'
import Viagens from '../../../assets/viagens.jpg'
const ModalPlaces = ({setModalOpen}) => {
return (
<motion.div
initial={{opacity:0 ,y: 0.1}}
animate={{opacity: 1, y: 0}}
exit={{opacity: 0, y:'50%'}}
>
<div className="container_modal_places">
<button className="button_close_signup" onClick={()=> setModalOpen(false)}>< FiX style={{width: 40, height: 20,fontWeight: 800}}/></button>
<h1 className="modal_places">Tipos de Reservas</h1>
<div className="list_places">
<div>
<Link to="/bares">
<img className="list_image" src={Bar} alt="bar"/>
<p className="list_1">Bares</p>
</Link>
</div>
<div><img className="list_image" src={Hoteis} alt="hoteis"/>
<p className="list_3">Hoteis</p>
</div>
<div><img className="list_image" src={Restaurantes} alt="restaurantes"/>
<p className="list_2">Restaurantes</p>
</div>
<div><img className="list_image" src={Viagens} alt="viagens"/>
<p className="list_4">Viagens</p>
</div>
</div>
</div>
</motion.div>
)}
export default ModalPlaces;<file_sep>import React from 'react';
import { Link } from 'react-router-dom'
import { BsArrowLeft } from 'react-icons/bs'
import NotFoundImg from '../../assets/notfound.svg'
import './styles.css'
const NotFound= () => {
return (
<>
<Link to="/">
<button className="button_back" >Voltar</button>
<BsArrowLeft className="button_back_icon"/>
</Link>
<img className="notFoundImg" src={NotFoundImg} alt="image_booking"/>
<h1>Not Found</h1>
</>
);
}
export default NotFound;
<file_sep>import React, {useState} from 'react';
import { Link, useHistory} from 'react-router-dom'
import { message } from 'antd'
import { motion } from 'framer-motion'
import { FiX } from 'react-icons/fi'
import { FaFacebook } from 'react-icons/fa'
import { FcGoogle } from "react-icons/fc"
import axios from "axios"
import './styles.css'
import { login } from '../../../services/auth';
const ModalSignUp = ({setModalOpen}) => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const history = useHistory()
const handleLogin = async (e) => {
e.preventDefault()
const data = { email, password }
console.log(data)
const key = 'updatable';
if(!email || !password) {
message.info({ content: 'Preencha todos os campos.', key, duration: 3.5 });
}
else {
try {
const response = await axios.post('http://localhost:8080/login', data )
const { token} = response.data
const { id, name, email} = response.data.user
console.log(response.data)
localStorage.setItem('userId', id);
localStorage.setItem('userName', name);
localStorage.setItem('userEmail', email);
localStorage.setItem('token', token);
if(login){
message.loading({ content: 'Loading...', key });
setTimeout(() => {
message.success({ content: ' sucesso.', key, duration: 3 });
}, 1000);
history.push("/session_user")
}else{
message.warning({ content:"Error "
, duration: 3 });
}
} catch (err) {
message.warning({ content:"Error, Este email não esta cadastrado no nosso banco de dados"
, duration: 3 });
}
}
}
return(
<motion.div
initial={{opacity:0 ,y: 0.1}}
animate={{opacity: 1, y: 0}}
exit={{opacity: 0, y:'50%'}}
>
<div className="container_modal_signup">
<button className="button_close_signup" onClick={ ()=> setModalOpen(false)}>< FiX style={{width: 40, height: 20,fontWeight: 800}}/></button>
<div>
<form onSubmit={handleLogin}>
<h1>Entrar</h1>
<h4>Informe email e senha</h4>
<input
className="signup_email"
type="text"
placeholder="email"
value={email}
onChange={ e => setEmail(e.target.value)}
/>
<input
className="signup_password"
type="text"
placeholder="senha"
value={password}
onChange={ e => setPassword(e.target.value)} />
<button className="signup_button_entrar">Entrar</button>
<p className="cadastre-se">Ainda não tem uma conta?
<Link to='/'>
Cadastre - se
</Link></p>
<p>ou</p>
<button className="signup_button_facebook"> Continuar com Facebook</button>
<div className="icon_facebook">
<FaFacebook />
</div>
<button className="signup_button_google">Continuar com Google</button>
<div className="icon_google">
<FcGoogle />
</div>
</form>
</div>
</div>
</motion.div>
)
}
export default ModalSignUp<file_sep>import React from 'react';
import { Divider } from 'antd'
import { motion } from 'framer-motion'
import { FiX, FiLogOut } from 'react-icons/fi'
import { logout } from '../../../services/auth'
import './styles.css'
const ModalUser = ({setModalOpen}) => {
const userEmail = localStorage.getItem('userEmail');
return(
<motion.div
initial={{opacity:0 ,y: 0.1}}
animate={{opacity: 1, y: 0}}
exit={{opacity: 0, y:'50%'}}
>
<div className="container_modal_user">
<button className="button_close_user" onClick={ ()=> setModalOpen(false)}>< FiX style={{width: 40, height: 20,fontWeight: 800}}/></button>
<div>
<Divider />
<p className="signup_user">{userEmail}</p>
<Divider />
<Divider />
<h6 className="logOut" onClick={ () => logout(window.location.reload())} ><FiLogOut/> Sair</h6>
</div>
</div>
</motion.div>
)
}
export default ModalUser | e2e5d53366c94b65080df1a4fc1d83a0b6bcdad7 | [
"JavaScript"
] | 4 | JavaScript | HEINRICK7/Booking_app | c8c71bbf38c0201fc9d8573c06a912947fe36fec | 146a68b874fd7d98818e04d4cee46fa2a3c2390c |
refs/heads/master | <file_sep>#!/bin/bash
# Set up Vundle
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
# Set up Solarized colorscheme
git clone git://github.com/altercation/vim-colors-solarized.git ~/.vim/bundle/vim-colors-solarized.git
cp -R ./.vim ~
cp ./.vimrc ~
# Install Plugins through Vundle
vim +PluginInstall +qall
# Compile YouCompleteMe plugin
cd ~/.vim/bundle/YouCompleteMe
./install.sh --clang-completer
# Add Vundle related configurations to .vimrc
echo '
function Set_c_env()
set colorcolumn=80
highlight ColorColumn ctermbg=darkgray
set tabstop=8
set softtabstop=8
set shiftwidth=8
set noexpandtab
let &path.="src/include,/usr/include"
let g:ycm_global_ycm_extra_conf = "~/.vim/.ycm_extra_conf_c.py"
endfunction
function Set_html_env()
set tabstop=2
set softtabstop=2
set shiftwidth=2
set expandtab
endfunction
function Set_cpp_env()
set colorcolumn=80
highlight ColorColumn ctermbg=darkgray
set tabstop=4
set softtabstop=4
set shiftwidth=4
set expandtab
let &path.="src/include,/usr/include"
let g:ycm_global_ycm_extra_conf = "~/.vim/.ycm_extra_conf_cpp.py"
endfunction
augroup filetype_c
autocmd!
autocmd FileType c :call Set_c_env()
augroup END
augroup filetype_cpp
autocmd!
autocmd FileType cpp :call Set_cpp_env()
augroup END
augroup filetype_html
autocmd!
autocmd FileType html :call Set_html_env()
augroup END
' >> ~/.vimrc
<file_sep># vimrc
This is my vim configuration files. You can install it by typing following commands:
<pre>
$ git clone https://github.com/oys/vimrc.git
$ cd vimrc
$ ./init.sh
</pre>
| 8828f70eaef644437b8d59ca750f415036c97cf8 | [
"Markdown",
"Shell"
] | 2 | Shell | oys/vimrc | da9409bbe268bba14c2a96fe1b90a6afd73c396b | 709db5234e0bf461eeae6063445681774d0f35f2 |
refs/heads/master | <repo_name>charDevMDP/AbstractFactoryPattern<file_sep>/MakerFactory.py
class MakerFactory:
def create_f(self,factory):
return factory<file_sep>/Preguntas.py
from abc import ABC, abstractmethod
class Preguntas(ABC):
@abstractmethod
def preguntaHora(self):
pass
@abstractmethod
def preguntaTiempo(self):
pass
<file_sep>/Saludos.py
from abc import ABC, abstractmethod
class Saludos(ABC):
@abstractmethod
def buenosDias(self):
pass
@abstractmethod
def buenasTardes(self):
pass
<file_sep>/main.py
from FactoryES import FactoryES
from MakerFactory import MakerFactory
from FactoryEN import FactoryEN
def main():
cont = True
while cont:
lenguage = input('Ingrese un idioma (ES-EN) : ')
makerf = MakerFactory()
if lenguage == 'ES' or lenguage == 'EN':
if lenguage == 'ES':
factory = makerf.create_f(FactoryES())
if lenguage == 'EN':
factory = makerf.create_f(FactoryEN())
print(f'IDIOMA {lenguage.upper()} CARGADO')
op = int(input('\nSALUDOS(1) | PREGUNTAS(2) Elige un opcion: '))
if op == 1 or op == 2:
if op == 1:
print(f'\nSALUDOS EN "{lenguage}": ')
print(factory.saludar().buenosDias())
print(factory.saludar().buenasTardes())
print('\n')
if op == 2:
print(f'\nPREGUNTAS EN "{lenguage}": ')
print(factory.preguntar().preguntaHora())
print(factory.preguntar().preguntaTiempo())
print('\n')
resp = input('Desear continuar? (S/N) : ')
if resp.upper() == 'N' or resp.upper() == 'S':
if resp.upper() == 'N':
cont = False
else:
cont = True
else:
print('Parece que fue compleja la pregunta.. bye bye')
cont = False
else:
print('Bue se ve que es complejo esto.. es colocar 1 0 2 nomas')
else:
print(f'{lenguage.upper()} no es un idioma soportado..')
else:
print('bye bye :) ')
main()<file_sep>/FactoryES.py
from Saludos import Saludos
from Preguntas import Preguntas
from FactoryAbs import Factory
class FactoryES(Factory):
def preguntar(self):
return PregES()
def saludar(self):
return SaludarES()
class PregES(Preguntas):
def preguntaHora(self):
return "¿qué hora es?"
def preguntaTiempo(self):
return "¿qué tiempo hace?"
class SaludarES(Saludos):
def buenosDias(self):
return "buenos días"
def buenasTardes(self):
return "buenas tardes"
<file_sep>/FactoryEN.py
from Saludos import Saludos
from Preguntas import Preguntas
from FactoryAbs import Factory
class FactoryEN(Factory):
def preguntar(self):
return PregEN()
def saludar(self):
return SaludarEN()
class PregEN(Preguntas):
def preguntaHora(self):
return "what time is it?"
def preguntaTiempo(self):
return "how is the weather?"
class SaludarEN(Saludos):
def buenosDias(self):
return "good morning"
def buenasTardes(self):
return "good afternoon"
<file_sep>/FactoryAbs.py
from abc import ABC, abstractmethod
# Fabrica Abstracta
class Factory(ABC):
@abstractmethod
def saludar(self):
pass
@abstractmethod
def preguntar(self):
pass
| 926b681e18ac2ee83a61d8d4a456c622fe1618a7 | [
"Python"
] | 7 | Python | charDevMDP/AbstractFactoryPattern | c3122b33fd4f27e82c8b10ad0b311411fa26fbe3 | f7695e4e2cd14ac9179dd1f623bd6ae8aa6b1c69 |
refs/heads/master | <file_sep>class WellcomeController < ApplicationController
before_action :require_login
def homepage
render "wellcome/homepage"
end
end
| 3887d91c100287cfdf7b483d45e1709c6db1de3a | [
"Ruby"
] | 1 | Ruby | DianaBaRo/has_secure_password_lab-online-web-sp-000 | 74f5716f31f21329cacedb9681eae8512ba5aa37 | 83ca5285eff6f43b25f18b8470871fd76762bbea |
refs/heads/master | <repo_name>SidRaghib/OnlineCart<file_sep>/SpringMVCAnnotationShoppingMart/src/main/java/org/raghib/springmvcshoppingcart/dao/AccountDAO.java
package org.raghib.springmvcshoppingcart.dao;
import org.raghib.springmvcshoppingcart.entity.Account;
public interface AccountDAO {
public Account findAccount(String userName );
}
| 7bef541cb584f78fc2e7a6bf9b66d8a8cfeb1d2f | [
"Java"
] | 1 | Java | SidRaghib/OnlineCart | f60e6817036c224f39d6e1eb1fea8aeb5d3cbe28 | c2e00634a51bc7ab1aeabc6db8674d35b8490405 |
refs/heads/master | <repo_name>jchen114/TouchesApplication<file_sep>/app/src/main/java/edu/activeauth/umcp/touchesapplication/ScrollPackage/ScrollImageAdapter.java
package edu.activeauth.umcp.touchesapplication.ScrollPackage;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Created by Hooligan on 7/21/2015.
*/
public class ScrollImageAdapter extends FragmentStatePagerAdapter {
private static String mLogTag = "ScrollImageAdapter";
private int NUM_PAGES;
private Context mContext;
private boolean mHorizontal = true;
public ScrollImageAdapter(FragmentManager fm, int numPages, Context context, boolean horizontal) {
super(fm);
NUM_PAGES = numPages;
mContext = context;
mHorizontal = horizontal;
}
@Override
public Fragment getItem(int position) {
PhotoViewFragment pf = new PhotoViewFragment();
NumberFormat f = new DecimalFormat("00");
String imageName;
if (mHorizontal) {
imageName = "img" + f.format(position + 1);
} else {
imageName = "img" + f.format(position + 8);
}
int resId = mContext.getResources().getIdentifier(imageName, "drawable", mContext.getPackageName());
Log.d(mLogTag, "imageName: " + imageName + " resId: " + Integer.toString(resId));
Bundle args = new Bundle();
args.putInt(PhotoViewFragment.RESOURCE_KEY, resId);
pf.setArguments(args);
return pf;
}
@Override
public int getCount() {
return NUM_PAGES;
}
}<file_sep>/README.md
# TouchesApplication
Collects the touch data from various activities:
- Horizontal Scrolling
- Vertical Scrolling
- Image Dragging
- Finding something inside a large image.
<file_sep>/app/src/main/java/edu/activeauth/umcp/touchesapplication/FindingPackage/FindingActivity.java
package edu.activeauth.umcp.touchesapplication.FindingPackage;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import edu.activeauth.umcp.touchesapplication.R;
import edu.activeauth.umcp.touchesapplication.TouchBaseActivity;
/**
* Created by Hooligan on 7/23/2015.
*/
public class FindingActivity extends TouchBaseActivity {
WebView mWaldoWebView;
private static String mLogTag = "FindingActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
Log.d(mLogTag, "On Start");
View view = getLayoutInflater().inflate(R.layout.waldo_web_view, null);
mWaldoWebView = (WebView) view.findViewById(R.id.waldo_web_view);
mWaldoWebView.loadUrl("file:///android_asset/waldo.html");
mWaldoWebView.getSettings().setBuiltInZoomControls(true);
mWaldoWebView.getSettings().setDisplayZoomControls(false);
mWaldoWebView.setOnTouchListener(this);
mRelativeLayout.addView(mWaldoWebView);
}
}
| 2a5eccb47a1f24dc2e50fed20e88084a1aba0cf4 | [
"Markdown",
"Java"
] | 3 | Java | jchen114/TouchesApplication | d40a58766702b961bce23610f12191384e1117d8 | 2ce76b0352539a292f3476da3b2ad3fefeeead34 |
refs/heads/master | <repo_name>biletnam/events-manager-seats<file_sep>/CONTRIBUTING.md
# Contributing
Pull requests welcome! We used the Events Manager plugin to coordinate TEDxCheyenne 2016, and managing *who* was sitting in each purchased seat was burdensome. This plugin aims to alleviate the individual seating burden, so that you can focus on running your event.
# Contributors
[<NAME>](https://github.com/bradkovach)<file_sep>/classes/SimpleOrm.class.php
<?php
/**
* Class SimpleOrm
* Not really an ORM, but is very useful for "unjoining" data. So if you have rows of join data, use this to create structured arrays.
*/
class SimpleOrm {
/**
* @param $collection mixed
* @param $keepers array properties to keep in the collection
*
* @return array
*/
static function pluck( $collection, $keepers ) {
$result = [];
$collection = (array) $collection;
foreach ( $keepers as $keeper ) {
if ( isset( $collection[ $keeper ] ) ) {
$result[ $keeper ] = $collection[ $keeper ];
}
}
return $result;
}
/**
* Imposes ORM-style structure on unstructured rows of data.
*
* @param $rows array Unstructured rows of data
*
* array(
* array(
* 'event_id' => 1,
* 'event_name' => "Event One",
* 'attendee_id' => 1
* 'attendee_first_name' => "John",
* 'attendee_last_name' => "Doe",
* ),
* array(
* 'event_id' => 1,
* 'event_name' => "Event One",
* 'attendee_id' => 2
* 'attendee_first_name' => "Jane",
* 'attendee_last_name' => "Doe",
* ),
* array(
* 'event_id' => 2,
* 'event_name' => "Event Two",
* 'attendee_id' => 1
* 'attendee_first_name' => "John",
* 'attendee_last_name' => "Doe",
* ),
* array(
* 'event_id' => 1,
* 'event_name' => "Event One",
* 'attendee_id' => 1
* 'attendee_first_name' => "John",
* 'attendee_last_name' => "Doe",
* ),
* )
*
* @param $structure array Structure to impose upon the data.
*
* array(
* 'Event' => array(
* '__key' => 'event_id',
* 'event_id'
* 'event_name',
* 'Attendees' => array(
* '__key' => 'attendee_id',
* 'attendee_id',
* 'attendee_first_name',
* 'attendee_last_name',
* )
* )
* )
*
* @return array
*
*
*/
static function map( $rows, $structure ) {
$rows = (array) $rows;
$groupedByKey = [];
foreach ( $structure as $entity => $properties ) {
if ( ! isset( $properties['__key'] ) ) {
return [];
}
$primary_key = $properties['__key'];
unset( $properties['__key'] );
$keepers = [];
$children = [];
foreach ( $properties as $propertyIdx => $property ) {
if( is_array($property) ) {
$children[ $propertyIdx ] = $property;
} else {
$keepers[] = $property;
}
}
foreach ( $rows as $row_id => $rowObj ) {
$row = (array) $rowObj;
$currentKey = $row[ $primary_key ];
if ( isset( $groupedByKey[ $entity ][ $currentKey ] ) ) {
continue;
}
$preparedRow = self::pluck( $row, $keepers );
$subRows = array_filter($rows, function($_row) use ($primary_key, $currentKey) {
return $_row->{$primary_key} === $currentKey;
});
foreach ( $children as $childEntity => $childProperties ) {
$childStructure = array(
$childEntity => $childProperties,
);
$preparedRow += self::map( $subRows, $childStructure );
}
$groupedByKey[ $entity ][ $currentKey ] = $preparedRow ;
}
}
return $groupedByKey;
}
}<file_sep>/events-manager-seats.php
<?php
/*
Plugin Name: Events Manager Seats
Plugin URI: https://tedxcheyenne.org
Description: Extends the Events Manager plugin to allow users to assign their seats to users.
Version: 1.0.0
Author: <NAME>
Author URI: https://bradkovach.com
Text Domain: em_seats
*/
require 'classes/SimpleOrm.class.php';
/**
* Class EventsManagerSeats
*/
class EventsManagerSeats
{
var $messages = [];
public function __construct()
{
if (file_exists(WP_PLUGIN_DIR . '/events-manager/events-manager.php')) {
// This will listen to the `em_booking_set_status` event and create seats whenever a booking is approved
add_filter('em_booking_set_status', array($this, 'em_booking_set_status'), 10, 2);
// em_seats can be placed on a page to show the users their bookings and allow them to configure their seats.
add_shortcode('em_seats', array($this, 'em_seats_shortcode'));
// maybe_update_seats validates that incoming data is from a valid, nonced form
add_action('init', array($this, 'maybe_update_seats'));
// Styles for rendering the Seat tickets.
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
} else {
add_action('admin_notices', array($this, 'em_is_required_admin_notice'));
}
}
public function enqueue_scripts()
{
wp_enqueue_style('em_seats_styles', plugin_dir_url(__FILE__) . 'assets/style.css');
}
public function em_is_required_admin_notice()
{
$class = 'notice notice-error';
$message = __('Please activate the Events Manager plugin to use Events Manager Seats', 'em_seats');
printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr($class), esc_html($message));
}
/**
* Analyzes incoming data to check for a situation where seats should be updated.
*/
public function maybe_update_seats()
{
if (
isset($_POST['em_seats'])
&& wp_verify_nonce($_POST['_wpnonce'], 'em_update_seats')
) {
foreach ($_POST['em_seats'] as $seat) {
$this->update_seat($seat);
}
}
}
/**
* @param $old_status
* @param $booking EM_Booking Booking to process seats for.
*/
public function em_booking_set_status($old_status, $booking)
{
/*
* $this->status_array = array(
0 => __('Pending','events-manager'),
1 => __('Approved','events-manager'),
2 => __('Rejected','events-manager'),
3 => __('Cancelled','events-manager'),
4 => __('Awaiting Online Payment','events-manager'),
5 => __('Awaiting Payment','events-manager')
);
*/
switch ($booking->booking_status) {
case 1: // Approved
$this->create_seats($booking);
break;
default:
$this->delete_seats($booking);
break;
}
}
/**
* Updates a seat as long as the user owns it.
* @param $seat array Array filled with Seat parameters
* @return bool|false|int
*/
public function update_seat($seat)
{
global $wpdb;
$user = wp_get_current_user();
if (!($user instanceof WP_User))
die('Unable to update seat');
if (!is_email($seat['email'])) {
$this->messages[] = __("Please enter valid email addresses", 'em_seats');
return false;
}
$query = $wpdb->prepare(
"
UPDATE `" . $this->table_name('em_seats') . "` Seat
JOIN `" . $this->table_name('em_tickets_bookings') . "` TicketsBookings on Seat.ticket_booking_id = TicketsBookings.ticket_booking_id
JOIN `" . $this->table_name('em_bookings') . "` Booking on TicketsBookings.booking_id = Booking.booking_id
JOIN `" . $this->table_name('users') . "` User on Booking.person_id = User.id
SET
Seat.first_name = %s,
Seat.last_name = %s,
Seat.email = %s
WHERE User.id = %d
AND Seat.seat_id = %d
",
$seat['first_name'],
$seat['last_name'],
$seat['email'],
$user->ID,
$seat['seat_id']
);
return $wpdb->query($query);
}
public static function table_name($table_name)
{
global $wpdb;
return $wpdb->prefix . $table_name;
}
/**
* @param $booking EM_Booking The booking to create seats for.
*/
public function create_seats($booking)
{
global $wpdb;
$query_rows = array();
foreach ($booking->tickets_bookings->tickets_bookings as $ticket_id => $ticket_booking) {
for ($i = 0; $i < $ticket_booking->ticket_booking_spaces; $i++) {
$seat_locator = hash('sha256', sprintf('booking__%d__%d__%d__%d__%s',
$booking->timestamp,
$ticket_id,
$ticket_booking->ticket_booking_id,
$i,
$booking->person->data->user_email
));
$query_rows[] = $wpdb->prepare("(%d, %s, %s, %s, %s)",
$ticket_booking->ticket_booking_id,
$seat_locator,
"",
"",
$booking->person->data->user_email
);
}
}
//
// for ($i = 0; $i < $booking->booking_spaces; $i++) {
// }
$query = "INSERT INTO " . $this->table_name('em_seats') . " (ticket_booking_id, seat_locator, first_name, last_name, email)";
if (count($query_rows) > 0) {
$query = $query . " VALUES " . implode(",", $query_rows);
}
print_r($query);
// $wpdb->query($query);
}
/**
* @param $booking EM_Booking Booking object to delete corresponding seats for.
*/
public function delete_seats($booking)
{
global $wpdb;
foreach ($booking->tickets_bookings->tickets_bookings as $ticket_id => $ticket_booking) {
$wpdb->delete($wpdb->prefix . 'em_seats', array(
'ticket_booking_id' => $ticket_booking->ticket_booking_id,
));
}
}
/**
* Handles the querying of data and rendering of the seat management form.
*/
public function em_seats_shortcode()
{
global $wpdb;
$editable = [];
$viewable = [];
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$editable_query = $wpdb->prepare("
SELECT
User.*,
Booking.*,
TicketsBookings.*,
Ticket.*,
Seat.*,
Evt.*
FROM `" . $this->table_name('users') . "` User
INNER JOIN `" . $this->table_name('em_bookings') . "` Booking on User.id = Booking.person_id
INNER JOIN `" . $this->table_name('em_tickets_bookings') . "` TicketsBookings on Booking.booking_id = TicketsBookings.booking_id
INNER JOIN `" . $this->table_name('em_tickets') . "` Ticket on Ticket.ticket_id = TicketsBookings.ticket_id
INNER JOIN `" . $this->table_name('em_events') . "` Evt on Ticket.event_id = Evt.event_id
INNER JOIN `" . $this->table_name('em_seats') . "` Seat on TicketsBookings.ticket_booking_id = Seat.ticket_booking_id
WHERE User.ID = %d", $current_user->ID);
$viewable_query = $wpdb->prepare("
SELECT Evt.*, Ticket.*, TicketsBookings.*, Booking.*, Seat.*, BookUser.user_email as booked_by_email
FROM `" . $this->table_name('users') . "` User
INNER JOIN `" . $this->table_name('em_seats') . "` Seat on User.user_email = Seat.email
INNER JOIN `" . $this->table_name('em_tickets_bookings') . "` TicketsBookings on Seat.ticket_booking_id = TicketsBookings.ticket_booking_id
INNER JOIN `" . $this->table_name('em_tickets') . "` Ticket on TicketsBookings.ticket_id = Ticket.ticket_id
INNER JOIN `" . $this->table_name('em_bookings') . "` Booking on Booking.booking_id = TicketsBookings.booking_id
INNER JOIN `" . $this->table_name('em_events') . "` Evt on Evt.event_id = Ticket.event_id
INNER JOIN `" . $this->table_name('users') . "` BookUser on Booking.person_id = BookUser.ID
WHERE User.user_email = %s
AND DATE(Evt.event_end_date) >= CURDATE()", $current_user->data->user_email);
$structure_editable = array(
'Events' => array(
'__key' => 'event_id',
'event_id',
'event_slug',
'event_owner',
'event_status',
'event_name',
'event_start_time',
'event_end_time',
'event_all_day',
'event_start_date',
'event_end_date',
'post_content',
'event_rsvp',
'event_rsvp_date',
'event_rsvp_time',
'event_rsvp_spaces',
'event_spaces',
'event_private',
'Tickets' => array(
'__key' => 'ticket_id',
'ticket_id',
'ticket_name',
'ticket_description',
'TicketsBookings' => array(
'__key' => 'ticket_booking_id',
'ticket_booking_id',
'ticket_id',
'booking_id',
'Bookings' => array(
'__key' => 'booking_id',
'booking_id',
'booking_date',
'booking_status',
'booking_spaces',
),
'Seats' => array(
'__key' => 'seat_id',
'seat_id',
'seat_locator',
'first_name',
'last_name',
'email',
),
)
),
),
);
$editable = SimpleOrm::map($wpdb->get_results($editable_query), $structure_editable);
$viewable = $wpdb->get_results($viewable_query);
}
require 'templates/shortcode__em_seats.php';
}
/**
* Logs data if the WordPress installation has WP_DEBUG set and true.
*/
static function log()
{
if (WP_DEBUG) {
$result = array();
foreach (func_get_args() as $idx => $arg) {
$value = $arg;
if (is_object($arg) || is_array($arg)) {
$value = print_r($arg, true);
}
array_push($result, $value);
}
error_log(implode("\t", $result));
}
}
/**
* Performs install procedure for Events Manager.
*/
static function install()
{
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$query = "CREATE TABLE IF NOT EXISTS `" . self::table_name('em_seats') . "` ("
. "`seat_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, "
. "ticket_booking_id INT NOT NULL, "
. "seat_locator CHAR(64) NOT NULL, "
. "first_name VARCHAR(50) NOT NULL, "
. "last_name VARCHAR(50) NOT NULL, "
. "email VARCHAR(255) NOT NULL "
. ") $charset_collate;";
$wpdb->query($query);
}
/**
* Performs deactivation procedure for Events Manager Seats plugin
*/
static function deactivate()
{
self::log("Deactivating Events Manager Seats plugin", __FILE__);
}
/**
* Performs uninstallation procedure for Events Manager Seats plugin
*/
static function uninstall()
{
self::log("Uninstalling Events Manager Seats plugin", __FILE__);
}
}
$EventsManagerSeats = new EventsManagerSeats();
// Creates the Plugin's table
register_activation_hook(__FILE__, array('EventsManagerSeats', 'install'));
// On Deactivate
register_deactivation_hook(__FILE__, array("EventsManagerSeats", 'deactivate'));
// On Uninstall
register_uninstall_hook(__FILE__, array('EventsManagerSeats', 'uninstall'));
<file_sep>/README.md
# Events Manager Seats
This plugin extends the awesome [Events Manager plugin](https://wordpress.org/plugins/events-manager/) by allowing users to manage the seats/spaces associated with their bookings. For example, if a user purchases/reserves two seats, they will be able to assign names and email addresses to those seats.
## Installation
The plugin is far from complete or stable and is a work in progress.
1. Upload the folder to your `wp-content/plugins` directory
2. Activate the plugin
3. Place the `[em_seats]` shortcode on the page where you would like visitors to manage their seats.
## How It Works
The shortcode renders a form that retrieves all of the user's **approved** bookings. The owner of the booking can assign names and email addresses to each seat. The named user will be emailed to create an account. Any seats will be visible to, but not editable by, the named user.<file_sep>/vendor/composer/autoload_static.php
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit19a1e59f06e54f9a77eac4ad0d0be85d {
public static $prefixLengthsPsr4 = array(
'P' => array(
'Picqer\\Barcode\\' => 15,
),
);
public static $prefixDirsPsr4 = array(
'Picqer\\Barcode\\' => array(
0 => __DIR__ . '/..' . '/picqer/php-barcode-generator/src',
),
);
public static function getInitializer( ClassLoader $loader ) {
return \Closure::bind( function () use ( $loader ) {
$loader->prefixLengthsPsr4 = ComposerStaticInit19a1e59f06e54f9a77eac4ad0d0be85d::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit19a1e59f06e54f9a77eac4ad0d0be85d::$prefixDirsPsr4;
}, null, ClassLoader::class );
}
}
<file_sep>/templates/shortcode__em_seats.php
<?php if (is_user_logged_in()): ?>
<h2><?php echo __("Seats You Have Booked", 'em_seats'); ?></h2>
<p>
<?php _e('Here you can modify and delegate access to your guests.', 'em_seats'); ?>
<?php _e('For each of your tickets, specify the attendee\'s name and email address.', 'em_seats'); ?>
<?php _e('We will send them a digital copy of the ticket before the event.', 'em_seats'); ?>
<?php _e('If you modify or cancel your booking, all of your guest information will be lost!', 'em_seats'); ?>
</p>
<?php if (!empty($this->messages)): ?>
<?php foreach ($this->messages as $message): ?>
<p><?php _e($message, 'em_seats'); ?></p>
<?php endforeach; ?>
<?php endif; ?>
<?php if (!empty($editable['Events'])): ?>
<form method="post">
<?php wp_nonce_field('em_update_seats'); ?>
<?php foreach ($editable['Events'] as $event_id => $event): ?>
<h2><?php echo htmlspecialchars($event['event_name']); ?></h2>
<?php echo $event['post_content']; ?>
<?php foreach ($event['Tickets'] as $ticket_id => $ticket): ?>
<h3><?php echo htmlspecialchars($ticket['ticket_name']); ?></h3>
<?php foreach ($ticket['TicketsBookings'] as $ticket_booking_id => $ticket_booking): ?>
<h4><?php
$booking = $ticket_booking['Bookings'][$ticket_booking['booking_id']];
$seatPlural = count($ticket_booking['Seats']) == 1
? "Seat"
: "Seats";
echo sprintf(__("%d %s %s Booked on %s", 'em_seats'),
count($ticket_booking['Seats']),
$ticket['ticket_name'],
$seatPlural,
date('F j, Y', strtotime($booking['booking_date']))); ?></h4>
<table>
<thead>
<tr>
<th><?php _e('Locator', 'em_seats'); ?></th>
<th><?php _e('First Name', 'em_seats'); ?></th>
<th><?php _e('Last Name', 'em_seats'); ?></th>
<th><?php _e('Email Address', 'em_seats'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($ticket_booking['Seats'] as $seat_id => $seat): ?>
<tr>
<td>
<code><?php echo substr($seat['seat_locator'], 0, 10); ?></code>
<input
type="hidden"
name="<?php echo esc_attr("em_seats[" . $seat['seat_id'] . "][seat_id]"); ?>"
value="<?php echo esc_attr($seat['seat_id']); ?>">
</td>
<td><input
type="text"
title="First Name for Seat <?php esc_attr_e( substr($seat['seat_locator'], 0, 10)) ?>"
name="<?php echo esc_attr("em_seats[" . $seat['seat_id'] . "][first_name]"); ?>"
value="<?php echo esc_attr($seat['first_name']); ?>">
</td>
<td><input
type="text"
title="Last Name for Seat <?php esc_attr_e( substr($seat['seat_locator'], 0, 10)) ?>"
name="<?php echo esc_attr("em_seats[" . $seat['seat_id'] . "][last_name]"); ?>"
value="<?php echo esc_attr($seat['last_name']); ?>">
</td>
<td><input
type="email"
title="Email for <?php esc_attr_e( substr($seat['seat_locator'], 0, 10)) ?>"
name="<?php echo esc_attr("em_seats[" . $seat['seat_id'] . "][email]"); ?>"
value="<?php echo esc_attr($seat['email']); ?>">
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p>
<button type="submit"><?php _e('Save Seat Assignments', 'em_seats'); ?></button>
</p>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endforeach; ?>
</form>
<?php else: ?>
<p><em>
<?php _e('You have not booked any seats at this time.', 'em_seats'); ?>
<?php _e('If you feel this is incorrect, contact us immediately.', 'em_seats') ?></em>
</p>
<?php endif; ?>
<h2><?php echo __("Seats Booked For You", 'em_seats'); ?></h2>
<p>
<?php _e('Here you can see tickets that have been purchased on your behalf.', 'em_seats'); ?>
<?php _e('You can print the ticket if you would like.', 'em_seats'); ?></p>
<?php if ( !empty($viewable) ) : ?>
<section class="seats">
<?php
require dirname(dirname(__FILE__)) . '/vendor/autoload.php';
$generator = new \Picqer\Barcode\BarcodeGeneratorPNG();
?>
<?php foreach ($viewable as $ticket) : ?>
<?php
$ticket = (array)$ticket;
$start_dt = new DateTime($ticket['event_start_date'] . " " . $ticket['event_start_time']);
$stop_dt = new DateTime($ticket['event_end_date'] . " " . $ticket['event_end_time']);
$df = "F j, Y ";
$tf = "g:s A";
?>
<section class="seat">
<h2>
<?php echo htmlspecialchars( $ticket['event_name'] ); ?><br>
<?php if ("" !== $ticket['first_name'] . $ticket['last_name']) : ?>
<strong><?php echo htmlspecialchars( $ticket['first_name'] ); ?>
<?php echo htmlspecialchars( $ticket['last_name'] ); ?></strong> –
<?php endif; ?> <?php echo htmlspecialchars( $ticket['ticket_name'] ); ?>
</h2>
<p><?php echo $start_dt->format($df . $tf); ?> – <?php echo $stop_dt->format($tf); ?></p>
<p><?php echo '<img src="data:image/png;base64,' . base64_encode($generator->getBarcode(substr($ticket['seat_locator'], 0, 10), $generator::TYPE_CODE_128)) . '">'; ?></p>
<table>
<tr>
<th><?php _e('Record Locator', 'em_seats'); ?></th>
<td><code><?php echo substr($ticket['seat_locator'], 0, 10); ?></code></td>
</tr>
<tr>
<th><?php _e('Booked By', 'em_seats'); ?></th>
<td><code><?php echo htmlspecialchars( $ticket['booked_by_email'] ); ?></code></td>
</tr>
</table>
</section>
<?php endforeach; ?>
</section>
<?php else: ?>
<p>
<?php _e('There are currently no tickets booked for you.', 'em_seats'); ?>
<?php _e('If you\'re trying to print tickets that you booked, set the seat email address to your email address.', 'em_seats'); ?>
</p>
<?php endif; ?>
<?php else: ?>
<p><?php
printf(
__('Please <a href="%s">login</a> to manage your bookings and seats.', 'em_seats'),
wp_login_url( get_permalink() )
);
?></p>
<?php endif; ?>
| 9db11ea8ff526e98b41442f895e92dbeac3c8618 | [
"Markdown",
"PHP"
] | 6 | Markdown | biletnam/events-manager-seats | 93ce807e30839471dfc0a76c7387207e33c02300 | 988102aa763cc6bdeb74d11d04ca716cc3aa41bc |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public static string SetValueForText1 = "";
public static string SetValueForText2 = "";
//public static string SetValueForText3 = "";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HRVLV6S\\sqlexpress;Initial Catalog=DESKTOP-HRVLV6S;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
this.Hide();
f2.Show();
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
this.Hide();
f2.Show();
}
private void uuyuuToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
this.Hide();
f2.Show();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
this.Hide();
f2.Show();
}
private void label4_Click_1(object sender, EventArgs e)
{
Form3 f3 = new Form3();
this.Hide();
f3.Show();
}
private void label3_Click(object sender, EventArgs e)
{
Form4 f4 = new Form4();
this.Hide();
f4.Show();
}
private void button2_Click(object sender, EventArgs e)
{
con.Open();
try
{
SqlCommand cmd = new SqlCommand("select * from student where email='" + textBox1.Text + "'and Password='" + textBox2.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows)
{
SetValueForText1 = textBox1.Text;
SetValueForText2 = textBox2.Text;
//SetValueForText3 = dr.GetValue(1).ToString();
MessageBox.Show("Log in Successful", "Logged In", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Form8 f8 = new Form8();
this.Hide();
f8.Show();
}
else
{
MessageBox.Show("please enter valid information: ", "LogIn", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message,"LogIn",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
con.Close();
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp3
{
public partial class Form3 : Form
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HRVLV6S\\sqlexpress;Initial Catalog=DESKTOP-HRVLV6S;Integrated Security=True");
public Form3()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form1 f = new Form1();
this.Hide();
f.Show();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
try
{
SqlCommand cmd = new SqlCommand("insert into Student(email,name,DOB,Password) values(@email,@name,@DOB,@Password)", con);
cmd.Parameters.AddWithValue("@email", textBox1.Text.Trim());
cmd.Parameters.AddWithValue("@name", textBox2.Text.Trim());
cmd.Parameters.AddWithValue("@DOB", textBox4.Text.Trim());
cmd.Parameters.AddWithValue("@Password", textBox3.Text.Trim());
SqlDataReader dr = cmd.ExecuteReader();
MessageBox.Show("registration successful", "Equestion", MessageBoxButtons.OKCancel);
}catch(Exception ex)
{
MessageBox.Show(ex.Message, "Equestion");
}
con.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form8 : Form
{
//public static string SetValueForText3 = "";
public Form8()
{
InitializeComponent();
}
private void changeYourPasswordToolStripMenuItem_Click(object sender, EventArgs e)
{
//SetValueForText3 = label3.Text;
Form5 f5 = new Form5();
this.Hide();
f5.Show();
}
private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
this.Hide();
f1.Show();
}
private void button1_Click(object sender, EventArgs e)
{
Form6 f6 = new Form6();
this.Hide();
f6.Show();
}
private void button3_Click(object sender, EventArgs e)
{
Form7 f7 = new Form7();
this.Hide();
f7.Show();
}
private void button2_Click(object sender, EventArgs e)
{
Form1 f = new Form1();
this.Hide();
f.Show();
}
private void logOutToolStripMenuItem1_Click(object sender, EventArgs e)
{
Form1 f = new Form1();
this.Hide();
f.Show();
}
private void Form8_Load(object sender, EventArgs e)
{
// label4.Text = Form1.SetValueForText3;
label3.Text = Form1.SetValueForText2;
label1.Text = Form1.SetValueForText1;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp3
{
//public int i = 2;
public partial class Form7 : Form
{
int i = 2;
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HRVLV6S\\sqlexpress;Initial Catalog=DESKTOP-HRVLV6S;Integrated Security=True");
public Form7()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form8 f8 = new Form8();
this.Hide();
f8.Show();
}
private void button2_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into Request(Req_ID,University_name) values (@Req_ID,@University_name)",con);
cmd.Parameters.AddWithValue("@Req_ID", i);
i++;
cmd.Parameters.AddWithValue("@University_name", textBox1.Text.Trim());
SqlDataReader dr = cmd.ExecuteReader();
MessageBox.Show("Requested,You will be notified Soon", "Equestion", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp3
{
public partial class Form5 : Form
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HRVLV6S\\sqlexpress;Initial Catalog=DESKTOP-HRVLV6S;Integrated Security=True");
public Form5()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form8 f8 = new Form8();
this.Hide();
f8.Show();
}
private void button2_Click(object sender, EventArgs e)
{
// textBox3.Text = Form1.SetValueForText2;
if (textBox1.Text.Equals(Form1.SetValueForText2))
{
if (textBox2.Text.Equals(textBox3.Text))
{
con.Open();
SqlCommand cmd = new SqlCommand("update Student set Password='" + textBox3.Text + "' where email='" + label4.Text + "'", con);
cmd.ExecuteReader();
MessageBox.Show("Password Updated", "Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Form1 f = new Form1();
this.Hide();
f.Show();
}
else
{
MessageBox.Show("New Password Does not match", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Entered Wrong Password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void Form5_Load(object sender, EventArgs e)
{
label4.Text = Form1.SetValueForText1;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;
namespace WindowsFormsApp3
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f = new Form1();
this.Hide();
f.Show();
}
private void button2_Click(object sender, EventArgs e)
{
string email = "";
string Password = "";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HRVLV6S\\sqlexpress;Initial Catalog=DESKTOP-HRVLV6S;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select email,Password from Student where email=@email", con);
cmd.Parameters.AddWithValue("email", textBox1.Text);
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.Read())
{
email = sdr["email"].ToString();
Password = sdr["Password"].ToString();
}
else
{
MessageBox.Show("Incorrect Email ID", "Forgot Password", MessageBoxButtons.OK);
}
}
con.Close();
if (!string.IsNullOrEmpty(Password))
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("<EMAIL>");
msg.To.Add(textBox1.Text);
msg.Subject = " Recover your Password";
msg.Body = ("Your Username is:" + email + "<br/><br/>" + "Your Password is:" + Password);
msg.IsBodyHtml = true;
SmtpClient smt = new SmtpClient();
smt.Host = "smtp.gmail.com";
System.Net.NetworkCredential ntwd = new NetworkCredential();
ntwd.UserName = "<EMAIL>";
ntwd.Password = "SOU@143mitra";
smt.UseDefaultCredentials = true;
smt.Credentials = <PASSWORD>;
smt.Port = 587;
smt.EnableSsl = true;
smt.Send(msg);
string msgs = "Username and Password Sent Successfully";
MessageBox.Show(msgs, "Forgot Password",MessageBoxButtons.OK);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}
private void Form6_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Form8 f8 = new Form8();
this.Hide();
f8.Show();
}
private void label6_Click(object sender, EventArgs e)
{
Form7 f7 = new Form7();
this.Hide();
f7.Show();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
this.Hide();
f2.Show();
}
}
}
| 82f297eb3f31baaddbc737a14680bba3e9a8b0cb | [
"C#"
] | 7 | C# | SOUMITRA-GTHB/Equestion | e42630138fb48d12fd9da01a35f379eb1f1d305d | 210dff9c86592add3e576c1358815ee2ea6cc53c |
refs/heads/master | <file_sep># AuthenticationApi
All URIs are relative to *http://localhost/api*
Method | HTTP request | Description
------------- | ------------- | -------------
[**authGet**](AuthenticationApi.md#authGet) | **GET** /auth | Authenticate a user by giving an Authorization Grant.
[**profileGet**](AuthenticationApi.md#profileGet) | **GET** /profile | Returns the user's profile
<a name="authGet"></a>
# **authGet**
> Object authGet(grant)
Authenticate a user by giving an Authorization Grant.
### Example
```java
// Import classes:
//import io.swagger.client.ApiException;
//import io.swagger.client.api.AuthenticationApi;
AuthenticationApi apiInstance = new AuthenticationApi();
String grant = "grant_example"; // String |
try {
Object result = apiInstance.authGet(grant);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AuthenticationApi#authGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**grant** | **String**| |
### Return type
**Object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="profileGet"></a>
# **profileGet**
> Object profileGet()
Returns the user's profile
### Example
```java
// Import classes:
//import io.swagger.client.ApiException;
//import io.swagger.client.api.AuthenticationApi;
AuthenticationApi apiInstance = new AuthenticationApi();
try {
Object result = apiInstance.profileGet();
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AuthenticationApi#profileGet");
e.printStackTrace();
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
**Object**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<file_sep>
# CreateSubSystemPermissionDto
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**user** | **Object** | |
**subsystem** | **Object** | |
**isMember** | **Boolean** | If the user is a member. |
**editEorReason** | **Boolean** | Reason for the end of run. |
**subSystemHash** | **String** | A unique token for a subsystem linked to a user. |
**subSystemTokenDescription** | **String** | A description for the subsystem. |
<file_sep>/*
* Jiskefet
* Running with /api prefix
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* CreateAttachmentDto
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-03-08T11:03:08.533Z")
public class CreateAttachmentDto {
@SerializedName("title")
private String title = null;
@SerializedName("fileMime")
private String fileMime = null;
@SerializedName("fileData")
private String fileData = null;
@SerializedName("logId")
private Integer logId = null;
public CreateAttachmentDto title(String title) {
this.title = title;
return this;
}
/**
* What kind of log is it?
* @return title
**/
@ApiModelProperty(example = "run", required = true, value = "What kind of log is it?")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public CreateAttachmentDto fileMime(String fileMime) {
this.fileMime = fileMime;
return this;
}
/**
* What kind of log is it?
* @return fileMime
**/
@ApiModelProperty(example = "run", required = true, value = "What kind of log is it?")
public String getFileMime() {
return fileMime;
}
public void setFileMime(String fileMime) {
this.fileMime = fileMime;
}
public CreateAttachmentDto fileData(String fileData) {
this.fileData = fileData;
return this;
}
/**
* What kind of log is it?
* @return fileData
**/
@ApiModelProperty(example = "23144132412314344", required = true, value = "What kind of log is it?")
public String getFileData() {
return fileData;
}
public void setFileData(String fileData) {
this.fileData = fileData;
}
public CreateAttachmentDto logId(Integer logId) {
this.logId = logId;
return this;
}
/**
* The id of the corresponding Log
* @return logId
**/
@ApiModelProperty(example = "1", required = true, value = "The id of the corresponding Log")
public Integer getLogId() {
return logId;
}
public void setLogId(Integer logId) {
this.logId = logId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CreateAttachmentDto createAttachmentDto = (CreateAttachmentDto) o;
return Objects.equals(this.title, createAttachmentDto.title) &&
Objects.equals(this.fileMime, createAttachmentDto.fileMime) &&
Objects.equals(this.fileData, createAttachmentDto.fileData) &&
Objects.equals(this.logId, createAttachmentDto.logId);
}
@Override
public int hashCode() {
return Objects.hash(title, fileMime, fileData, logId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CreateAttachmentDto {\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" fileMime: ").append(toIndentedString(fileMime)).append("\n");
sb.append(" fileData: ").append(toIndentedString(fileData)).append("\n");
sb.append(" logId: ").append(toIndentedString(logId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep># AttachmentsApi
All URIs are relative to *http://localhost/api*
Method | HTTP request | Description
------------- | ------------- | -------------
[**attachmentsIdLogsGet**](AttachmentsApi.md#attachmentsIdLogsGet) | **GET** /attachments/{id}/logs |
[**attachmentsPost**](AttachmentsApi.md#attachmentsPost) | **POST** /attachments |
<a name="attachmentsIdLogsGet"></a>
# **attachmentsIdLogsGet**
> Object attachmentsIdLogsGet(id)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.AttachmentsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
AttachmentsApi apiInstance = new AttachmentsApi();
Integer id = 56; // Integer |
try {
Object result = apiInstance.attachmentsIdLogsGet(id);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#attachmentsIdLogsGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **Integer**| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="attachmentsPost"></a>
# **attachmentsPost**
> attachmentsPost(createAttachmentDto)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.AttachmentsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
AttachmentsApi apiInstance = new AttachmentsApi();
CreateAttachmentDto createAttachmentDto = new CreateAttachmentDto(); // CreateAttachmentDto |
try {
apiInstance.attachmentsPost(createAttachmentDto);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#attachmentsPost");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createAttachmentDto** | [**CreateAttachmentDto**](CreateAttachmentDto.md)| |
### Return type
null (empty response body)
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<file_sep>
# CreateLogDto
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**subtype** | [**SubtypeEnum**](#SubtypeEnum) | What kind of log is it? |
**origin** | [**OriginEnum**](#OriginEnum) | Where did the log come from? |
**title** | **String** | describes the log in short |
**text** | **String** | describes the log in depth |
**attachments** | **List<String>** | Attachments of this log |
**runs** | **List<String>** | Attached run numbers of this log |
<a name="SubtypeEnum"></a>
## Enum: SubtypeEnum
Name | Value
---- | -----
RUN | "run"
SUBSYSTEM | "subsystem"
ANNOUNCEMENT | "announcement"
INTERVENTION | "intervention"
COMMENT | "comment"
<a name="OriginEnum"></a>
## Enum: OriginEnum
Name | Value
---- | -----
HUMAN | "human"
PROCESS | "process"
<file_sep>
# CreateRunResultDto
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**timeO2Start** | [**OffsetDateTime**](OffsetDateTime.md) | |
**timeTrgStart** | [**OffsetDateTime**](OffsetDateTime.md) | |
**timeO2End** | [**OffsetDateTime**](OffsetDateTime.md) | |
**timeTrgEnd** | [**OffsetDateTime**](OffsetDateTime.md) | |
**runType** | **String** | What kind of run. |
**runQuality** | **String** | The quality of the run. |
**activityId** | **String** | The id of the activity. |
**nDetectors** | **Integer** | Number of detectors during run. |
**nFlps** | **Integer** | Number of FLPs that computed data |
**nEpns** | **Integer** | Number of EPNs that stored data |
**nTimeframes** | **Integer** | Number of timeframes |
**nSubtimeframes** | **Integer** | Number of subtimeframes |
**bytesReadOut** | **Integer** | Amount of bytes read out |
**bytesTimeframeBuilder** | **Integer** | What builder was used. |
**runNumber** | **Integer** | The run number. | [optional]
<file_sep># OverviewApi
All URIs are relative to *http://localhost/api*
Method | HTTP request | Description
------------- | ------------- | -------------
[**overviewGet**](OverviewApi.md#overviewGet) | **GET** /overview |
<a name="overviewGet"></a>
# **overviewGet**
> Object overviewGet(timeRange)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.OverviewApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
OverviewApi apiInstance = new OverviewApi();
String timeRange = "timeRange_example"; // String | In which time range the logs of eachsubsystem should be posted
try {
Object result = apiInstance.overviewGet(timeRange);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling OverviewApi#overviewGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**timeRange** | **String**| In which time range the logs of eachsubsystem should be posted | [optional]
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<file_sep># swagger-java-client
Jiskefet
- API version: 1.0
- Build date: 2019-03-08T11:03:08.533Z
Running with /api prefix
*Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen)*
## Requirements
Building the API client library requires:
1. Java 1.7+
2. Maven/Gradle
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn clean install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn clean deploy
```
Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information.
### Maven users
Add this dependency to your project's POM:
```xml
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-java-client</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
```
### Gradle users
Add this dependency to your project's build file:
```groovy
compile "io.swagger:swagger-java-client:1.0.0"
```
### Others
At first generate the JAR by executing:
```shell
mvn clean package
```
Then manually install the following JARs:
* `target/swagger-java-client-1.0.0.jar`
* `target/lib/*.jar`
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
```java
import io.swagger.client.*;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
import io.swagger.client.api.AttachmentsApi;
import java.io.File;
import java.util.*;
public class AttachmentsApiExample {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
AttachmentsApi apiInstance = new AttachmentsApi();
Integer id = 56; // Integer |
try {
Object result = apiInstance.attachmentsIdLogsGet(id);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling AttachmentsApi#attachmentsIdLogsGet");
e.printStackTrace();
}
}
}
```
## Documentation for API Endpoints
All URIs are relative to *http://localhost/api*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*AttachmentsApi* | [**attachmentsIdLogsGet**](docs/AttachmentsApi.md#attachmentsIdLogsGet) | **GET** /attachments/{id}/logs |
*AttachmentsApi* | [**attachmentsPost**](docs/AttachmentsApi.md#attachmentsPost) | **POST** /attachments |
*AuthenticationApi* | [**authGet**](docs/AuthenticationApi.md#authGet) | **GET** /auth | Authenticate a user by giving an Authorization Grant.
*AuthenticationApi* | [**profileGet**](docs/AuthenticationApi.md#profileGet) | **GET** /profile | Returns the user's profile
*LogsApi* | [**logsGet**](docs/LogsApi.md#logsGet) | **GET** /logs |
*LogsApi* | [**logsIdGet**](docs/LogsApi.md#logsIdGet) | **GET** /logs/{id} |
*LogsApi* | [**logsIdRunsPatch**](docs/LogsApi.md#logsIdRunsPatch) | **PATCH** /logs/{id}/runs |
*LogsApi* | [**logsPost**](docs/LogsApi.md#logsPost) | **POST** /logs |
*OverviewApi* | [**overviewGet**](docs/OverviewApi.md#overviewGet) | **GET** /overview |
*RunsApi* | [**runsGet**](docs/RunsApi.md#runsGet) | **GET** /runs |
*RunsApi* | [**runsIdGet**](docs/RunsApi.md#runsIdGet) | **GET** /runs/{id} |
*RunsApi* | [**runsIdLogsPatch**](docs/RunsApi.md#runsIdLogsPatch) | **PATCH** /runs/{id}/logs |
*RunsApi* | [**runsPost**](docs/RunsApi.md#runsPost) | **POST** /runs |
*SubsystemsApi* | [**subsystemsGet**](docs/SubsystemsApi.md#subsystemsGet) | **GET** /subsystems |
*SubsystemsApi* | [**subsystemsIdGet**](docs/SubsystemsApi.md#subsystemsIdGet) | **GET** /subsystems/{id} |
*UsersApi* | [**usersIdGet**](docs/UsersApi.md#usersIdGet) | **GET** /users/{id} |
*UsersApi* | [**usersIdTokensGet**](docs/UsersApi.md#usersIdTokensGet) | **GET** /users/{id}/tokens |
*UsersApi* | [**usersIdTokensNewPost**](docs/UsersApi.md#usersIdTokensNewPost) | **POST** /users/{id}/tokens/new |
## Documentation for Models
- [CreateAttachmentDto](docs/CreateAttachmentDto.md)
- [CreateLogDto](docs/CreateLogDto.md)
- [CreateRunDto](docs/CreateRunDto.md)
- [CreateRunResultDto](docs/CreateRunResultDto.md)
- [CreateSubSystemPermissionDto](docs/CreateSubSystemPermissionDto.md)
- [LinkLogToRunDto](docs/LinkLogToRunDto.md)
- [LinkRunToLogDto](docs/LinkRunToLogDto.md)
## Documentation for Authorization
Authentication schemes defined for the API:
### bearer
- **Type**: API key
- **API key parameter name**: Authorization
- **Location**: HTTP header
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
## Author
<file_sep>
# CreateAttachmentDto
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**title** | **String** | What kind of log is it? |
**fileMime** | **String** | What kind of log is it? |
**fileData** | **String** | What kind of log is it? |
**logId** | **Integer** | The id of the corresponding Log |
<file_sep># SubsystemsApi
All URIs are relative to *http://localhost/api*
Method | HTTP request | Description
------------- | ------------- | -------------
[**subsystemsGet**](SubsystemsApi.md#subsystemsGet) | **GET** /subsystems |
[**subsystemsIdGet**](SubsystemsApi.md#subsystemsIdGet) | **GET** /subsystems/{id} |
<a name="subsystemsGet"></a>
# **subsystemsGet**
> Object subsystemsGet()
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.SubsystemsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
SubsystemsApi apiInstance = new SubsystemsApi();
try {
Object result = apiInstance.subsystemsGet();
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubsystemsApi#subsystemsGet");
e.printStackTrace();
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="subsystemsIdGet"></a>
# **subsystemsIdGet**
> Object subsystemsIdGet(id)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.SubsystemsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
SubsystemsApi apiInstance = new SubsystemsApi();
Integer id = 56; // Integer |
try {
Object result = apiInstance.subsystemsIdGet(id);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling SubsystemsApi#subsystemsIdGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **Integer**| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<file_sep>/*
* Jiskefet
* Running with /api prefix
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.api;
import io.swagger.client.ApiCallback;
import io.swagger.client.ApiClient;
import io.swagger.client.ApiException;
import io.swagger.client.ApiResponse;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.ProgressRequestBody;
import io.swagger.client.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import io.swagger.client.model.CreateLogDto;
import io.swagger.client.model.LinkRunToLogDto;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LogsApi {
private ApiClient apiClient;
public LogsApi() {
this(Configuration.getDefaultApiClient());
}
public LogsApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Build call for logsGet
* @param orderBy On which field to order on. (optional)
* @param orderDirection The order direction, either ascending or descending. (optional)
* @param pageSize The maximum amount of logs in each result. (optional, default to 25)
* @param pageNumber The current page, i.e. the offset in the result set based on pageSize. (optional, default to 1)
* @param logId The id of the log. (optional)
* @param searchterm Search for a term that exists in the title field of a log. (optional)
* @param subtype The subtype of the log. (optional)
* @param origin The origin/creator of the log. (optional)
* @param startCreationTime The lower bound of the creation time filter range. (optional)
* @param endCreationTime The upper bound of the creation time filter range. (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call logsGetCall(String orderBy, String orderDirection, String pageSize, String pageNumber, String logId, String searchterm, String subtype, String origin, String startCreationTime, String endCreationTime, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/logs";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (orderBy != null)
localVarQueryParams.addAll(apiClient.parameterToPair("orderBy", orderBy));
if (orderDirection != null)
localVarQueryParams.addAll(apiClient.parameterToPair("orderDirection", orderDirection));
if (pageSize != null)
localVarQueryParams.addAll(apiClient.parameterToPair("pageSize", pageSize));
if (pageNumber != null)
localVarQueryParams.addAll(apiClient.parameterToPair("pageNumber", pageNumber));
if (logId != null)
localVarQueryParams.addAll(apiClient.parameterToPair("logId", logId));
if (searchterm != null)
localVarQueryParams.addAll(apiClient.parameterToPair("searchterm", searchterm));
if (subtype != null)
localVarQueryParams.addAll(apiClient.parameterToPair("subtype", subtype));
if (origin != null)
localVarQueryParams.addAll(apiClient.parameterToPair("origin", origin));
if (startCreationTime != null)
localVarQueryParams.addAll(apiClient.parameterToPair("startCreationTime", startCreationTime));
if (endCreationTime != null)
localVarQueryParams.addAll(apiClient.parameterToPair("endCreationTime", endCreationTime));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "bearer" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call logsGetValidateBeforeCall(String orderBy, String orderDirection, String pageSize, String pageNumber, String logId, String searchterm, String subtype, String origin, String startCreationTime, String endCreationTime, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
com.squareup.okhttp.Call call = logsGetCall(orderBy, orderDirection, pageSize, pageNumber, logId, searchterm, subtype, origin, startCreationTime, endCreationTime, progressListener, progressRequestListener);
return call;
}
/**
*
*
* @param orderBy On which field to order on. (optional)
* @param orderDirection The order direction, either ascending or descending. (optional)
* @param pageSize The maximum amount of logs in each result. (optional, default to 25)
* @param pageNumber The current page, i.e. the offset in the result set based on pageSize. (optional, default to 1)
* @param logId The id of the log. (optional)
* @param searchterm Search for a term that exists in the title field of a log. (optional)
* @param subtype The subtype of the log. (optional)
* @param origin The origin/creator of the log. (optional)
* @param startCreationTime The lower bound of the creation time filter range. (optional)
* @param endCreationTime The upper bound of the creation time filter range. (optional)
* @return Object
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public Object logsGet(String orderBy, String orderDirection, String pageSize, String pageNumber, String logId, String searchterm, String subtype, String origin, String startCreationTime, String endCreationTime) throws ApiException {
ApiResponse<Object> resp = logsGetWithHttpInfo(orderBy, orderDirection, pageSize, pageNumber, logId, searchterm, subtype, origin, startCreationTime, endCreationTime);
return resp.getData();
}
/**
*
*
* @param orderBy On which field to order on. (optional)
* @param orderDirection The order direction, either ascending or descending. (optional)
* @param pageSize The maximum amount of logs in each result. (optional, default to 25)
* @param pageNumber The current page, i.e. the offset in the result set based on pageSize. (optional, default to 1)
* @param logId The id of the log. (optional)
* @param searchterm Search for a term that exists in the title field of a log. (optional)
* @param subtype The subtype of the log. (optional)
* @param origin The origin/creator of the log. (optional)
* @param startCreationTime The lower bound of the creation time filter range. (optional)
* @param endCreationTime The upper bound of the creation time filter range. (optional)
* @return ApiResponse<Object>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Object> logsGetWithHttpInfo(String orderBy, String orderDirection, String pageSize, String pageNumber, String logId, String searchterm, String subtype, String origin, String startCreationTime, String endCreationTime) throws ApiException {
com.squareup.okhttp.Call call = logsGetValidateBeforeCall(orderBy, orderDirection, pageSize, pageNumber, logId, searchterm, subtype, origin, startCreationTime, endCreationTime, null, null);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* (asynchronously)
*
* @param orderBy On which field to order on. (optional)
* @param orderDirection The order direction, either ascending or descending. (optional)
* @param pageSize The maximum amount of logs in each result. (optional, default to 25)
* @param pageNumber The current page, i.e. the offset in the result set based on pageSize. (optional, default to 1)
* @param logId The id of the log. (optional)
* @param searchterm Search for a term that exists in the title field of a log. (optional)
* @param subtype The subtype of the log. (optional)
* @param origin The origin/creator of the log. (optional)
* @param startCreationTime The lower bound of the creation time filter range. (optional)
* @param endCreationTime The upper bound of the creation time filter range. (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call logsGetAsync(String orderBy, String orderDirection, String pageSize, String pageNumber, String logId, String searchterm, String subtype, String origin, String startCreationTime, String endCreationTime, final ApiCallback<Object> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = logsGetValidateBeforeCall(orderBy, orderDirection, pageSize, pageNumber, logId, searchterm, subtype, origin, startCreationTime, endCreationTime, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for logsIdGet
* @param id (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call logsIdGetCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/logs/{id}"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "bearer" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call logsIdGetValidateBeforeCall(Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling logsIdGet(Async)");
}
com.squareup.okhttp.Call call = logsIdGetCall(id, progressListener, progressRequestListener);
return call;
}
/**
*
*
* @param id (required)
* @return Object
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public Object logsIdGet(Integer id) throws ApiException {
ApiResponse<Object> resp = logsIdGetWithHttpInfo(id);
return resp.getData();
}
/**
*
*
* @param id (required)
* @return ApiResponse<Object>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Object> logsIdGetWithHttpInfo(Integer id) throws ApiException {
com.squareup.okhttp.Call call = logsIdGetValidateBeforeCall(id, null, null);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* (asynchronously)
*
* @param id (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call logsIdGetAsync(Integer id, final ApiCallback<Object> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = logsIdGetValidateBeforeCall(id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for logsIdRunsPatch
* @param linkRunToLogDto (required)
* @param id (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call logsIdRunsPatchCall(LinkRunToLogDto linkRunToLogDto, Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = linkRunToLogDto;
// create path and map variables
String localVarPath = "/logs/{id}/runs"
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "bearer" };
return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call logsIdRunsPatchValidateBeforeCall(LinkRunToLogDto linkRunToLogDto, Integer id, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'linkRunToLogDto' is set
if (linkRunToLogDto == null) {
throw new ApiException("Missing the required parameter 'linkRunToLogDto' when calling logsIdRunsPatch(Async)");
}
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException("Missing the required parameter 'id' when calling logsIdRunsPatch(Async)");
}
com.squareup.okhttp.Call call = logsIdRunsPatchCall(linkRunToLogDto, id, progressListener, progressRequestListener);
return call;
}
/**
*
*
* @param linkRunToLogDto (required)
* @param id (required)
* @return Object
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public Object logsIdRunsPatch(LinkRunToLogDto linkRunToLogDto, Integer id) throws ApiException {
ApiResponse<Object> resp = logsIdRunsPatchWithHttpInfo(linkRunToLogDto, id);
return resp.getData();
}
/**
*
*
* @param linkRunToLogDto (required)
* @param id (required)
* @return ApiResponse<Object>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Object> logsIdRunsPatchWithHttpInfo(LinkRunToLogDto linkRunToLogDto, Integer id) throws ApiException {
com.squareup.okhttp.Call call = logsIdRunsPatchValidateBeforeCall(linkRunToLogDto, id, null, null);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* (asynchronously)
*
* @param linkRunToLogDto (required)
* @param id (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call logsIdRunsPatchAsync(LinkRunToLogDto linkRunToLogDto, Integer id, final ApiCallback<Object> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = logsIdRunsPatchValidateBeforeCall(linkRunToLogDto, id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for logsPost
* @param createLogDto (required)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call logsPostCall(CreateLogDto createLogDto, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = createLogDto;
// create path and map variables
String localVarPath = "/logs";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "bearer" };
return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call logsPostValidateBeforeCall(CreateLogDto createLogDto, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'createLogDto' is set
if (createLogDto == null) {
throw new ApiException("Missing the required parameter 'createLogDto' when calling logsPost(Async)");
}
com.squareup.okhttp.Call call = logsPostCall(createLogDto, progressListener, progressRequestListener);
return call;
}
/**
*
*
* @param createLogDto (required)
* @return Object
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public Object logsPost(CreateLogDto createLogDto) throws ApiException {
ApiResponse<Object> resp = logsPostWithHttpInfo(createLogDto);
return resp.getData();
}
/**
*
*
* @param createLogDto (required)
* @return ApiResponse<Object>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Object> logsPostWithHttpInfo(CreateLogDto createLogDto) throws ApiException {
com.squareup.okhttp.Call call = logsPostValidateBeforeCall(createLogDto, null, null);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* (asynchronously)
*
* @param createLogDto (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call logsPostAsync(CreateLogDto createLogDto, final ApiCallback<Object> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = logsPostValidateBeforeCall(createLogDto, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<Object>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
}
<file_sep>/*
* Jiskefet
* Running with /api prefix
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.api;
import io.swagger.client.ApiException;
import io.swagger.client.model.CreateSubSystemPermissionDto;
import org.junit.Test;
import org.junit.Ignore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for UsersApi
*/
@Ignore
public class UsersApiTest {
private final UsersApi api = new UsersApi();
/**
*
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void usersIdGetTest() throws ApiException {
Integer id = null;
Object response = api.usersIdGet(id);
// TODO: test validations
}
/**
*
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void usersIdTokensGetTest() throws ApiException {
Integer id = null;
Object response = api.usersIdTokensGet(id);
// TODO: test validations
}
/**
*
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void usersIdTokensNewPostTest() throws ApiException {
Integer id = null;
CreateSubSystemPermissionDto createSubSystemPermissionDto = null;
api.usersIdTokensNewPost(id, createSubSystemPermissionDto);
// TODO: test validations
}
}
<file_sep>/*
* Jiskefet
* Running with /api prefix
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.api;
import io.swagger.client.ApiException;
import org.junit.Test;
import org.junit.Ignore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for SubsystemsApi
*/
@Ignore
public class SubsystemsApiTest {
private final SubsystemsApi api = new SubsystemsApi();
/**
*
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void subsystemsGetTest() throws ApiException {
Object response = api.subsystemsGet();
// TODO: test validations
}
/**
*
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void subsystemsIdGetTest() throws ApiException {
Integer id = null;
Object response = api.subsystemsIdGet(id);
// TODO: test validations
}
}
<file_sep>
# LinkLogToRunDto
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**logId** | **Integer** | The id of the log to link to the run. |
<file_sep># LogsApi
All URIs are relative to *http://localhost/api*
Method | HTTP request | Description
------------- | ------------- | -------------
[**logsGet**](LogsApi.md#logsGet) | **GET** /logs |
[**logsIdGet**](LogsApi.md#logsIdGet) | **GET** /logs/{id} |
[**logsIdRunsPatch**](LogsApi.md#logsIdRunsPatch) | **PATCH** /logs/{id}/runs |
[**logsPost**](LogsApi.md#logsPost) | **POST** /logs |
<a name="logsGet"></a>
# **logsGet**
> Object logsGet(orderBy, orderDirection, pageSize, pageNumber, logId, searchterm, subtype, origin, startCreationTime, endCreationTime)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.LogsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
LogsApi apiInstance = new LogsApi();
String orderBy = "orderBy_example"; // String | On which field to order on.
String orderDirection = "orderDirection_example"; // String | The order direction, either ascending or descending.
String pageSize = "25"; // String | The maximum amount of logs in each result.
String pageNumber = "1"; // String | The current page, i.e. the offset in the result set based on pageSize.
String logId = "logId_example"; // String | The id of the log.
String searchterm = "searchterm_example"; // String | Search for a term that exists in the title field of a log.
String subtype = "subtype_example"; // String | The subtype of the log.
String origin = "origin_example"; // String | The origin/creator of the log.
String startCreationTime = "startCreationTime_example"; // String | The lower bound of the creation time filter range.
String endCreationTime = "endCreationTime_example"; // String | The upper bound of the creation time filter range.
try {
Object result = apiInstance.logsGet(orderBy, orderDirection, pageSize, pageNumber, logId, searchterm, subtype, origin, startCreationTime, endCreationTime);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling LogsApi#logsGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderBy** | **String**| On which field to order on. | [optional]
**orderDirection** | **String**| The order direction, either ascending or descending. | [optional] [enum: ASC, DESC]
**pageSize** | **String**| The maximum amount of logs in each result. | [optional] [default to 25]
**pageNumber** | **String**| The current page, i.e. the offset in the result set based on pageSize. | [optional] [default to 1]
**logId** | **String**| The id of the log. | [optional]
**searchterm** | **String**| Search for a term that exists in the title field of a log. | [optional]
**subtype** | **String**| The subtype of the log. | [optional] [enum: run, subsystem, announcement, intervention, comment]
**origin** | **String**| The origin/creator of the log. | [optional] [enum: human, process]
**startCreationTime** | **String**| The lower bound of the creation time filter range. | [optional]
**endCreationTime** | **String**| The upper bound of the creation time filter range. | [optional]
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="logsIdGet"></a>
# **logsIdGet**
> Object logsIdGet(id)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.LogsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
LogsApi apiInstance = new LogsApi();
Integer id = 56; // Integer |
try {
Object result = apiInstance.logsIdGet(id);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling LogsApi#logsIdGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **Integer**| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="logsIdRunsPatch"></a>
# **logsIdRunsPatch**
> Object logsIdRunsPatch(linkRunToLogDto, id)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.LogsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
LogsApi apiInstance = new LogsApi();
LinkRunToLogDto linkRunToLogDto = new LinkRunToLogDto(); // LinkRunToLogDto |
Integer id = 56; // Integer |
try {
Object result = apiInstance.logsIdRunsPatch(linkRunToLogDto, id);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling LogsApi#logsIdRunsPatch");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**linkRunToLogDto** | [**LinkRunToLogDto**](LinkRunToLogDto.md)| |
**id** | **Integer**| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="logsPost"></a>
# **logsPost**
> Object logsPost(createLogDto)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.LogsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
LogsApi apiInstance = new LogsApi();
CreateLogDto createLogDto = new CreateLogDto(); // CreateLogDto |
try {
Object result = apiInstance.logsPost(createLogDto);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling LogsApi#logsPost");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createLogDto** | [**CreateLogDto**](CreateLogDto.md)| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<file_sep># RunsApi
All URIs are relative to *http://localhost/api*
Method | HTTP request | Description
------------- | ------------- | -------------
[**runsGet**](RunsApi.md#runsGet) | **GET** /runs |
[**runsIdGet**](RunsApi.md#runsIdGet) | **GET** /runs/{id} |
[**runsIdLogsPatch**](RunsApi.md#runsIdLogsPatch) | **PATCH** /runs/{id}/logs |
[**runsPost**](RunsApi.md#runsPost) | **POST** /runs |
<a name="runsGet"></a>
# **runsGet**
> Object runsGet(orderBy, orderDirection, pageSize, pageNumber, runNumber, startTimeO2Start, endTimeO2Start, startTimeTrgStart, endTimeTrgStart, startTimeTrgEnd, endTimeTrgEnd, startTimeO2End, endTimeO2End, activityId, runType, runQuality)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.RunsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
RunsApi apiInstance = new RunsApi();
String orderBy = "orderBy_example"; // String | On which field to order on.
String orderDirection = "orderDirection_example"; // String | The order direction, either ascending or descending.
String pageSize = "25"; // String | The maximum amount of logs in each result.
String pageNumber = "1"; // String | The current page, i.e. the offset in the result set based on pageSize.
String runNumber = "runNumber_example"; // String | The id of the log.
OffsetDateTime startTimeO2Start = OffsetDateTime.now(); // OffsetDateTime | The lower bound of the timeO2Start filter range.
OffsetDateTime endTimeO2Start = OffsetDateTime.now(); // OffsetDateTime | The upper bound of the timeO2Start filter range.
OffsetDateTime startTimeTrgStart = OffsetDateTime.now(); // OffsetDateTime | The lower bound of the timeTrgStart filter range.
OffsetDateTime endTimeTrgStart = OffsetDateTime.now(); // OffsetDateTime | The upper bound of the timeTrgStart filter range.
OffsetDateTime startTimeTrgEnd = OffsetDateTime.now(); // OffsetDateTime | The lower bound of the timeTrgEnd filter range.
OffsetDateTime endTimeTrgEnd = OffsetDateTime.now(); // OffsetDateTime | The upper bound of the timeTrgEnd filter range.
OffsetDateTime startTimeO2End = OffsetDateTime.now(); // OffsetDateTime | The lower bound of the timeO2End filter range.
OffsetDateTime endTimeO2End = OffsetDateTime.now(); // OffsetDateTime | The upper bound of the timeO2End filter range.
String activityId = "activityId_example"; // String | The id of the activity.
Integer runType = 56; // Integer | The type of the run.
Integer runQuality = 56; // Integer | The quality of the run.
try {
Object result = apiInstance.runsGet(orderBy, orderDirection, pageSize, pageNumber, runNumber, startTimeO2Start, endTimeO2Start, startTimeTrgStart, endTimeTrgStart, startTimeTrgEnd, endTimeTrgEnd, startTimeO2End, endTimeO2End, activityId, runType, runQuality);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RunsApi#runsGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderBy** | **String**| On which field to order on. | [optional]
**orderDirection** | **String**| The order direction, either ascending or descending. | [optional] [enum: ASC, DESC]
**pageSize** | **String**| The maximum amount of logs in each result. | [optional] [default to 25]
**pageNumber** | **String**| The current page, i.e. the offset in the result set based on pageSize. | [optional] [default to 1]
**runNumber** | **String**| The id of the log. | [optional]
**startTimeO2Start** | **OffsetDateTime**| The lower bound of the timeO2Start filter range. | [optional]
**endTimeO2Start** | **OffsetDateTime**| The upper bound of the timeO2Start filter range. | [optional]
**startTimeTrgStart** | **OffsetDateTime**| The lower bound of the timeTrgStart filter range. | [optional]
**endTimeTrgStart** | **OffsetDateTime**| The upper bound of the timeTrgStart filter range. | [optional]
**startTimeTrgEnd** | **OffsetDateTime**| The lower bound of the timeTrgEnd filter range. | [optional]
**endTimeTrgEnd** | **OffsetDateTime**| The upper bound of the timeTrgEnd filter range. | [optional]
**startTimeO2End** | **OffsetDateTime**| The lower bound of the timeO2End filter range. | [optional]
**endTimeO2End** | **OffsetDateTime**| The upper bound of the timeO2End filter range. | [optional]
**activityId** | **String**| The id of the activity. | [optional]
**runType** | **Integer**| The type of the run. | [optional]
**runQuality** | **Integer**| The quality of the run. | [optional]
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="runsIdGet"></a>
# **runsIdGet**
> Object runsIdGet(id)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.RunsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
RunsApi apiInstance = new RunsApi();
Integer id = 56; // Integer |
try {
Object result = apiInstance.runsIdGet(id);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RunsApi#runsIdGet");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **Integer**| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="runsIdLogsPatch"></a>
# **runsIdLogsPatch**
> Object runsIdLogsPatch(linkLogToRunDto, id)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.RunsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
RunsApi apiInstance = new RunsApi();
LinkLogToRunDto linkLogToRunDto = new LinkLogToRunDto(); // LinkLogToRunDto |
Integer id = 56; // Integer |
try {
Object result = apiInstance.runsIdLogsPatch(linkLogToRunDto, id);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RunsApi#runsIdLogsPatch");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**linkLogToRunDto** | [**LinkLogToRunDto**](LinkLogToRunDto.md)| |
**id** | **Integer**| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<a name="runsPost"></a>
# **runsPost**
> Object runsPost(createRunDto)
### Example
```java
// Import classes:
//import io.swagger.client.ApiClient;
//import io.swagger.client.ApiException;
//import io.swagger.client.Configuration;
//import io.swagger.client.auth.*;
//import io.swagger.client.api.RunsApi;
ApiClient defaultClient = Configuration.getDefaultApiClient();
// Configure API key authorization: bearer
ApiKeyAuth bearer = (ApiKeyAuth) defaultClient.getAuthentication("bearer");
bearer.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//bearer.setApiKeyPrefix("Token");
RunsApi apiInstance = new RunsApi();
CreateRunDto createRunDto = new CreateRunDto(); // CreateRunDto |
try {
Object result = apiInstance.runsPost(createRunDto);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling RunsApi#runsPost");
e.printStackTrace();
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**createRunDto** | [**CreateRunDto**](CreateRunDto.md)| |
### Return type
**Object**
### Authorization
[bearer](../README.md#bearer)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
<file_sep>/*
* Jiskefet
* Running with /api prefix
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* CreateLogDto
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-03-08T11:03:08.533Z")
public class CreateLogDto {
/**
* What kind of log is it?
*/
@JsonAdapter(SubtypeEnum.Adapter.class)
public enum SubtypeEnum {
RUN("run"),
SUBSYSTEM("subsystem"),
ANNOUNCEMENT("announcement"),
INTERVENTION("intervention"),
COMMENT("comment");
private String value;
SubtypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static SubtypeEnum fromValue(String text) {
for (SubtypeEnum b : SubtypeEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<SubtypeEnum> {
@Override
public void write(final JsonWriter jsonWriter, final SubtypeEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public SubtypeEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return SubtypeEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName("subtype")
private SubtypeEnum subtype = null;
/**
* Where did the log come from?
*/
@JsonAdapter(OriginEnum.Adapter.class)
public enum OriginEnum {
HUMAN("human"),
PROCESS("process");
private String value;
OriginEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static OriginEnum fromValue(String text) {
for (OriginEnum b : OriginEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<OriginEnum> {
@Override
public void write(final JsonWriter jsonWriter, final OriginEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public OriginEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return OriginEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName("origin")
private OriginEnum origin = null;
@SerializedName("title")
private String title = null;
@SerializedName("text")
private String text = null;
@SerializedName("attachments")
private List<String> attachments = new ArrayList<String>();
@SerializedName("runs")
private List<String> runs = new ArrayList<String>();
public CreateLogDto subtype(SubtypeEnum subtype) {
this.subtype = subtype;
return this;
}
/**
* What kind of log is it?
* @return subtype
**/
@ApiModelProperty(example = "run", required = true, value = "What kind of log is it?")
public SubtypeEnum getSubtype() {
return subtype;
}
public void setSubtype(SubtypeEnum subtype) {
this.subtype = subtype;
}
public CreateLogDto origin(OriginEnum origin) {
this.origin = origin;
return this;
}
/**
* Where did the log come from?
* @return origin
**/
@ApiModelProperty(example = "human", required = true, value = "Where did the log come from?")
public OriginEnum getOrigin() {
return origin;
}
public void setOrigin(OriginEnum origin) {
this.origin = origin;
}
public CreateLogDto title(String title) {
this.title = title;
return this;
}
/**
* describes the log in short
* @return title
**/
@ApiModelProperty(example = "log for run 12", required = true, value = "describes the log in short")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public CreateLogDto text(String text) {
this.text = text;
return this;
}
/**
* describes the log in depth
* @return text
**/
@ApiModelProperty(example = "lorum ipsum", required = true, value = "describes the log in depth")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public CreateLogDto attachments(List<String> attachments) {
this.attachments = attachments;
return this;
}
public CreateLogDto addAttachmentsItem(String attachmentsItem) {
this.attachments.add(attachmentsItem);
return this;
}
/**
* Attachments of this log
* @return attachments
**/
@ApiModelProperty(example = "[]", required = true, value = "Attachments of this log")
public List<String> getAttachments() {
return attachments;
}
public void setAttachments(List<String> attachments) {
this.attachments = attachments;
}
public CreateLogDto runs(List<String> runs) {
this.runs = runs;
return this;
}
public CreateLogDto addRunsItem(String runsItem) {
this.runs.add(runsItem);
return this;
}
/**
* Attached run numbers of this log
* @return runs
**/
@ApiModelProperty(example = "\"8\"", required = true, value = "Attached run numbers of this log")
public List<String> getRuns() {
return runs;
}
public void setRuns(List<String> runs) {
this.runs = runs;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CreateLogDto createLogDto = (CreateLogDto) o;
return Objects.equals(this.subtype, createLogDto.subtype) &&
Objects.equals(this.origin, createLogDto.origin) &&
Objects.equals(this.title, createLogDto.title) &&
Objects.equals(this.text, createLogDto.text) &&
Objects.equals(this.attachments, createLogDto.attachments) &&
Objects.equals(this.runs, createLogDto.runs);
}
@Override
public int hashCode() {
return Objects.hash(subtype, origin, title, text, attachments, runs);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CreateLogDto {\n");
sb.append(" subtype: ").append(toIndentedString(subtype)).append("\n");
sb.append(" origin: ").append(toIndentedString(origin)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" text: ").append(toIndentedString(text)).append("\n");
sb.append(" attachments: ").append(toIndentedString(attachments)).append("\n");
sb.append(" runs: ").append(toIndentedString(runs)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep>/*
* Jiskefet
* Running with /api prefix
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.threeten.bp.OffsetDateTime;
/**
* CreateRunDto
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2019-03-08T11:03:08.533Z")
public class CreateRunDto {
@SerializedName("timeO2Start")
private OffsetDateTime timeO2Start = null;
@SerializedName("timeTrgStart")
private OffsetDateTime timeTrgStart = null;
@SerializedName("timeO2End")
private OffsetDateTime timeO2End = null;
@SerializedName("timeTrgEnd")
private OffsetDateTime timeTrgEnd = null;
@SerializedName("runType")
private String runType = null;
@SerializedName("runQuality")
private String runQuality = null;
@SerializedName("activityId")
private String activityId = null;
@SerializedName("nDetectors")
private Integer nDetectors = null;
@SerializedName("nFlps")
private Integer nFlps = null;
@SerializedName("nEpns")
private Integer nEpns = null;
@SerializedName("nTimeframes")
private Integer nTimeframes = null;
@SerializedName("nSubtimeframes")
private Integer nSubtimeframes = null;
@SerializedName("bytesReadOut")
private Integer bytesReadOut = null;
@SerializedName("bytesTimeframeBuilder")
private Integer bytesTimeframeBuilder = null;
public CreateRunDto timeO2Start(OffsetDateTime timeO2Start) {
this.timeO2Start = timeO2Start;
return this;
}
/**
* Get timeO2Start
* @return timeO2Start
**/
@ApiModelProperty(example = "2018-11-26T16:43:22.279Z", required = true, value = "")
public OffsetDateTime getTimeO2Start() {
return timeO2Start;
}
public void setTimeO2Start(OffsetDateTime timeO2Start) {
this.timeO2Start = timeO2Start;
}
public CreateRunDto timeTrgStart(OffsetDateTime timeTrgStart) {
this.timeTrgStart = timeTrgStart;
return this;
}
/**
* Get timeTrgStart
* @return timeTrgStart
**/
@ApiModelProperty(example = "2018-11-26T16:43:22.279Z", required = true, value = "")
public OffsetDateTime getTimeTrgStart() {
return timeTrgStart;
}
public void setTimeTrgStart(OffsetDateTime timeTrgStart) {
this.timeTrgStart = timeTrgStart;
}
public CreateRunDto timeO2End(OffsetDateTime timeO2End) {
this.timeO2End = timeO2End;
return this;
}
/**
* Get timeO2End
* @return timeO2End
**/
@ApiModelProperty(example = "2018-11-26T16:43:22.279Z", required = true, value = "")
public OffsetDateTime getTimeO2End() {
return timeO2End;
}
public void setTimeO2End(OffsetDateTime timeO2End) {
this.timeO2End = timeO2End;
}
public CreateRunDto timeTrgEnd(OffsetDateTime timeTrgEnd) {
this.timeTrgEnd = timeTrgEnd;
return this;
}
/**
* Get timeTrgEnd
* @return timeTrgEnd
**/
@ApiModelProperty(example = "2018-11-26T16:43:22.279Z", required = true, value = "")
public OffsetDateTime getTimeTrgEnd() {
return timeTrgEnd;
}
public void setTimeTrgEnd(OffsetDateTime timeTrgEnd) {
this.timeTrgEnd = timeTrgEnd;
}
public CreateRunDto runType(String runType) {
this.runType = runType;
return this;
}
/**
* What kind of run.
* @return runType
**/
@ApiModelProperty(example = "", required = true, value = "What kind of run.")
public String getRunType() {
return runType;
}
public void setRunType(String runType) {
this.runType = runType;
}
public CreateRunDto runQuality(String runQuality) {
this.runQuality = runQuality;
return this;
}
/**
* The quality of the run.
* @return runQuality
**/
@ApiModelProperty(example = "", required = true, value = "The quality of the run.")
public String getRunQuality() {
return runQuality;
}
public void setRunQuality(String runQuality) {
this.runQuality = runQuality;
}
public CreateRunDto activityId(String activityId) {
this.activityId = activityId;
return this;
}
/**
* The id of the activity.
* @return activityId
**/
@ApiModelProperty(example = "Sl4e12ofb83no92ns", required = true, value = "The id of the activity.")
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public CreateRunDto nDetectors(Integer nDetectors) {
this.nDetectors = nDetectors;
return this;
}
/**
* Number of detectors during run.
* @return nDetectors
**/
@ApiModelProperty(example = "16", required = true, value = "Number of detectors during run.")
public Integer getNDetectors() {
return nDetectors;
}
public void setNDetectors(Integer nDetectors) {
this.nDetectors = nDetectors;
}
public CreateRunDto nFlps(Integer nFlps) {
this.nFlps = nFlps;
return this;
}
/**
* Number of FLPs that computed data
* @return nFlps
**/
@ApiModelProperty(example = "7", required = true, value = "Number of FLPs that computed data")
public Integer getNFlps() {
return nFlps;
}
public void setNFlps(Integer nFlps) {
this.nFlps = nFlps;
}
public CreateRunDto nEpns(Integer nEpns) {
this.nEpns = nEpns;
return this;
}
/**
* Number of EPNs that stored data
* @return nEpns
**/
@ApiModelProperty(example = "8", required = true, value = "Number of EPNs that stored data")
public Integer getNEpns() {
return nEpns;
}
public void setNEpns(Integer nEpns) {
this.nEpns = nEpns;
}
public CreateRunDto nTimeframes(Integer nTimeframes) {
this.nTimeframes = nTimeframes;
return this;
}
/**
* Number of timeframes
* @return nTimeframes
**/
@ApiModelProperty(example = "2", required = true, value = "Number of timeframes")
public Integer getNTimeframes() {
return nTimeframes;
}
public void setNTimeframes(Integer nTimeframes) {
this.nTimeframes = nTimeframes;
}
public CreateRunDto nSubtimeframes(Integer nSubtimeframes) {
this.nSubtimeframes = nSubtimeframes;
return this;
}
/**
* Number of subtimeframes
* @return nSubtimeframes
**/
@ApiModelProperty(example = "4", required = true, value = "Number of subtimeframes")
public Integer getNSubtimeframes() {
return nSubtimeframes;
}
public void setNSubtimeframes(Integer nSubtimeframes) {
this.nSubtimeframes = nSubtimeframes;
}
public CreateRunDto bytesReadOut(Integer bytesReadOut) {
this.bytesReadOut = bytesReadOut;
return this;
}
/**
* Amount of bytes read out
* @return bytesReadOut
**/
@ApiModelProperty(example = "5", required = true, value = "Amount of bytes read out")
public Integer getBytesReadOut() {
return bytesReadOut;
}
public void setBytesReadOut(Integer bytesReadOut) {
this.bytesReadOut = bytesReadOut;
}
public CreateRunDto bytesTimeframeBuilder(Integer bytesTimeframeBuilder) {
this.bytesTimeframeBuilder = bytesTimeframeBuilder;
return this;
}
/**
* What builder was used.
* @return bytesTimeframeBuilder
**/
@ApiModelProperty(example = "12", required = true, value = "What builder was used.")
public Integer getBytesTimeframeBuilder() {
return bytesTimeframeBuilder;
}
public void setBytesTimeframeBuilder(Integer bytesTimeframeBuilder) {
this.bytesTimeframeBuilder = bytesTimeframeBuilder;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CreateRunDto createRunDto = (CreateRunDto) o;
return Objects.equals(this.timeO2Start, createRunDto.timeO2Start) &&
Objects.equals(this.timeTrgStart, createRunDto.timeTrgStart) &&
Objects.equals(this.timeO2End, createRunDto.timeO2End) &&
Objects.equals(this.timeTrgEnd, createRunDto.timeTrgEnd) &&
Objects.equals(this.runType, createRunDto.runType) &&
Objects.equals(this.runQuality, createRunDto.runQuality) &&
Objects.equals(this.activityId, createRunDto.activityId) &&
Objects.equals(this.nDetectors, createRunDto.nDetectors) &&
Objects.equals(this.nFlps, createRunDto.nFlps) &&
Objects.equals(this.nEpns, createRunDto.nEpns) &&
Objects.equals(this.nTimeframes, createRunDto.nTimeframes) &&
Objects.equals(this.nSubtimeframes, createRunDto.nSubtimeframes) &&
Objects.equals(this.bytesReadOut, createRunDto.bytesReadOut) &&
Objects.equals(this.bytesTimeframeBuilder, createRunDto.bytesTimeframeBuilder);
}
@Override
public int hashCode() {
return Objects.hash(timeO2Start, timeTrgStart, timeO2End, timeTrgEnd, runType, runQuality, activityId, nDetectors, nFlps, nEpns, nTimeframes, nSubtimeframes, bytesReadOut, bytesTimeframeBuilder);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CreateRunDto {\n");
sb.append(" timeO2Start: ").append(toIndentedString(timeO2Start)).append("\n");
sb.append(" timeTrgStart: ").append(toIndentedString(timeTrgStart)).append("\n");
sb.append(" timeO2End: ").append(toIndentedString(timeO2End)).append("\n");
sb.append(" timeTrgEnd: ").append(toIndentedString(timeTrgEnd)).append("\n");
sb.append(" runType: ").append(toIndentedString(runType)).append("\n");
sb.append(" runQuality: ").append(toIndentedString(runQuality)).append("\n");
sb.append(" activityId: ").append(toIndentedString(activityId)).append("\n");
sb.append(" nDetectors: ").append(toIndentedString(nDetectors)).append("\n");
sb.append(" nFlps: ").append(toIndentedString(nFlps)).append("\n");
sb.append(" nEpns: ").append(toIndentedString(nEpns)).append("\n");
sb.append(" nTimeframes: ").append(toIndentedString(nTimeframes)).append("\n");
sb.append(" nSubtimeframes: ").append(toIndentedString(nSubtimeframes)).append("\n");
sb.append(" bytesReadOut: ").append(toIndentedString(bytesReadOut)).append("\n");
sb.append(" bytesTimeframeBuilder: ").append(toIndentedString(bytesTimeframeBuilder)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
<file_sep>
# LinkRunToLogDto
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**runNumber** | **Integer** | The id of the run to link to the log. |
| 027ed016470c0515675f418bda62e05509075e62 | [
"Markdown",
"Java"
] | 19 | Markdown | SoftwareForScience/jiskefet-api-java | 60404538c406e2de394cf6b1d9ffa95b1a3ab2de | 365b916549531504a023ac75021ec44e94f451e2 |
refs/heads/master | <repo_name>scottmorr/Readme.generator<file_sep>/ReadME.md
# Project Title: Readme
Created in Node.Js. READMe was created using NPM Inquirer. Inquirer provided question prompts to better assist in READMe completion. Included in this README are images of the created project with video highlighting project usage.

This image indicates Inquirer. Also provided is the function that allowed me to transfer pormpt questions to new page.

Prompts with answers. Accessed within index.js terminal.

Completed READMe
# Project Title: Readme
### Authors: <NAME>
### Github User: scottmorr
###Project link: https://github.com/scottmorr/readme
###Project Description: it was hard
###Project license: [](https://github.com/scottmorr/readme)
##### please contact <EMAIL>
<file_sep>/file.js
import css from 'file.css';<file_sep>/index.js
const fs = require("fs");
const inquirer = require("inquirer");
const generateMarkdown = require("./utils/generateMarkdown");
inquirer
.prompt([
{
type: "input",
message: "What is your GitHub user name?",
name: "github"
},
{
type: "input",
message: "What is your email?",
name: "email"
}, {
type: "input",
message: "What is the name of your project",
name: "title"
}, {
type: "input",
message: "List the names of all contributors",
name: "author"
},
{
type: "input",
message: "Add the link of your project.",
name: "url"
}, {
type: "input",
message: "Describe your project.",
name: "description"
},
{
type: "list",
message: "What license does your project have?",
choices: ["MIT", "None", "APACHE2.0"],
name: "license"
},
])
.then(function (response) {
//create data object
fs.writeFileSync("README.md", generateMarkdown(response), function (err) {
if (err) return console.log(err)
});
console.log("Success! A README has beenn created.");
});
| 1b968e042fccdde26c5b23a4d2639446a8e90e52 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | scottmorr/Readme.generator | f043d00f8f9a4d88566779848ef1cdec58d553fd | 3b30bdffaa1e2f2f27d0e81dd9bcf3c7b6711939 |
refs/heads/master | <file_sep><?php
$hostname="localhost";
$user="root";
$password="";
$database="tuaplicacion";
$link = mysqli_connect($hostname, $user, $password, $database) or die("No fue posible conectarse.");
?><file_sep><?php
require_once("coneccion.php");
require_once("geolocalizar.php");
$nomb = $_POST["nombres"];
$apell = $_POST["apellidos"];
$tel = $_POST["telefono"];
$emai = $_POST["email"];
$direc = $_POST["direccion"];
$pref = $_POST["preferencias"];
$return = Maps::buscaLugar($direc);
$lat = $return[0];
$long = $return[1];
$sql = "INSERT INTO usuario (nombres, apellidos, telefono, email, direccion, preferencias, latitud, longitud) VALUES ('$nomb', '$apell', '$tel', '$emai', '$direc', '$pref', '$lat', '$long');";
$query = mysqli_query($link,$sql);
if ($query){
echo "<script>alert(\"Exito al registrar.\"); </script>";
echo "<script>location.href='index.php'</script>";
}else{
echo "<script>alert(\"Error al registrar.\"); </script>";
echo "<script>location.href='index.php'</script>";
}
<file_sep><!DOCTYPE html>
<?php require_once("coneccion.php");
$result = mysqli_query($link,"SELECT * FROM usuario");
?>
<html>
<head>
<meta charset="UTF-8">
<title>Entrevista_Tuaplicacion</title>
<link rel="stylesheet" href="css/estilos.css">
</head>
<body>
<section id="formulario2">
<?php
if ($result){
$row = mysqli_fetch_array($result);
echo "<table border = '2' \n";
echo "<tr><td>ID</td><td>Nombres</td><td>Apellidos</td><td>Teléfono</td><td>Email</td><td>Direccion</td><td>Preferencias</td><td>Latitud</td><td>Longitud</td></tr>";
do{
echo "<tr><td>".$row["id_usuario"]."</td><td>".$row["nombres"]."</td><td>".$row["apellidos"]."</td><td>".$row["telefono"]."</td><td>".$row["email"]."</td><td>".$row["direccion"]."</td><td>".$row["preferencias"]."</td><td>".$row["latitud"]."</td><td>".$row["longitud"]."</td><tr>";
}while ($row = mysqli_fetch_array($result));
echo "</table> \n";
}else{
echo "<hr></br></br><p align='center'>¡SIN REGISTROS!</p></br></br>";
}
?>
<br><br><a class="botones" href="index.php">VOLVER A REGISTRAR USUARIOS</a>
</section>
</body>
</html> | 3d77033e01413978730425621d1add85e006a8c2 | [
"PHP"
] | 3 | PHP | jasa1704/landing-page | 1ba7a4a67f3e9d284ea93b498fd80b8158845953 | a7de4353242e755b26eda1367dc941dfef441347 |
refs/heads/main | <file_sep>package com.exercise.weatherdemo.ui.place.adapter
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.exercise.weatherdemo.R
import com.exercise.weatherdemo.common.CommonObject
import com.exercise.weatherdemo.logic.model.Place
import com.exercise.weatherdemo.ui.place.fragment.PlaceFragment
import com.exercise.weatherdemo.ui.weather.activity.WeatherActivity
import kotlinx.android.synthetic.main.activity_weather.*
class PlaceAdapter(private val fragment: PlaceFragment, private val placeList: List<Place>) : RecyclerView.Adapter<PlaceAdapter.ViewHolder>() {
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val placeName: TextView = view.findViewById(R.id.placeName)
val placeAddress: TextView = view.findViewById(R.id.placeAddress)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.place_item, parent, false)
val holder = ViewHolder(view)
holder.itemView.setOnClickListener {
val position = holder.adapterPosition
val place = placeList[position]
val activity = fragment.activity
val placeSaveList = fragment.viewModel.getPlace()
if (activity is WeatherActivity) {
activity.drawerLayout.closeDrawers()
activity.viewModel.locationLng = place.location.lng
activity.viewModel.locationLat = place.location.lat
activity.viewModel.placeName = place.name
activity.refreshWeather()
}
if(CommonObject.checkPlaceContains(placeSaveList, place)==-1)
placeSaveList.add(place)
fragment.viewModel.savePlace(placeSaveList)
}
return holder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val place = placeList[position]
holder.placeName.text = place.name
holder.placeAddress.text = place.address
}
override fun getItemCount() = placeList.size
}<file_sep>package com.exercise.weatherdemo.common
/**
* @author lvzw
* @date 2021年04月15日 15:51
*/
class UpdateEvent() {
// object{
var updateEvent: Boolean = true
//}
init {
updateEvent = false
}
constructor(update: Boolean): this(){
updateEvent = update
}
}<file_sep>package com.exercise.weatherdemo.logic.DAO
import android.content.Context
import androidx.core.content.edit
import androidx.lifecycle.MutableLiveData
import com.exercise.weatherdemo.WeatherDemoApplication
import com.exercise.weatherdemo.common.CommonObject
import com.exercise.weatherdemo.logic.model.Place
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonParser
/**
* @author lvzw
* @date 2021年04月12日 8:56
*/
object PlaceDao {
private val placeList = ArrayList<Place>()
val placeListLiveData = MutableLiveData<ArrayList<Place>>()
private fun getSharedPreferences() = WeatherDemoApplication.context.getSharedPreferences(
DaoConstant.PLACE_SHAREDPREFERENCE,
Context.MODE_PRIVATE
)
fun savePlace(place: ArrayList<Place>){
getSharedPreferences().edit{
putString("place", Gson().toJson(place))
}
placeListLiveData.value = place
}
fun getPlace(): ArrayList<Place> {
try {
val gson = Gson()
val array: JsonArray =
JsonParser().parse(getSharedPreferences().getString("place", "")).asJsonArray
placeList.clear()
for (jsonElement in array) {
val place = gson.fromJson(jsonElement, Place::class.java)
placeList.add(place)
}
} catch (e: Exception) {
e.printStackTrace()
}
return placeList
}
fun isPlaceSaved(): Boolean{
return getSharedPreferences().contains("place")
}
fun deleteListItem(place: Place) {
val places = getPlace()
places.removeAt(CommonObject.checkPlaceContains(places, place))
savePlace(places)
}
}<file_sep>include ':app'
rootProject.name='WeatherDemo'
<file_sep>package com.exercise.weatherdemo.ui.place.viewmodel
import androidx.lifecycle.ViewModel
import com.exercise.weatherdemo.common.CommonObject
import com.exercise.weatherdemo.logic.model.Place
import com.exercise.weatherdemo.logic.model.Repository
import com.exercise.weatherdemo.logic.model.Weather
import com.exercise.weatherdemo.logic.model.data.PlaceListItem
/**
* @author lvzw
* @date 2021年04月14日 11:29
*/
class ListPlaceViewModel: ViewModel() {
var placeListLiveData = Repository.placeListLiveData
val placeList = getPlace()
val placeItemList = ArrayList<PlaceListItem>()
fun getPlace() = Repository.getPlace()
fun deleteListItem(place: Place, position: Int) {
placeItemList.removeAt(position)
Repository.deleteListItem(place)
}
}<file_sep>package com.exercise.weatherdemo.common
import android.location.*
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import com.exercise.weatherdemo.WeatherDemoApplication.Companion.context
import com.exercise.weatherdemo.logic.model.data.CurrentLocation
import java.io.IOException
import java.util.*
/**
* Author : lchiway
* Date : 2021/4/16
* Desc :
*/
object PlaceLocation {
private var locationManager : LocationManager? = null
private var updatePeriod: Long = 5*60*1000
var currentLocation: CurrentLocation = CurrentLocation("", "", "")
var curLocLiveData = MutableLiveData<CurrentLocation>()
private val locationListener: LocationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
//Log.d("lvzw", "onLocationChanged: get the locations: ${location.toString()}")
currentLocation.lng = location.longitude.toString()
currentLocation.lat = location.latitude.toString()
try {
val geoCoder = Geocoder(context, Locale.getDefault())
val addresses: List<Address> = geoCoder.getFromLocation(
location.latitude,
location.longitude, 1
)
val sb = StringBuilder()
if (addresses.isNotEmpty()) {
val address: Address = addresses[0]
sb.append(address.locality).append("\n")
currentLocation.name = sb.toString()
}
} catch (e: IOException) {
e.printStackTrace()
}
curLocLiveData.value = currentLocation
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
}
fun requestLocationUpdate(){
locationManager = context.getSystemService(AppCompatActivity.LOCATION_SERVICE) as LocationManager?
try {
// Request location updates
locationManager?.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
updatePeriod,
0f,
locationListener
)
} catch (e: SecurityException) {
e.printStackTrace()
}
}
/**
* @param period: update period
* @Description: For update period settings
*/
fun setUpdatePeriod(period: Long){
updatePeriod = period
}
fun removeLocationRequest(){
locationManager?.removeUpdates(locationListener)
}
}<file_sep>package com.exercise.weatherdemo.ui.place.fragment
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.exercise.weatherdemo.R
import com.exercise.weatherdemo.common.CommonObject
import com.exercise.weatherdemo.common.UpdateEvent
import com.exercise.weatherdemo.logic.model.Place
import com.exercise.weatherdemo.logic.model.data.PlaceListItem
import com.exercise.weatherdemo.ui.place.adapter.ListAdapter
import com.exercise.weatherdemo.ui.place.viewmodel.ListPlaceViewModel
import com.exercise.weatherdemo.ui.weather.viewmodel.WeatherViewModel
import kotlinx.android.synthetic.main.fragment_list.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
/**
* @author lvzw
* @date 2021年04月13日 17:24
*/
class ListFragment: Fragment() {
private lateinit var adapter: ListAdapter
val viewModel by lazy { ViewModelProvider(this).get(ListPlaceViewModel::class.java) }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.d("lvzw", "onCreateView: ")
return inflater.inflate(R.layout.fragment_list, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Log.d("lvzw", "onActivityCreated: ")
val layoutManager = LinearLayoutManager(activity)
listView.layoutManager = layoutManager
initWeatherObserver(viewModel.placeList)
adapter = ListAdapter(this, viewModel.placeItemList)
listView.adapter = adapter
viewModel.placeListLiveData.observe(this.viewLifecycleOwner, Observer { result ->
if (result.size != 0) {
Log.d("lvzw", "placeListLiveData: ${result[result.size-1]}")
addWeatherObserver(result[result.size-1])
}
})
EventBus.getDefault().register(this)
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
@Subscribe
fun refreshListWeather(update: UpdateEvent){
Log.d("lvzw", "refreshListWeather: ${update.updateEvent}")
if(update.updateEvent) {
for (i in 0 until viewModel.placeItemList.size) {
viewModel.placeItemList[i].weatherViewModel.refreshWeather(
viewModel.placeItemList[i].place.location.lng,
viewModel.placeItemList[i].place.location.lat
)
}
}
}
private fun initWeatherObserver(placeList: ArrayList<Place>){
for(i in 0 until placeList.size){
addWeatherObserver(placeList[i])
}
}
private fun addWeatherObserver(place: Place){
val weatherViewModel = WeatherViewModel()
val placeList = viewModel.getPlace()
weatherViewModel.locationLat = place.location.lat
weatherViewModel.locationLng = place.location.lng
weatherViewModel.placeName = place.name
weatherViewModel.weatherLiveData.observe(this.viewLifecycleOwner, Observer { result ->
val weather = result.getOrNull()
if (weather != null) {
if(viewModel.placeItemList.size!=placeList.size || CommonObject.checkPlaceContains(placeList, place) == -1)
viewModel.placeItemList.add(PlaceListItem(place, weather, weatherViewModel))
adapter.notifyDataSetChanged()
} else {
Toast.makeText(this.context, "${place.name}无法成功获取天气信息", Toast.LENGTH_SHORT).show()
result.exceptionOrNull()?.printStackTrace()
}
})
weatherViewModel.refreshWeather(weatherViewModel.locationLng, weatherViewModel.locationLat)
}
}<file_sep>package com.exercise.weatherdemo.ui.weather.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.exercise.weatherdemo.common.CommonObject
import com.exercise.weatherdemo.logic.model.Location
import com.exercise.weatherdemo.logic.model.Place
import com.exercise.weatherdemo.logic.model.Repository
/**
* Author : lchiway
* Date : 2021/4/4
* Desc :
*/
class WeatherViewModel : ViewModel(){
private val locationLiveData = MutableLiveData<Location>()
var locationLng = ""
var locationLat = ""
var placeName = ""
val weatherLiveData = Transformations.switchMap(locationLiveData) { location ->
Repository.refreshWeather(location.lng, location.lat)
}
fun refreshWeather(lng: String, lat: String){
locationLiveData.value = Location(lng, lat)
}
fun savePlace() {
placeName += "(定位)"
val place: Place = Place(placeName, Location(locationLng, locationLat), "")
val placeList = Repository.getPlace()
if(placeList.size==0) {
placeList.add(place)
Repository.savePlace(placeList)
}
else {
placeList[0] = place
Repository.savePlace(placeList)
}
}
}<file_sep>package com.exercise.weatherdemo.common
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ViewParent
import android.widget.LinearLayout
import android.widget.Scroller
import kotlin.math.abs
/**
* @author lvzw
* @date 2021年04月15日 16:46
*/
class SwipeLinearLayout @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
LinearLayout(context, attrs, defStyleAttr) {
var mScroller: Scroller
var startScrollX = 0
var lastX = 0f
var lastY = 0f
var startX = 0f
var startY = 0f
var hasJudged = false
var ignore = false
var onSwipeListener: OnSwipeListener? = null
// 左边部分, 即从开始就显示的部分的长度
private var width_left = 0
// 右边部分, 即在开始时是隐藏的部分的长度
private var width_right = 0
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l, t, r, b)
val left = getChildAt(0)
val right = getChildAt(1)
width_left = left.measuredWidth
width_right = right.measuredWidth
}
private fun disallowParentsInterceptTouchEvent(parent: ViewParent?) {
if (null == parent) {
return
}
parent.requestDisallowInterceptTouchEvent(true)
disallowParentsInterceptTouchEvent(parent.parent)
}
private fun allowParentsInterceptTouchEvent(parent: ViewParent?) {
if (null == parent) {
return
}
parent.requestDisallowInterceptTouchEvent(false)
allowParentsInterceptTouchEvent(parent.parent)
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
disallowParentsInterceptTouchEvent(parent)
hasJudged = false
startX = ev.x
startY = ev.y
}
MotionEvent.ACTION_MOVE -> {
val curX = ev.x
val curY = ev.y
if (!hasJudged) {
val dx = curX - startX
val dy = curY - startY
if (abs(dy) > abs(dx)) {
allowParentsInterceptTouchEvent(parent)
if (null != onSwipeListener) {
onSwipeListener!!.onDirectionJudged(this, false)
}
} else {
if (null != onSwipeListener) {
onSwipeListener!!.onDirectionJudged(this, true)
}
lastX = curX
lastY = curY
}
if (dx * dx + dy * dy > 2 * MOVE_JUDGE_DISTANCE * MOVE_JUDGE_DISTANCE) {
hasJudged = true
ignore = true
}
}
}
MotionEvent.ACTION_UP -> {
}
else -> {
}
}
return super.dispatchTouchEvent(ev)
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return if (hasJudged) {
true
} else super.onInterceptTouchEvent(ev)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
//Log.d("lvzw", "onTouchEvent: touch down: $event")
lastX = event.x
lastY = event.y
startScrollX = scrollX
}
MotionEvent.ACTION_MOVE -> {
//Log.d("lvzw", "onTouchEvent: touch move: $event")
if (ignore) {
ignore = false
}
val curX = event.x
val dX = curX - lastX
lastX = curX
if (hasJudged) {
val targetScrollX = scrollX + (-dX).toInt()
when {
targetScrollX > width_right -> scrollTo(width_right, 0)
targetScrollX < 0 -> scrollTo(0, 0)
else -> scrollTo(targetScrollX, 0)
}
}
}
MotionEvent.ACTION_UP -> {
//Log.d("lvzw", "onTouchEvent: touch up: $event")
val finalX = event.x
if (finalX < startX) {
scrollAuto(DIRECTION_EXPAND)
} else {
scrollAuto(DIRECTION_SHRINK)
}
}
}
return true
}
/**
* 自动滚动, 变为展开或收缩状态
* @param direction
*/
fun scrollAuto(direction: Int) {
val curScrollX = scrollX
if (direction == DIRECTION_EXPAND) {
// 展开
mScroller.startScroll(curScrollX, 0, width_right - curScrollX, 0, 300)
} else {
// 缩回
mScroller.startScroll(curScrollX, 0, -curScrollX, 0, 300)
}
invalidate()
}
override fun computeScroll() {
super.computeScroll()
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.currX, 0)
invalidate()
}
}
fun setSwipeListener(listener: OnSwipeListener?) {
onSwipeListener = listener
}
interface OnSwipeListener {
/**
* 手指滑动方向明确了
* @param sll 拖动的SwipeLinearLayout
* @param isHorizontal 滑动方向是否为水平
*/
fun onDirectionJudged(sll: SwipeLinearLayout?, isHorizontal: Boolean)
}
companion object {
const val DIRECTION_EXPAND = 0
const val DIRECTION_SHRINK = 1
var MOVE_JUDGE_DISTANCE = 15f
}
init {
mScroller = Scroller(context)
this.orientation = HORIZONTAL
}
}<file_sep>package com.exercise.weatherdemo.ui.place.adapter
import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.exercise.weatherdemo.R
import com.exercise.weatherdemo.common.SwipeLinearLayout
import com.exercise.weatherdemo.logic.model.data.PlaceListItem
import com.exercise.weatherdemo.logic.model.getSky
import com.exercise.weatherdemo.ui.place.fragment.ListFragment
import com.exercise.weatherdemo.ui.weather.activity.WeatherActivity
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.list_place_item.*
/**
* @author lvzw
* @date 2021年04月14日 9:58
*/
class ListAdapter(
private val fragment: ListFragment,
private val placeItemList: ArrayList<PlaceListItem>
): RecyclerView.Adapter<ListAdapter.ViewHolder>(), SwipeLinearLayout.OnSwipeListener {
private val swipeLinearLayouts = ArrayList<SwipeLinearLayout>()
inner class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
val placeName: TextView = view.findViewById(R.id.listPlaceName)
val placeTemp: TextView = view.findViewById(R.id.listPlaceTemp)
val listPlaceLayout: LinearLayout = view.findViewById(R.id.listPlaceLayout)
val swipeLinearLayout: SwipeLinearLayout = view.findViewById(R.id.swipeListLayout)
val deleteListItem: FrameLayout = view.findViewById(R.id.deleteListItem)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(
R.layout.list_place_item,
parent,
false
)
val holder = ViewHolder(view)
holder.swipeLinearLayout.setSwipeListener(this)
holder.listPlaceLayout.setOnClickListener {
val position = holder.adapterPosition
val place = placeItemList[position].place
val activity = fragment.activity
if (activity is WeatherActivity) {
activity.drawerLayout.closeDrawers()
activity.viewModel.locationLng = place.location.lng
activity.viewModel.locationLat = place.location.lat
activity.viewModel.placeName = place.name
activity.refreshWeather(placeItemList[position].weather)
}
//holder.swipeLinearLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
}
holder.deleteListItem.setOnClickListener {
Log.d("lvzw", "onCreateViewHolder: ${holder.adapterPosition}, ${placeItemList.size}")
if(holder.adapterPosition != 0) {
fragment.viewModel.deleteListItem(
placeItemList[holder.adapterPosition].place,
holder.adapterPosition
)
holder.swipeLinearLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
}
}
return holder
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
var temp = 0.0F
holder.placeName.text = placeItemList[position].place.name
if(placeItemList.size > 0 && placeItemList.size > position) {
temp = placeItemList[position].weather.realtime.temperature
holder.listPlaceLayout.setBackgroundResource(getSky(placeItemList[position].weather.realtime.skycon).bg)
}
holder.placeTemp.text = "$temp ℃"
swipeLinearLayouts.add(holder.swipeLinearLayout)
}
override fun onDirectionJudged(sll: SwipeLinearLayout?, isHorizontal: Boolean) {
if (isHorizontal) {
for (swipeLinearLayout in swipeLinearLayouts) {
swipeLinearLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
}
} else {
for (swipeLinearLayout in swipeLinearLayouts) {
if (swipeLinearLayout != sll) {
swipeLinearLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK)
}
}
}
}
override fun getItemCount() = placeItemList.size
}<file_sep>package com.exercise.weatherdemo.common
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.exercise.weatherdemo.WeatherDemoApplication.Companion.context
/**
* Author : lchiway
* Date : 2021/4/16
* Desc :
*/
object WeatherPermission {
private val permission = arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
fun checkPermission(activity: Activity): Boolean {
for (i in permission.indices) {
val checkPermission = context.let{ActivityCompat.checkSelfPermission(it, permission[i])}
if (checkPermission == PackageManager.PERMISSION_DENIED) {
requestWeatherPermission(activity)
return false
}
}
return true
}
private fun requestWeatherPermission(activity: Activity){
activity.requestPermissions(permission, 0)
}
}<file_sep>package com.exercise.weatherdemo.ui.place.viewmodel
import androidx.lifecycle.ViewModel
import com.exercise.weatherdemo.common.PlaceLocation.curLocLiveData
import com.exercise.weatherdemo.logic.model.Repository
/**
* @author lvzw
* @date 2021年04月12日 16:59
*/
class PlaceLocationViewModel: ViewModel() {
var placeLocationLiveData = curLocLiveData
fun requestLocationUpdate() = Repository.requestLocationUpdate()
fun removeLocationRequest() = Repository.removeLocationRequest()
}<file_sep>package com.exercise.weatherdemo.logic.model.data
import com.exercise.weatherdemo.logic.model.Place
import com.exercise.weatherdemo.logic.model.Weather
import com.exercise.weatherdemo.ui.weather.viewmodel.WeatherViewModel
/**
* Author : lchiway
* Date : 2021/4/16
* Desc :
*/
data class PlaceListItem(var place: Place, var weather: Weather, var weatherViewModel: WeatherViewModel)
<file_sep>package com.exercise.weatherdemo.logic.model
import java.util.*
/**
* Author : lchiway
* Date : 2021/4/12
* Desc :
*/
data class HourlyResponse(val status: String, val result: Result){
data class Result(val hourly: Hourly)
data class Hourly(val skycon: List<Skycon>, val temperature: List<Temperature>)
data class Skycon(val value: String, val datetime: Date)
data class Temperature(val value: String, val datetime: Date)
}
<file_sep>package com.exercise.weatherdemo.logic.network
import com.exercise.weatherdemo.WeatherDemoApplication
import com.exercise.weatherdemo.logic.model.HourlyResponse
import com.exercise.weatherdemo.logic.model.RealtiimResponse
import com.exercise.weatherdemo.logic.model.dailyResponse
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
interface WeatherService {
@GET("v2.5/${WeatherDemoApplication.TOKEN}/{lng},{lat}/realtime.json")
fun getRealtimeWeather(@Path("lng")lng: String, @Path("lat")lat: String) : Call<RealtiimResponse>
@GET("v2.5/${WeatherDemoApplication.TOKEN}/{lng},{lat}/daily.json")
fun getDailyWeather(@Path("lng")lng: String, @Path("lat")lat: String) : Call<dailyResponse>
@GET("v2.5/${WeatherDemoApplication.TOKEN}/{lng},{lat}/hourly.json?hourlysteps=12")
fun getHourlyWeather(@Path("lng")lng: String, @Path("lat")lat: String) : Call<HourlyResponse>
}<file_sep>package com.exercise.weatherdemo.common
import com.exercise.weatherdemo.logic.model.Place
/**
* Author : lchiway
* Date : 2021/4/16
* Desc :
*/
object CommonObject {
fun checkPlaceContains(list: ArrayList<Place>, place: Place): Int{
for(i in 0 until list.size){
if(list[i].name == place.name)
return i
}
return -1
}
}<file_sep>package com.exercise.weatherdemo.logic.model.data
/**
* Author : lchiway
* Date : 2021/4/16
* Desc :
*/
data class CurrentLocation(var lng: String, var lat: String, var name: String)
<file_sep>package com.exercise.weatherdemo.ui.weather.activity
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowInsets
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.ScrollView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.exercise.weatherdemo.R
import com.exercise.weatherdemo.common.UpdateEvent
import com.exercise.weatherdemo.common.WeatherPermission
import com.exercise.weatherdemo.logic.model.Weather
import com.exercise.weatherdemo.logic.model.getSky
import com.exercise.weatherdemo.ui.place.viewmodel.PlaceLocationViewModel
import com.exercise.weatherdemo.ui.weather.viewmodel.WeatherViewModel
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.forecast.*
import kotlinx.android.synthetic.main.hourly.*
import kotlinx.android.synthetic.main.life_index.*
import kotlinx.android.synthetic.main.now.*
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.*
class WeatherActivity : AppCompatActivity() {
val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) }
private val locationViewModel by lazy { ViewModelProvider(this).get(PlaceLocationViewModel::class.java) }
private var exitTime: Long = 0
private lateinit var scrollView: ScrollView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_weather)
setFullScreen()
setTheme(R.style.AppTheme)
//initLocationInfo()
scrollView = findViewById(R.id.weatherLayout)
if(WeatherPermission.checkPermission(this)){
locationViewModel.requestLocationUpdate()
initObserver()
initListener()
}
}
override fun onDestroy() {
super.onDestroy()
locationViewModel.removeLocationRequest()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
// location permission
if(grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
locationViewModel.requestLocationUpdate()
initObserver()
initListener()
return
}
finish()
}
private fun setFullScreen(){
if (Build.VERSION.SDK_INT >= 30) {
window.insetsController.also {
it?.hide(WindowInsets.Type.statusBars())
it?.hide(WindowInsets.Type.navigationBars())
it?.hide(WindowInsets.Type.systemBars())
}
}
else {
val decorView = window.decorView
window.statusBarColor = Color.TRANSPARENT
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
}
private fun initLocationInfo(){
if (viewModel.locationLng.isEmpty()) {
viewModel.locationLng = intent.getStringExtra("location_lng") ?: ""
}
if (viewModel.locationLat.isEmpty()) {
viewModel.locationLat = intent.getStringExtra("location_lat") ?: ""
}
if (viewModel.placeName.isEmpty()) {
viewModel.placeName = intent.getStringExtra("place_name") ?: ""
}
}
private fun initObserver(){
locationViewModel.placeLocationLiveData.observe(this, Observer { result ->
if (result.name != "") {
viewModel.locationLng = result.lng
viewModel.locationLat = result.lat
viewModel.placeName = result.name
viewModel.savePlace() //should be optimized
refreshWeather()
} else {
Toast.makeText(this, "无法成功获取定位信息", Toast.LENGTH_SHORT).show()
}
})
viewModel.weatherLiveData.observe(this, Observer { result ->
val weather = result.getOrNull()
if (weather != null) {
showWeatherInfo(weather)
} else {
Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show()
result.exceptionOrNull()?.printStackTrace()
}
swipeRefresh.isRefreshing = false
})
}
private fun initListener(){
swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
refreshWeather()
swipeRefresh.setOnRefreshListener {
refreshWeather()
}
navBtn.setOnClickListener {
drawerLayout.openDrawer(GravityCompat.START)
}
listBtn.setOnClickListener {
EventBus.getDefault().post(UpdateEvent(true))
drawerLayout.openDrawer(GravityCompat.END)
}
scrollView.viewTreeObserver.addOnScrollChangedListener( ViewTreeObserver.OnScrollChangedListener {
swipeRefresh.isEnabled = (scrollView.scrollY == 0)
})
drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
override fun onDrawerStateChanged(newState: Int) {}
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
override fun onDrawerOpened(drawerView: View) {}
override fun onDrawerClosed(drawerView: View) {
val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
manager.hideSoftInputFromWindow(
drawerView.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS
)
}
})
}
override fun onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START) || drawerLayout.isDrawerOpen(GravityCompat.END)){
drawerLayout.closeDrawers()
return
}
if(System.currentTimeMillis() - exitTime > 2000){
Toast.makeText(this, "Press back key twice to exit the app", Toast.LENGTH_LONG).show()
exitTime = System.currentTimeMillis()
return
}
finish()
}
fun refreshWeather() {
viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat)
swipeRefresh.isRefreshing = true
}
fun refreshWeather(weather: Weather){
showWeatherInfo(weather)
}
private fun showWeatherInfo(weather: Weather?) {
placeName.text = viewModel.placeName
val realtime = weather!!.realtime
val daily = weather.daily
val hourly = weather.hourly
// 填充now.xml布局中数据
val currentTempText = "${realtime.temperature.toInt()} ℃"
currentTemp.text = currentTempText
currentSky.text = getSky(realtime.skycon).info
val currentAQIText = "aqi: ${realtime.airQuality.aqi.chn.toInt()}"
currentAQI.text = currentAQIText
drawerLayout.setBackgroundResource(getSky(realtime.skycon).bg)
// 填充hourly.xml布局中的数据
hourly_layout.removeAllViews()
val hours = hourly.skycon.size
for(i in 0 until hours) {
val skycon = hourly.skycon[i]
val temp = hourly.temperature[i]
val view = LayoutInflater.from(this).inflate(R.layout.hourly_item, hourly_layout, false)
val hour = view.findViewById(R.id.hourly_time) as TextView
val skyIcon = view.findViewById(R.id.hourly_skycon) as ImageView
val temperature = view.findViewById(R.id.hourly_temp) as TextView
hour.text = SimpleDateFormat("HH", Locale.getDefault()).format(skycon.datetime)
skyIcon.setImageResource(getSky(skycon.value).icon)
temperature.text = "${temp.value} ℃"
hourly_layout.addView(view)
}
// 填充forecast.xml布局中的数据
forecastLayout.removeAllViews()
val days = daily.skycon.size
for (i in 0 until days) {
val skycon = daily.skycon[i]
val temperature = daily.temperature[i]
val view = LayoutInflater.from(this).inflate(
R.layout.forecast_item,
forecastLayout,
false
)
val dateInfo = view.findViewById(R.id.dateInfo) as TextView
val skyIcon = view.findViewById(R.id.skyIcon) as ImageView
val skyInfo = view.findViewById(R.id.skyInfo) as TextView
val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
dateInfo.text = simpleDateFormat.format(skycon.date)
val sky = getSky(skycon.value)
skyIcon.setImageResource(sky.icon)
skyInfo.text = sky.info
val tempText = "${temperature.min.toInt()} ~ ${temperature.max.toInt()} ℃"
temperatureInfo.text = tempText
forecastLayout.addView(view)
}
// 填充life_index.xml布局中的数据
val lifeIndex = daily.lifeIndex
coldRiskText.text = lifeIndex.coldRisk[0].desc
dressingText.text = lifeIndex.dressing[0].desc
ultravioletText.text = lifeIndex.ultraviolet[0].desc
carWashingText.text = lifeIndex.carWashing[0].desc
weatherLayout.visibility = View.VISIBLE
}
}<file_sep>package com.exercise.weatherdemo.logic.model
data class Weather(val realtime: RealtiimResponse.Realtime, val daily: dailyResponse.Daily, val hourly: HourlyResponse.Hourly)<file_sep>package com.exercise.weatherdemo.logic.DAO
/**
* @author lvzw
* @date 2021年04月12日 9:00
*/
object DaoConstant {
const val PLACE_SHAREDPREFERENCE = "weatherDemo"
} | 3f1b078f2bb06702d9e98ac29fa49f7929d62a4a | [
"Kotlin",
"Gradle"
] | 20 | Kotlin | lchiway/WeatherDemo | a7b11bac4bdbb17d44028088883ba8d71e9fe2c3 | 0b1a425df9d095ca4fe0ba1b95149e4409309e29 |
refs/heads/master | <file_sep>$(document).ready(function() {
$("#jscpt").click(function() {
$(".j-gone").toggle();
$(".j-text-showing").toggle();
$("#jscpt").addClass("backgroundnew");
$("#jscpt").removeClass("style");
});
$("#opts").click(function() {
$(".o-gone").toggle();
$(".o-text-showing").toggle();
$("#opts").addClass("backgroundnew");
$("#opts").removeClass("style");
});
$("#vars").click(function() {
$(".v-gone").toggle();
$(".v-text-showing").toggle();
$("#vars").addClass("backgroundnew");
$("#vars").removeClass("style");
});
$("#varName").click(function() {
$(".vn-gone").toggle();
$(".vn-text-showing").toggle();
$("#varName").addClass("backgroundnew");
$("#varName").removeClass("style");
});
$("#funct").click(function() {
$(".f-gone").toggle();
$(".f-text-showing").toggle();
$("#funct").addClass("backgroundnew");
$("#funct").removeClass("style");
});
$("#meth").click(function() {
$(".m-gone").toggle();
$(".m-text-showing").toggle();
$("#meth").addClass("backgroundnew");
$("#meth").removeClass("style");
});
});
| e9bceb62fe31b5192dea63f4f497029c422763bd | [
"JavaScript"
] | 1 | JavaScript | albelka/flashcards | 407bb7ec7e893c5ee6511a9f3bc406fcdb7c36a4 | 9faf49ddbab1bf9ecd7483ea34e2727f46226815 |
refs/heads/master | <repo_name>pavan-kanchupati/Img-upload<file_sep>/src/components/card/Home.js
import React from 'react';
import './card-style.css';
const Home = ( props ) =>{
return(
<div className = 'card text-center'>
<div className='overflow'>
<a href="" >
<img src= {props.imgsrc} alt='image1' className="card-img-top"></img>
</a>
</div>
</div>
)
}
export default Home;<file_sep>/src/components/card/Cards.js
import React,{ Component } from 'react'
import Home from './Home';
import img1 from '../../assets/1.jpg';
import img2 from '../../assets/2.jpg';
import img3 from '../../assets/3.jpg';
import img4 from '../../assets/4.jpg';
import img5 from '../../assets/5.jpg';
import img6 from '../../assets/6.jpg';
class Cards extends Component {
render(){
return(
<div>
<div className="container-fluid d-flex justify-content-center">
<div className="row">
<div className="col-md-6">
<Home imgsrc={img1}/>
</div>
<div className="col-md-6">
<Home imgsrc={img2}/>
</div>
</div>
</div>
<div className="container-fluid d-flex justify-content-center">
<div className="row">
<div className="col-md-6">
<Home imgsrc={img3}/>
</div>
<div className="col-md-6">
<Home imgsrc={img4}/>
</div>
</div>
</div>
<div className="container-fluid d-flex justify-content-center">
<div className="row">
<div className="col-md-6">
<Home imgsrc={img5}/>
</div>
<div className="col-md-6">
<Home imgsrc={img6}/>
</div>
</div>
</div>
</div>
);
}
}
export default Cards; | 39fc68e0b2e64ae6bec49843a6a7011a88a18fe9 | [
"JavaScript"
] | 2 | JavaScript | pavan-kanchupati/Img-upload | 87607927bdbe23eed7f81cae9c58e2835f241e76 | 69f01ff18188dedfee5ffa4d13fa22cb35a7763e |
refs/heads/master | <file_sep># require_relative 'bingauto'
# require 'sinatra'
get '/' do
@query = Query.last
erb :main
end
post '/' do
@query = get_random_query
@query = body_parser(@query, send_request(@query))
redirect back
end
<file_sep>require 'uri'
require 'net/http'
require 'json'
def get_info ## for command line program only
puts "What are you searching?"
request = gets.chomp
body_parser(request, send_request(request))
end
def get_random_query
File.readlines('./queries_list.txt').sample
end
def send_request(request_string)
request_string = request_string.split(" ").join("+") + " + " # doesn't appear to work
uri = URI('https://api.cognitive.microsoft.com/bing/v5.0/suggestions/')
uri.query = URI.encode_www_form({
'q' => "#{request_string}" # Request parameters
})
request = Net::HTTP::Get.new(uri.request_uri)
request['Ocp-Apim-Subscription-Key'] = ENV['KEY1'] # Request headers
# request['WebSearchOptions'] = 'DisableQueryAlterations' # doesn't appear to work
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
return http.request(request)
end
end
def body_parser(original_query, response)
suggestions = []
JSON.parse(response.body)["suggestionGroups"][0]['searchSuggestions'].each do |line|
p line['displayText']
line_text = line["displayText"].gsub('+', " ")
# enable for command line program
if line_text.match(/^#{original_query.chomp}\b.+/i)
suggestions << line_text
end
end
Query.create(statement: original_query, responses: suggestions)
# query.repsonses = suggestions
end
# enable to make command line program work
# get_info
<file_sep>class Query < ActiveRecord::Base
validates :statement, presence: true
serialize :responses, Array
end
<file_sep>source 'https://rubygems.org'
gem 'dotenv'
gem 'sinatra'
gem 'shotgun'
gem 'pry'
gem 'activerecord'
gem 'activesupport'
gem 'json'
gem 'pg'
gem 'rake'
<file_sep># but-its-not-google-feud | 067594e08df4357a9cfb5d2e7429e73cb7b681ac | [
"Markdown",
"Ruby"
] | 5 | Ruby | SeanMNorton/but-its-not-google-feud | 74c867e32162911442df0682eae3cd9206894a42 | 4f6299450cc673092d02ab0088adb33ad212c914 |
refs/heads/master | <repo_name>lxj0276/SuzhouNewPaper<file_sep>/readme.md
##说明
## 代码是刚学python时写的,很久都没维护,一直放在服务器上面,想要抓的关键字放到szrb.txt上
<file_sep>/crawlszrb.py
#coding=utf-8
'''
想要爬取的关键字列表存在 szrb.txt
'''
import re
import chardet
from datetime import datetime, timedelta
from time import strftime, sleep
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
import urllib,urllib2
import json
oriurl = 'http://epaper.subaonet.com/'#报纸的根地址
paperName_list = ['szrb', 'gswb', 'cssb']
# 网上很多,可以看说明
from_addr = 'your email address'
password = '<PASSWORD>'
to_addr = ["dst email list"]
smtp_server = 'server'
def getupdatetime():
html = getHtml(oriurl)
#print html
post_timetmp = re.findall(r'<td align="left" height="25" class="fz-14 pad-l-10 " >(.*?)</td>', html, re.S)
post_times = [] #所有报纸更新时间
for j in post_timetmp[:11]:
post_times.append(j.decode('u8')[0:4]+j.decode('u8')[5:7]+j.decode('u8')[8:10])
shortnames = re.findall(r'paperType=(.*?)" class="cor-red">',html,re.S)
result ={}
result['szrb'] = post_times[0]
result['gswb'] =post_times[1]
result['cssb'] = post_times[2]
return result
# 网上截取的代码
def getHtml(url):
try:
html_1 = urllib2.urlopen(url).read()
mychar = chardet.detect(html_1)
bianma = mychar['encoding']
if bianma == 'utf-8' or bianma == 'UTF-8':
#html=html.decode('utf-8','ignore').encode('utf-8')
html=html_1
return html
elif bianma == 'gbk' or bianma == 'GBK' :
html =html_1.decode('gbk','ignore').encode('utf-8')
return html
elif bianma == 'gb2312' or bianma=='GB2312':
html =html_1.decode('gb2312','ignore').encode('utf-8')
return html
except:
pass
# 获取报纸的页数
def getPages(html):
pages = re.findall(r'</a><a href="(.*?)".*?', html, re.S)
last_page_len = len(pages[-1])
if last_page_len==11:
return int(pages[-1][5:7])
if last_page_len==10:
return int(pages[-1][5:6])
if last_page_len==12:
return int(pages[-1][5:8])
#获取标题,内容
def getTitleUrl(html,paperName,timeToday_str,day_str):
result =[]
titles = re.findall(r'<Area shape="polygon" coords=.*?href=.*?title="(.*?)"', html, re.S)
# print titles
urls = re.findall(r'Area shape=.*?href="(.*?)"', html,re.S)
len_title = len(titles)
len_urls = len(urls)
if len_title==len_urls:
for i in range(0,len_title):
try:
url_in =oriurl + paperName+'/html/'+timeToday_str[0:7]+'/'+day_str +'/'+ urls[i]
# print url_in
content= getContent(url_in)
# content = getContent('http://epaper.subaonet.com/gswb/html/2015-12/13/content_326473.htm')
# print content
for each in open(r'szrb.txt'):
line = unicode(each.strip(), 'u8')
if content and line in content:
# print line
# print url_in
result.append((line, url_in))
except:
pass
return result
# 获取正文内容
def getContent(url):
html = getHtml(url)
try:
content = re.findall(r'<div class="article-content fontSizeSmall mar-lr-6" style="border-top:1px #d4d2d3 solid; line-height:28px; padding:10px; font-size:14px">(.*?)</div>.*?<div class',html,re.S)
return unicode(content[0], 'utf-8')
except:
return
def craw(paper_name,timeToday_str,day_str):
# url = oriurl + paperName+'/html/'+timeToday_str[0:7]+'/'+day_str +'/'+ 'node_'+'%s'%i+'.'+'htm'
result =[]
base_url = oriurl + paper_name+'/html/'+timeToday_str[0:7]+'/'+day_str +'/'+ 'node_'+'%s'%2+'.'+'htm'
print 'base_url:',base_url
base_html = getHtml(base_url)
# print 'base_html',base_html
page_nums = getPages(base_html)
for i in range(2,page_nums+1):
url = oriurl + paper_name+'/html/'+timeToday_str[0:7]+'/'+day_str +'/'+ 'node_'+'%s'%i+'.'+'htm'
html = getHtml(url)# 每个url去请求,得到html
try:
res = getTitleUrl(html,paper_name,timeToday_str,day_str)#每个html里得到标题,和每个新闻的url,然后拿到url后去寻找正文
result.append(res)
except:
pass
return result
###发送邮件
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(( \
Header(name, 'utf-8').encode(), \
addr.encode('utf-8') if isinstance(addr, unicode) else addr))
def sendemail(from_addr,to_addr_list,new_info,password,smtp_server):
msg = MIMEText(new_info, 'plain', 'utf-8')
msg['From'] = _format_addr(u'苏州报社<%s>' % from_addr)
msg['To'] = _format_addr(u'随便什么都可以 <%s>' % to_addr)
msg['Subject'] = Header(u'每日新闻', 'utf-8').encode()
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
for each in to_addr_list:
server.sendmail(from_addr, [each], msg.as_string())
server.quit()
# def main(time_post):
def main(timeToday_str,day_str):
result = []
# if time_post.get('szrb')==timetodaystr:
res_szrb = craw('szrb',timeToday_str,day_str)
for each in res_szrb:
if each :
result.append(each)
# if time_post.get('gswb')==timetodaystr:
res_gswb = craw('gswb',timeToday_str,day_str)
for each1 in res_gswb:
if each1 :
result.append(each1)
# if time_post.get('cssb')==timetodaystr:
res_cssb = craw('cssb',timeToday_str,day_str)
for each2 in res_cssb:
if each2 :
result.append(each2)
str = ' '
for name_urls in result:
for name_url in name_urls:
name = name_url[0]
url = name_url[1]
str = str+name.encode('u8')+":"+url+'\n'
return str
if __name__=='__main__':
# 9点55去爬取一次
dt = ['0955']
while 1:
if strftime("%H%M") in dt:
try:
timeToday = datetime.now()-timedelta(days=0) # 今天的时间
timeToday_str = timeToday.strftime("%Y-%m%d")
day_str = timeToday_str[7:9]
print timeToday_str,day_str
res_str = main(timeToday_str,day_str)
sendemail(from_addr, to_addr, res_str, password, smtp_server)
except:
# 如果9点55没爬到,一个小时后再去爬一次
sleep(3600)
timeToday = datetime.now()-timedelta(days=0) # 今天的时间
timeToday_str = timeToday.strftime("%Y-%m%d")
day_str = timeToday_str[7:9]
print timeToday_str,day_str
res_str = main(timeToday_str,day_str)
sendemail(from_addr, to_addr, res_str, password, smtp_server)
| 59cbd6f6e1375548944aae33875d24e5285a7263 | [
"Markdown",
"Python"
] | 2 | Markdown | lxj0276/SuzhouNewPaper | 1adc6b3f026689b86c3d7bdb3c692a6e46392bde | e01bb530a16df1960f44959d84ec2b31f370c0c9 |
refs/heads/master | <file_sep>Sinatra Classic Template
========================
This is a template for a basic Sinatra Classic application. It uses Bundler to manage dependencies and ERB for views.
The template includes a blank "style.css" stylesheet to include application-specific CSS and includes jQuery from the Google CDN.
Hope this gets you up and running fast!
Usage
-----
````Bash
bundle install
foreman start
````
Copyright
---
Copyright (c) 2012 <NAME>.
See [LICENSE][] for details.
[license]: https://github.com/brandonhilkert/sinatra-classic-template/blob/master/LICENSE
<file_sep>source 'https://rubygems.org'
ruby '2.1.4'
gem 'sinatra'
gem 'unicorn'
gem 'hipchat'
gem 'json'
gem 'rest-client'
<file_sep>require 'bundler'
Bundler.require
get '/' do
'OMG'
end
post '/' do
if params[:payload]
payload = JSON.parse(params[:payload])
# Only trigger message when a new PR is opened
if payload['action'] == 'opened'
send_to_dev_underground_in_hipchat(payload['pull_request'])
send_to_engineering_in_slack(payload['pull_request'])
elsif payload['action'] == 'closed' && payload['pull_request']['merged']
send_to_operations_talk_in_hipchat(payload['pull_request'])
send_to_operations_in_slack(payload['pull_request'])
end
end
end
def send_to_dev_underground_in_hipchat(pr)
msg = "#{pr['head']['repo']['name']}/#{pr['number']} - <a href='#{pr['html_url']}' >#{pr['title']}</a> (#{pr['user']['login']})"
hipchat_client['Engineering'].send('Github', msg)
end
def send_to_operations_talk_in_hipchat(pr)
msg = "<strong>MERGED</strong>: #{pr['head']['repo']['name']}/#{pr['number']} - <a href='#{pr['html_url']}' >#{pr['title']}</a> (#{pr['user']['login']})"
hipchat_client['Operations talk'].send('Github', msg)
end
def send_to_engineering_in_slack(pr)
text = "*#{pr['head']['repo']['name']}/#{pr['number']}* - <#{pr['html_url']}|#{pr['title']}> (#{pr['user']['login']})"
attachment = {
text: text,
color: "warning",
mrkdwn_in: ["text"],
}
RestClient.post ENV["SLACK_WEBHOOK_URL"], { attachments: [attachment] }.to_json, content_type: :json, accept: :json
end
def send_to_operations_in_slack(pr)
text = "*MERGED*: #{pr['head']['repo']['name']}/#{pr['number']} - <#{pr['html_url']}|#{pr['title']}> (#{pr['user']['login']})"
attachment = {
text: text,
color: "warning",
mrkdwn_in: ["text"],
}
RestClient.post ENV["SLACK_WEBHOOK_URL"], { attachments: [attachment], channel: "#operations" }.to_json, content_type: :json, accept: :json
end
def slack_attachment(text)
end
def hipchat_client
HipChat::Client.new(ENV['HIPCHAT_API'])
end
| a73d227df1e7f01c46249b8ab7e461597bc61397 | [
"Markdown",
"Ruby"
] | 3 | Markdown | brandonhilkert/pipeline_pr | 9f2f8f07832f46cd6a3ce6bec4617e3e91aae4e5 | 8000f5ab847525aff27bff68122565aca4bae00d |
refs/heads/master | <repo_name>SplittyDev/Tesseract<file_sep>/build
#!/usr/bin/env bash
if [ -d "$HOME/opt/cross/bin" ]; then
export PATH="$HOME/opt/cross/bin:$PATH"
else
echo "Couldn't find crosscompiler."
echo "Please install your crosscompiler to ~/opt/cross"
echo "The executables should be located at ~/opt/cross/bin"
echo "Running environment\\setup should build and install \
an i686-elf gcc crosscompiler autmatically."
exit
fi
# Delete current kernel iso
rm -f kernel.iso >/dev/null
# Copy makefile and linker script
# to source directory
cp kernel.ld src/kernel.ld
cp makefile src/makefile
# Navigate to source directory
cd src
# Build kernel
make
# Remove makefile and linker script
# from source directory
rm -f kernel.ld
rm -f makefile
# Delete object files
find . -name "*.o" -type f -delete
if [ -f "kernel" ]; then
# Move kernel to base directory
mv kernel ../kernel
else
echo -e "\e[31mBuilding your OS failed.\e[39m"
exit
fi
# Navigate back to base directory
cd ../
# Copy kernel to iso/boot directory
cp kernel iso/boot/kernel.bin
# Run Tesseract kernel
./run $*
<file_sep>/src/includes/stdlib/stdio.h
#ifndef __stdio__
#define __stdio__
#include <stdlib/stdarg.h>
void vsprintf (char *, const char *, va_list);
char *sprintf (char[], const char *, ...);
void printf (const char *, ...);
#endif
<file_sep>/src/stdlib/stdio.c
/* Copyright (C) 2014 - GruntTheDivine (<NAME>)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdlib/stdlib.h>
#include <stdlib/stdio.h>
#include <stdlib/stdarg.h>
#include <io/memory.h>
#include <io/terminal.h>
void vsprintf (char *dest, const char *format, va_list argp) {
int len = strlen (format);
int ptr = 0;
int i = 0;
char nbuf[16];
for (; i < len; i++) {
char c = *(format + i);
if (c == '%') {
char spec = format[++i];
switch (spec) {
case '%':
dest[ptr++] = '%';
break;
case 's':
strcpy ((char *)(dest + ptr), va_arg (argp, char *));
ptr = strlen (dest);
break;
case 'i':
case 'd':
itoa (nbuf, va_arg (argp, int));
strcpy ((char *)(dest + ptr), nbuf);
dest += strlen (nbuf);
break;
case 'x':
itox (nbuf, va_arg (argp, int));
strcpy ((char *)(dest + ptr), nbuf);
dest += strlen (nbuf);
break;
case 'p':
memset (nbuf, 0, 16);
memset (nbuf, '0', 8);
itox (nbuf, va_arg (argp, int));
strcpy ((char *)(dest + ptr), nbuf);
nbuf[8] = 0;
dest += 8;
break;
case 'c':
dest[ptr++] = va_arg (argp, int);
break;
}
} else {
dest[ptr++] = c;
}
}
}
char *sprintf (char buf[], const char *format, ...) {
va_list argp;
va_start (argp, format);
vsprintf (buf, format, argp);
va_end (argp);
return buf;
}
void printf (const char *format, ...) {
va_list argp;
va_start (argp, format);
char buf[512];
memset ((void *)buf, 0, 512);
vsprintf (buf, format, argp);
va_end (argp);
puts (buf);
}
<file_sep>/src/tesseract/drivers/vesa/fb.c
#include <drivers/vesa/fb.h>
#include <drivers/vesa/font.h>
#include <system/typedef.h>
int init_vesa (void) {
}
<file_sep>/run
#!/usr/bin/env bash
diskimage="tesseract.img"
# Build iso using grub-mkrescue
if which grub-mkrescue >/dev/null; then
grub-mkrescue -o kernel.iso iso
else
echo "grub-mkrescue couldn't be found."
echo "Please install it and run this file again."
echo "Running environment\\setup should install it automatically."
exit
fi
# Run kernel using qemu-system-x86_64
if which qemu-system-i386 >/dev/null; then
qemu-system-i386 -cdrom kernel.iso -hda $diskimage $*
else
echo "qemu-system-i386 couldn't be found."
echo "Please install it and run this file again."
echo "Running environment\\setup should install it automatically."
exit
fi
<file_sep>/src/includes/drivers/vesa/fb.h
#ifndef __fb__
#define __fb__
#include <system/typedef.h>
typedef struct fbinfo {
uint32_t resx;
uint32_t resy;
uint16_t pitch;
uint8_t fb_length;
int8_t *fb;
} fbinfo_t;
int init_vesa (void);
#endif
<file_sep>/src/tesseract/io/terminal.c
#include <system/typedef.h>
#include <io/terminal.h>
#include <io/ports.h>
#include <io/memory.h>
uint8_t x;
uint8_t y;
uint8_t foreground;
uint8_t background;
uintptr_t *ptr;
void putc_internal (uint8_t, bool_t);
void checkoverflow (void);
uint16_t makecolor (void);
uint16_t makeattrib (uint8_t);
size_t where (void);
void init_terminal (void) {
x = 0;
y = 0;
foreground = COLOR_WHITE;
background = COLOR_BLACK;
ptr = (uintptr_t *)TEXTMEMPTR;
}
void set_background_color (uint8_t color) {
background = color;
}
void set_foreground_color (uint8_t color) {
foreground = color;
}
void set_color (uint8_t bg, uint8_t fg) {
background = bg;
foreground = fg;
}
void reset_color () {
background = COLOR_BLACK;
foreground = COLOR_WHITE;
}
void putc_internal (const uint8_t chr, bool_t singleop) {
switch (chr) {
case KEY_BACKSPACE:
if (x > 0)
x--;
break;
case KEY_TAB:
x = (x + 8) & ~(8 - 1);
break;
case KEY_CARRIAGE_RETURN:
x = 0;
break;
case KEY_NEWLINE:
x = 0;
y++;
break;
default:
ptr[where ()] = makeattrib (chr);
x++;
break;
}
checkoverflow ();
scroll ();
if (singleop)
cursor ();
}
void putc (const uint8_t chr) {
putc_internal (chr, true);
}
void puts (const uint8_t *str) {
size_t i = 0;
while (str[i] != KEY_TERMINATE)
putc_internal (str[i++], false);
cursor ();
}
void scroll (void) {
if (y >= TERMINAL_HEIGHT) {
uint8_t tmp = y - TERMINAL_HEIGHT + 1;
uint8_t tmp2 = (TERMINAL_HEIGHT - tmp) * TERMINAL_WIDTH;
memcpy ((void *)ptr, (void *)(ptr + tmp * TERMINAL_WIDTH), tmp2 * 2);
memset ((void *)(ptr + tmp2), makeattrib (KEY_BLANK), TERMINAL_WIDTH);
y = TERMINAL_HEIGHT - 1;
}
}
void clear (void) {
size_t i = 0;
for (; i < TERMINAL_HEIGHT; i++)
memset ((void *)(ptr + i * TERMINAL_WIDTH), KEY_BLANK, TERMINAL_WIDTH);
x = 0;
y = 0;
cursor ();
}
void cursor (void) {
outb (0x3D4, 14);
outb (0x3D5, where () >> 8);
outb (0x3D4, 15);
outb (0x3D5, where ());
}
void checkoverflow (void) {
if (x > TERMINAL_WIDTH) {
x = 0;
y++;
}
}
size_t where (void) {
return y * TERMINAL_WIDTH + x;
}
uint16_t makecolor (void) {
return foreground | (background << 4);
}
uint16_t makeattrib (uint8_t chr) {
return chr | (makecolor () << 8);
}
<file_sep>/src/includes/io/ports.h
#ifndef __ports__
#define __ports__
#include <system/typedef.h>
static inline uint8_t inb (port_t port) {
uint8_t ret;
asm volatile ("inb %1, %0" : "=a" (ret) : "Nd" (port));
return ret;
}
static inline uint16_t inw (port_t port) {
uint16_t ret;
asm volatile ("inw %1, %0" : "=a" (ret) : "Nd" (port));
return ret;
}
static inline uint32_t inl (port_t port) {
uint32_t ret;
asm volatile ("inl %1, %0" : "=a" (ret) : "Nd" (port));
return ret;
}
static inline void outb (port_t port, uint8_t value) {
asm volatile ("outb %0, %1" : : "a" (value), "Nd" (port));
}
static inline void outw (port_t port, uint16_t value) {
asm volatile ("outw %0, %1" : : "a" (value), "Nd" (port));
}
static inline void outl (port_t port, uint32_t value) {
asm volatile ("outl %0, %1" : : "a" (value), "Nd" (port));
}
#endif
<file_sep>/src/includes/io/terminal.h
#ifndef __terminal__
#define __terminal__
#include <system/typedef.h>
#define TEXTMEMPTR 0xB8000
#define TERMINAL_WIDTH 80
#define TERMINAL_HEIGHT 25
#define BRIGHT 0x8
#define COLOR_BLACK 0x0
#define COLOR_BLUE 0x1
#define COLOR_GREEN 0x2
#define COLOR_CYAN 0x3
#define COLOR_RED 0x4
#define COLOR_MAGENTA 0x5
#define COLOR_BROWN 0x6
#define COLOR_LIGHT_GRAY 0x7
#define COLOR_DARK_GRAY 0x0 + BRIGHT
#define COLOR_LIGHT_BLUE 0x1 + BRIGHT
#define COLOR_LIGHT_GREEN 0x2 + BRIGHT
#define COLOR_LIGHT_CYAN 0x3 + BRIGHT
#define COLOR_LIGHT_RED 0x4 + BRIGHT
#define COLOR_LIGHT_MAGENTA 0x5 + BRIGHT
#define COLOR_YELLOW 0x6 + BRIGHT
#define COLOR_WHITE 0x7 + BRIGHT
#define KEY_BACKSPACE '\b'
#define KEY_TAB '\t'
#define KEY_CARRIAGE_RETURN '\r'
#define KEY_NEWLINE '\n'
#define KEY_TERMINATE '\0'
#define KEY_BLANK ' '
void init_terminal (void);
void putc (const uint8_t);
void puts (const uint8_t *);
void scroll (void);
void cursor (void);
void clear (void);
void set_background_color (uint8_t);
void set_foreground_color (uint8_t);
void set_color (uint8_t, uint8_t);
#endif
<file_sep>/src/tesseract/hardware/idt.c
#include <hardware/idt.h>
#include <hardware/isr.h>
#include <system/system.h>
#include <system/typedef.h>
#include <io/memory.h>
#include <io/ports.h>
#include <io/terminal.h>
#include <stdlib/stdio.h>
struct {
uint16_t limit;
void *pointer;
} __attribute__((packed)) idt_ptr = {
.limit = (sizeof (struct idt_entry) * 256) - 1,
.pointer = &idt,
};
void idt_load (void);
void idt_set_gate(uint8_t, uint32_t, uint16_t, uint8_t);
void idt_handle_irq (stackframe_t *);
void idt_handle_syscall (stackframe_t *);
void idt_handle_general (stackframe_t *);
void idt_handle_exception (stackframe_t *);
int init_idt (void) {
// Clear IDT
memset ((void *)&idt, 0, sizeof(struct idt_entry) * 256);
// Exceptions
idt_set_gate (0x00, (unsigned) isr0, 0x08, 0x8E);
idt_set_gate (0x01, (unsigned) isr1, 0x08, 0x8E);
idt_set_gate (0x02, (unsigned) isr2, 0x08, 0x8E);
idt_set_gate (0x03, (unsigned) isr3, 0x08, 0x8E);
idt_set_gate (0x04, (unsigned) isr4, 0x08, 0x8E);
idt_set_gate (0x05, (unsigned) isr5, 0x08, 0x8E);
idt_set_gate (0x06, (unsigned) isr6, 0x08, 0x8E);
idt_set_gate (0x07, (unsigned) isr7, 0x08, 0x8E);
idt_set_gate (0x08, (unsigned) exc8, 0x08, 0x8E);
idt_set_gate (0x09, (unsigned) isr9, 0x08, 0x8E);
idt_set_gate (0x0A, (unsigned) exc10, 0x08, 0x8E);
idt_set_gate (0x0B, (unsigned) exc11, 0x08, 0x8E);
idt_set_gate (0x0C, (unsigned) exc12, 0x08, 0x8E);
idt_set_gate (0x0D, (unsigned) exc13, 0x08, 0x8E);
idt_set_gate (0x0E, (unsigned) exc14, 0x08, 0x8E);
idt_set_gate (0x0F, (unsigned) isr15, 0x08, 0x8E);
idt_set_gate (0x10, (unsigned) isr16, 0x08, 0x8E);
idt_set_gate (0x11, (unsigned) isr17, 0x08, 0x8E);
idt_set_gate (0x12, (unsigned) isr18, 0x08, 0x8E);
idt_set_gate (0x13, (unsigned) isr19, 0x08, 0x8E);
idt_set_gate (0x14, (unsigned) isr20, 0x08, 0x8E);
idt_set_gate (0x15, (unsigned) isr21, 0x08, 0x8E);
idt_set_gate (0x16, (unsigned) isr22, 0x08, 0x8E);
idt_set_gate (0x17, (unsigned) isr23, 0x08, 0x8E);
idt_set_gate (0x18, (unsigned) isr24, 0x08, 0x8E);
idt_set_gate (0x19, (unsigned) isr25, 0x08, 0x8E);
idt_set_gate (0x1A, (unsigned) isr26, 0x08, 0x8E);
idt_set_gate (0x1B, (unsigned) isr27, 0x08, 0x8E);
idt_set_gate (0x1C, (unsigned) isr28, 0x08, 0x8E);
idt_set_gate (0x1D, (unsigned) isr29, 0x08, 0x8E);
idt_set_gate (0x1E, (unsigned) isr30, 0x08, 0x8E);
idt_set_gate (0x1F, (unsigned) isr31, 0x08, 0x8E);
// IRQs
idt_set_gate (0x20, (unsigned) irq0, 0x08, 0x8E);
idt_set_gate (0x21, (unsigned) irq1, 0x08, 0x8E);
idt_set_gate (0x22, (unsigned) irq2, 0x08, 0x8E);
idt_set_gate (0x23, (unsigned) irq3, 0x08, 0x8E);
idt_set_gate (0x24, (unsigned) irq4, 0x08, 0x8E);
idt_set_gate (0x25, (unsigned) irq5, 0x08, 0x8E);
idt_set_gate (0x26, (unsigned) irq6, 0x08, 0x8E);
idt_set_gate (0x27, (unsigned) irq7, 0x08, 0x8E);
idt_set_gate (0x28, (unsigned) irq8, 0x08, 0x8E);
idt_set_gate (0x29, (unsigned) irq9, 0x08, 0x8E);
idt_set_gate (0x2A, (unsigned) irq10, 0x08, 0x8E);
idt_set_gate (0x2B, (unsigned) irq11, 0x08, 0x8E);
idt_set_gate (0x2C, (unsigned) irq12, 0x08, 0x8E);
idt_set_gate (0x2D, (unsigned) irq13, 0x08, 0x8E);
idt_set_gate (0x2E, (unsigned) irq14, 0x08, 0x8E);
idt_set_gate (0x2F, (unsigned) irq15, 0x08, 0x8E);
// Load IDT
idt_load ();
return 1;
}
void idt_set_gate (uint8_t num, uint32_t base, uint16_t sel, uint8_t flags) {
idt[num].base_lo = base & 0xFFFF;
idt[num].base_hi = (base >> 16) & 0xFFFF;
idt[num].sel = sel;
idt[num].zero = 0;
idt[num].flags = flags;
}
void idt_load (void) {
asm volatile ("lidt %0" : : "m" (idt_ptr));
}
void *irq_handlers[16] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
void idt_install_handler (int8_t irq, void (*handler)(stackframe_t *frame)) {
irq_handlers[irq] = handler;
puts ("Installed IRQ handler\n");
//uint8_t buf[13];
//puts (itoa (irq, buf));
}
void idt_uninstall_handler (int8_t irq) {
irq_handlers[irq] = 0;
}
void idt_handle_exception (stackframe_t *frame) {
// Print exception message
set_foreground_color (COLOR_RED);
printf ("\nEXCEPTION: %s\n", exception_messages[frame->intr]);
reset_color ();
printf ("[CPU state]\n");
printf ("GS : %x\n", frame->gs);
printf ("FS : %x\n", frame->fs);
printf ("ES : %x\n", frame->es);
printf ("DS : %x\n", frame->ds);
printf ("EDI : %x\n", frame->edi);
printf ("ESI : %x\n", frame->esi);
printf ("EBP : %x\n", frame->ebp);
printf ("ESP : %x\n", frame->esp);
printf ("EBX : %x\n", frame->ebx);
printf ("EDX : %x\n", frame->edx);
printf ("ECX : %x\n", frame->ecx);
printf ("EAX : %x\n", frame->eax);
printf ("EIP : %x\n", frame->eip);
printf ("CS : %x\n", frame->cs);
printf ("SS : %x\n", frame->ss);
printf ("EFLAGS : %x\n", frame->eflags);
printf ("USERESP: %x\n", frame->useresp);
// Halt
while (true) {
asm ("cli; hlt");
}
}
void idt_handle_irq (stackframe_t *frame) {
// Blank IRQ handler
void (*handler)(stackframe_t *frame);
// Set our handler to the actual IRQ handler
handler = irq_handlers[frame->intr - 32];
// Call the handler
if (handler)
handler (frame);
}
void idt_handle_syscall (stackframe_t *frame) {
}
void idt_handle_general (stackframe_t *frame) {
// Exceptions
if (frame->intr <= 0x1F) {
// Call exception handler
idt_handle_exception (frame);
}
// IRQs
if (frame->intr >= 0x20 && frame->intr <= 0x2F) {
// Call IRQ handler
idt_handle_irq (frame);
// Send EOI to slave interrupt controller
if (frame->intr >= 0x28) {
outb (0xA0, 0x20);
}
// Send EOI to master interrupt controller
outb (0x20, 0x20);
}
}
<file_sep>/src/includes/hardware/idt.h
#ifndef __idt__
#define __idt__
#include <system/system.h>
#include <system/typedef.h>
#define IDT_ENTRIES 256
struct idt_entry
{
unsigned short base_lo;
unsigned short sel;
unsigned char zero;
unsigned char flags;
unsigned short base_hi;
} __attribute__((packed));
struct idt_entry idt[IDT_ENTRIES];
int init_idt (void);
void idt_install_handler (int8_t, void (*)(stackframe_t *));
void idt_uninstall_handler (int8_t);
#endif
<file_sep>/src/includes/io/memory.h
#ifndef __memory__
#define __memory__
#include <system/typedef.h>
static inline void *memcpy (void *dest, void *src, size_t size) {
asm volatile ("cld");
asm volatile ("rep movsb" : "+c" (size), "+S" (src), "+D" (dest) :: "memory");
}
static inline void *memset (void *b, int val, size_t size) {
asm volatile ("cld");
asm volatile ("rep stosb" : "+c" (size), "+D" (b) : "a" (val) : "memory");
return b;
}
static inline uintptr_t *memsetw (uintptr_t *ptr, uint8_t val, size_t size) {
int i = 0;
for (; i < size; ++i) {
ptr[i] = val;
}
return ptr;
}
/*
static inline void *memset (void *dest, uint8_t value, size_t size) {
if (size) {
int8_t *d = dest;
do {
*d++ = value;
} while (--size);
}
return dest;
}
static inline void *memsetw (void *dest, uint16_t value, size_t size) {
if (size) {
int8_t *d = dest;
do {
*d++ = value;
} while (--size);
}
return dest;
}
static inline uintptr_t *memcpy (
uintptr_t *dest, uintptr_t *src, size_t count) {
size_t i = 0;
for (; i < count; i++)
dest[i] = src[i];
return dest;
}
*/
#endif
<file_sep>/environment/setup
#!/usr/bin/env bash
function main {
check_root
check_pm
prepare_make
update_packages
install_dependencies_apt
install_dependencies_yum
build_qemu
check_cc
create_kernel_env
echo "This should be all set up now."
exit
}
function check_root {
# Check if we are root
if [ "$(whoami)" != "root" ]; then
echo "Please run this script as root."
exit
else
echo "Kernel toolchain builder"
fi
}
function check_pm {
if which apt-get >/dev/null; then
pmsig="apt"
pm="apt-get -q -y install"
export DEBIAN_FRONTEND=noninteractive
elif which yum >/dev/null; then
pmsig="yum"
pm="yum -q -y install"
echo "Support for yum isn't finished."
echo "There is a chance that qemu, binutils \
and gcc won't compile."
echo "In this case, please resolve the dependencies manually \
and run this script again."
else
echo "Your package manager is not supported."
echo "Please consider using apt or yum."
exit
fi
echo "Using $pmsig as package manager."
}
function prepare_make {
processor_cores=$(grep -c ^processor /proc/cpuinfo)
echo "Found $processor_cores processor cores."
make_threads=$((processor_cores + 1))
echo "Using $make_threads make threads."
}
function install_apt {
if [ "$pmsig" == "apt" ]; then
echo "[Installing] $*"
$pm $* >/dev/null
fi
}
function install_yum {
if [ "$pmsig" == "yum" ]; then
echo "[Installing] $*"
$pm $* >/dev/null
fi
}
function update_packages {
echo "Updating package index..."
case "$pm" in
"apt")
apt-get -qq -y update >/dev/null
;;
esac
}
function install_dependencies_apt {
# required
install_apt build-essential
install_apt grub-common
install_apt xorriso
install_apt wget
install_apt tar
# qemu required
install_apt git libglib2.0-dev
install_apt libglib2.0-dev libfdt-dev
install_apt libpixman-1-dev zlib1g-dev
# qemu recommended
install_apt libaio-dev libbluetooth-dev
install_apt libbrlapi-dev libbz2-dev
install_apt libcap-dev libcap-ng-dev
install_apt libcurl4-gnutls-dev libgtk-3-dev
install_apt libibverbs-dev libjpeg8-dev
install_apt libncurses5-dev libnuma-dev
install_apt librbd-dev librdmacm-dev
install_apt libsasl2-dev libsdl1.2-dev
install_apt libseccomp-dev libsnappy-dev
install_apt libssh2-1-dev
install_apt libvde-dev libvdeplug-dev
install_apt libvte-2.90-dev libxen-dev
install_apt liblzo2-dev
install_apt valgrind xfslibs-dev
install_apt libnfs-dev libiscsi-dev
# gcc required
install_apt libgmp10 libgmp-dev
install_apt libmpfr4 libmpfr-dev
install_apt libmpc3 libmpc-dev
}
function install_dependencies_yum {
#required
install_yum gcc gcc-c++ kernel_devel
install_yum grub2
install_yum xorriso
install_yum wget
install_yum tar
#qemu required
install_yum git
install_yum libfdt-devel
#qemu recommended
install_yum gtk2-devel
install_yum vte-devel
#gcc required
}
function build_qemu {
echo "[Checking] qemu-system-i386"
if which qemu-system-i386 >/dev/null; then
echo "[OK] qemu-system-i386"
return
fi
set qemu="qemu-2.3.0-rc0"
echo "Downlading $qemu..."
wget "http://wiki.qemu-project.org/download/$qemu.tar.bz2"
echo "Unpacking $qemu"
tar xfvj "$qemu.tar.bz2"
echo "Building qemu i386-softmmu..."
echo "This can take a long time on some systems..."
mkdir build-qemu
cd build-qemu
../$qemu/configure --target-list="i386-softmmu"
make -j $make_threads
make -j $make_threads install
cd ../
}
function prepare_toolchain {
export PREFIX="$HOME/opt/cross"
export TARGET=i686-elf
export PATH="$PREFIX/bin:$PATH"
}
function build_binutils {
set binutils="binutils-2.25"
echo "Downloading $binutils..."
wget "https://ftp.gnu.org/gnu/binutils/$binutils.tar.bz2"
echo "Unpacking $binutils"
tar xfvj "$binutils.tar.bz2"
echo "Building binutils..."
binutils_switches="--with-sysroot --disable-nls --disable-werror"
mkdir build-binutils
cd build-binutils
../$binutils/configure --target=$TARGET --prefix="$PREFIX" $binutils_switches
make -j $make_threads
make -j $make_threads install
cd ../
}
function check_cc {
echo "Looking for cross-compiler in ~/opt/cross"
if [ -d "$HOME/opt/cross/bin" ]; then
echo "[OK] Cross-compiler"
echo "Done!"
else
echo "A gcc cross-compiler targeting i686-elf will be built."
echo "This can take a long time on some systems."
prepare_toolchain
build_binutils
build_gcc
fi
}
function build_gcc {
set gcc="gcc-4.8.2"
echo "Downloading $gcc..."
wget "https://ftp.gnu.org/gnu/gcc/gcc-4.8.2/$gcc.tar.bz2"
echo "Unpacking $gcc"
tar xfvj "$gcc.tar.bz2"
echo "Building gcc with c and c++ support..."
gcc_switches="--disable-nls --enable-languages=c,c++ --without-headers"
mkdir build-gcc
cd build-gcc
../$gcc/configure --target=$TARGET --prefix="$PREFIX" $gcc_switches
make -j $make_threads all-gcc
make -j $make_threads all-target-libgcc
make -j $make_threads install-gcc
make -j $make_threads install-target-libgcc
cd ../
echo "Testing if everything is working..."
gcc_version=$($HOME/opt/cross/bin/$TARGET-gcc --version)
binutils_version=$($HOME/opt/cross/bin/$TARGET-ld --version)
echo "You should see the gcc-version now: $gcc_version"
echo "You should see the binutils-version now: $binutils_version"
}
function create_kernel_env {
echo "Creating kernel directories"
cd ../
if [ ! -d "iso" ]; then mkdir -m 777 iso; fi
if [ ! -d "iso/boot" ]; then mkdir -m 777 iso/boot; fi
if [ ! -d "iso/boot/grub" ]; then mkdir -m 777 iso/boot/grub; fi
if [ ! -d "src" ]; then mkdir -m 777 src; fi
if [ ! -d "src/includes" ]; then mkdir -m 777 src/includes; fi
if [ ! -f "src/boot.S" ]; then
echo "Creating boot.S in src/"
touch src/boot.S
chmod 777 src/boot.S
fi
if [ ! -f "src/kmain.c" ]; then
echo "Creating kmain.c in src/"
touch src/kmain.c
chmod 777 src/kmain.c
fi
if [ ! -f "iso/boot/grub/grub.cfg" ]; then
echo "Creating grub.cgf in iso/boot/grub/"
touch iso/boot/grub/grub.cfg
chmod 777 iso/boot/grub/grub.cfg
echo -e "menuentry \"MyOS\" {" >iso/boot/grub/grub.cfg
echo -e "\tmultiboot /boot/kernel.bin" >>iso/boot/grub/grub.cfg
echo -e "}" >> iso/boot/grub/grub.cfg
fi
}
main
<file_sep>/src/tesseract/hardware/rtc.c
#include <system/typedef.h>
#include <hardware/rtc.h>
#include <hardware/cmos.h>
#include <io/ports.h>
enum {
rtc_reg_second = 0x00,
rtc_reg_minute = 0x02,
rtc_reg_hour = 0x04,
rtc_reg_dayofweek = 0x06,
rtc_reg_dayofmonth = 0x07,
rtc_reg_month = 0x08,
rtc_reg_year = 0x09,
rtc_reg_century = 0x00, // 0x32
};
int bcdtoi (uint32_t n, const uint8_t *data) {
uint32_t result = 0;
uint32_t i = 0;
for (; i < n; i++) {
result *= 100;
result += (data[i] >> 4) * 10;
result += data[i] & 0x0F;
}
return result;
}
#define bcdtoib(x) ((x / 16) * 10 + (x & 0xF))
int init_rtc (void) {
cmos_write (0x0B, cmos_read (0x0B) | 0x40); // IRQ 8
cmos_write (0x0A, (cmos_read (0x0A) & 0xF0) | 0x0F); // 500ms
}
uint8_t readregb (uint16_t dump[128], uint8_t pos) {
uint8_t tmp;
tmp = bcdtoib (dump[pos]);
return tmp;
}
uint16_t readregs (uint16_t dump[128], uint8_t pos) {
uint16_t tmp;
tmp = bcdtoib (dump[pos]);
return tmp;
}
uint32_t rtc_get_full_year (uint16_t dump[128]) {
uint32_t Y = readregs (dump, rtc_reg_year);
Y += (KERNEL_YEAR / 100) * 100;
if (Y < KERNEL_YEAR)
Y += 100;
return Y;
}
date_t rtc_get_date (void) {
uint16_t dump[128];
cmos_dump (dump);
date_t rtcdate = {
readregs (dump, rtc_reg_dayofmonth),
readregs (dump, rtc_reg_dayofweek),
readregs (dump, rtc_reg_month),
rtc_get_full_year (dump)
};
return rtcdate;
}
time_t rtc_get_time (void) {
uint16_t dump[128];
cmos_dump (dump);
time_t rtctime = {
readregs (dump, rtc_reg_second),
readregs (dump, rtc_reg_minute),
readregs (dump, rtc_reg_hour)
};
return rtctime;
}
<file_sep>/src/includes/system/kheap.h
#ifndef __kheap__
#define __kheap__
#include <system/typedef.h>
typedef struct kheapblock {
struct kheapblock *next;
uint32_t top;
uint32_t max;
uintptr_t size;
} kheapblock_t;
typedef struct kheap {
kheapblock_t *fblock;
uint32_t bsize;
} kheap_t;
int init_kheap (kheap_t *, uint32_t);
int kheap_addblock (kheap_t *, uint32_t, uint32_t);
void *kheap_alloc (kheap_t *, uint32_t);
void kheap_free (kheap_t *, void *);
#endif
<file_sep>/src/includes/system/system.h
#ifndef __system__
#define __system__
#include <system/typedef.h>
#define IRQ_ON asm volatile ("sti")
#define IRQ_OFF asm volatile ("cli")
typedef struct stackframe {
uint32_t gs, fs, es, ds;
uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax;
uint32_t intr, error;
uint32_t eip, cs, eflags, useresp, ss;
} stackframe_t;
static const uint8_t *exception_messages[] =
{
"DIVIDE BY ZERO EXCEPTION\n", // 0x00
"DEBUG EXCEPTION\n", // 0x01
"NON MASKABLE INTERRUPT EXCEPTION\n", // 0x02
"BREAKPOINT EXCEPTION\n", // 0x03
"INTO DETECTED OVERFLOW EXCEPTION\n", // 0x04
"OUT OF BOUNDS EXCEPTION\n", // 0x05
"INVALID OPCODE EXCEPTION\n", // 0x06
"NO COPROCESSOR EXCEPTION\n", // 0x07
"DOUBLE FAULT EXCEPTION\n", // 0x08
"COPROCESSOR SEGMENT OVERRUN EXCEPTION\n", // 0x09
"BAD TSS EXCEPTION\n", // 0x0A
"SEGMENT NOT PRESENT EXCEPTION\n", // 0x0B
"STACK FAULT EXCEPTION\n", // 0x0C
"GENERAL PROTECTION FAULT EXCEPTION\n", // 0x0D
"PAGE FAULT EXCEPTION\n", // 0x0E
"UNKNOWN INTERRUPT EXCEPTION\n", // 0x0F
"COPROCESSOR FAULT EXCEPTION\n", // 0x10
"ALIGNMENT CHECK EXCEPTION\n", // 0x11
"MACHINE CHECK EXCEPTION\n", // 0x12
};
#endif
<file_sep>/src/stdlib/stdlib.c
/* Copyright (C) 2014 - GruntTheDivine (<NAME>)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdlib/stdlib.h>
int strlen(const char *str)
{
int i = 0;
while (str[i] != 0) i++;
return i;
}
char *strrchr(const char *str, char ch)
{
int dlen = strlen(str);
int i = 0;
for (; i < dlen; i++)
if (str[i] == ch)
return (char *)(str + i);
return NULL;
}
char *strlchr(const char *str, char ch)
{
int dlen = strlen(str);
char *rstr = NULL;
int i = 0;
for (; i < dlen; i++)
if (str[i] == ch)
rstr = (char *)(str + i);
return rstr;
}
int strindx(const char *str, char ch)
{
int dlen = strlen(str);
char *rstr = NULL;
int i = 0;
for (; i < dlen; i++)
if (str[i] == ch)
return i;
return -1;
}
char *strcpy(char *dest, const char *src)
{
size_t len = strlen(src);
int i = 0;
for (; i < len; i = i + 1)
dest[i] = src[i];
dest[len] = 0;
return dest;
}
char *strncpy(char *dest, const char *src, size_t len)
{
int i = 0;
for (; i < len && dest[i] != NULL; i++)
dest[i] = src[i];
return dest;
}
int strncmp(const char *str1, const char *str2, size_t len)
{
int i = 0;
for (; i < len; i++)
if (str1[i] != str2[i])
return -1;
return 0;
}
int strcmp(const char *str1, const char *str2)
{
if (strlen(str1) > strlen(str2))
return strncmp(str1, str2, strlen(str1));
else
return strncmp(str1, str2, strlen(str2));
}
char *strcat(char *dest, const char *dat)
{
int dlen = strlen(dat);
strncat(dest, dat, dlen);
return dest;
}
char *strncat(char *dest, const char *dat, size_t dlen)
{
int pos = 0;
while (dest[pos] != 0) pos++;
char *new_str = (char *)(dest + pos);
int i = 0;
for (; i < dlen; i = i + 1)
new_str[i] = dat[i];
return dest;
}
void reverse(char *str)
{
int start = 0;
int end = strlen(str) - 1;
while (start < end) {
char c1 = *(str + start);
char c2 = *(str + end);
*(str + start) = c2;
*(str + end) = c1;
start++;
end--;
}
}
void itoa(char *s, int i)
{
int d;
int p = 0;
do {
d = i % 10;
i = (i - d) / 10;
s[p] = (char)d + 48;
p = p + 1;
} while (i > 0);
s[p] = 0;
reverse(s);
}
int atoi(char *s)
{
int final = 0;
int mul = 1;
int len = strlen(s);
reverse(s);
int i = 0;
for (; i < len; i++) {
char b = s[i];
int RealDigit = (int)b - 48;
final = (RealDigit * mul) + final;
mul = mul * 10;
}
return final;
}
int strtol(char *s, int base)
{
int final = 0;
int mul = 1;
int len = strlen(s);
//reverse(s);
int i = len - 1;
for (; i >= 0; i--) {
char b = s[i];
int RealDigit;
if (b >= 'a')
RealDigit = 10 + ((int)b - 'a');
else
RealDigit = (int)b - 48;
final = (RealDigit * mul) + final;
mul = mul * base;
}
return final;
}
void itox(char *s, unsigned int i)
{
int d;
int p = 0;
do {
d = i % 16;
i = (i - d) / 16;
s[p++] = (char)d + (d < 10 ? 48 : 'A' - 10);
} while (i > 0);
reverse(s);
s[p] = 0;
}
<file_sep>/src/includes/fs/vfs.h
#ifndef __vfs__
#define __vfs__
#endif
<file_sep>/src/includes/system/typedef.h
#ifndef __typedef__
#define __typedef__
#define true 1
#define false 0
typedef char int8_t;
typedef short int16_t;
typedef long int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
typedef unsigned long long uint64_t;
typedef unsigned char bool_t;
typedef unsigned short size_t;
typedef unsigned short port_t;
typedef unsigned short uintptr_t;
typedef unsigned long uintlptr_t;
#endif
<file_sep>/src/tesseract/hardware/pic.c
#include <hardware/pic.h>
#include <io/ports.h>
void pic_remap_master (void);
void pic_remap_slave (void);
void pic_unmask (void);
int init_pic (void) {
pic_remap_master ();
pic_remap_slave ();
pic_unmask ();
return 1;
}
void pic_remap_master (void) {
outb (0x20, 0x11);
outb (0x21, 0x20);
outb (0x21, 0x04);
outb (0x21, 0x01);
}
void pic_remap_slave (void) {
outb (0xA0, 0x11);
outb (0xA1, 0x28);
outb (0xA1, 0x02);
outb (0xA1, 0x01);
}
void pic_unmask (void) {
outb (0x21, 0x0);
outb (0xA1, 0x0);
}
<file_sep>/src/includes/hardware/isr.h
#ifndef __isrs__
#define __isrs__
// Exceptions
extern void isr0 (void);
extern void isr1 (void);
extern void isr2 (void);
extern void isr3 (void);
extern void isr4 (void);
extern void isr5 (void);
extern void isr6 (void);
extern void isr7 (void);
extern void exc8 (void);
extern void isr9 (void);
extern void exc10 (void);
extern void exc11 (void);
extern void exc12 (void);
extern void exc13 (void);
extern void exc14 (void);
extern void isr15 (void);
extern void isr16 (void);
extern void isr17 (void);
extern void isr18 (void);
extern void isr19 (void);
extern void isr20 (void);
extern void isr21 (void);
extern void isr22 (void);
extern void isr23 (void);
extern void isr24 (void);
extern void isr25 (void);
extern void isr26 (void);
extern void isr27 (void);
extern void isr28 (void);
extern void isr29 (void);
extern void isr30 (void);
extern void isr31 (void);
// IRQs
extern void irq0 (void);
extern void irq1 (void);
extern void irq2 (void);
extern void irq3 (void);
extern void irq4 (void);
extern void irq5 (void);
extern void irq6 (void);
extern void irq7 (void);
extern void irq8 (void);
extern void irq9 (void);
extern void irq10 (void);
extern void irq11 (void);
extern void irq12 (void);
extern void irq13 (void);
extern void irq14 (void);
extern void irq15 (void);
#endif
<file_sep>/src/includes/hardware/rtc.h
#ifndef __rtc__
#define __rtc__
#define KERNEL_YEAR 2015
static const uint8_t *MONTH[] = {
"January",
"February",
"March",
"April",
"May",
"Juny",
"July",
"August",
"September",
"October",
"November",
"December"
};
static const uint8_t *DAY[] = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
typedef struct date {
uint16_t d;
uint16_t dow;
uint16_t M;
uint32_t Y;
} date_t;
typedef struct time {
uint16_t s;
uint16_t m;
uint16_t h;
} time_t;
int init_rtc (void);
date_t rtc_get_date (void);
time_t rtc_get_time (void);
#endif
<file_sep>/src/tesseract/kmain.c
#include <system/multiboot.h>
#include <system/typedef.h>
#include <system/system.h>
#include <system/kheap.h>
#include <io/terminal.h>
#include <hardware/gdt.h>
#include <hardware/pic.h>
#include <hardware/idt.h>
#include <hardware/rtc.h>
void main (void);
void invoke (char *msg, int (*func)()) {
printf ("%s %s\n", msg, func () ? "OK" : "FAIL");
}
void init (multiboot_info_t *mbootinfo) {
void *kheap = (uint32_t *)(mbootinfo->mods_addr + 4);
IRQ_OFF;
init_kheap (kheap, 4096);
init_terminal ();
init_gdt ();
init_pic ();
init_idt ();
init_rtc ();
printf ("Heap, GDT, PIC, IDT and RTC initialized.\n");
printf ("Gathering video information form multiboot header...\n");
printf ("Framebuffer width: %d\n", mbootinfo->framebuffer_width);
printf ("Framebuffer height: %d\n", mbootinfo->framebuffer_height);
IRQ_ON;
main ();
}
void main (void) {
printf ("Tesseract booted.\n");
date_t date = rtc_get_date ();
printf ("%s, the %dth of %s %d", DAY[date.dow-1], date.d, MONTH[date.M-1], date.Y);
while (true) {
}
}
<file_sep>/src/tesseract/system/kheap.c
#include <stdlib/stdio.h>
#include <system/kheap.h>
#include <system/typedef.h>
int init_kheap (kheap_t *heap, uint32_t bsize) {
heap->fblock = 0;
heap->bsize = bsize;
return 1;
}
int kheap_addblock (kheap_t *heap, uint32_t addr, uint32_t size) {
kheapblock_t *b;
uint32_t x;
uint32_t *stack;
uint32_t stacksz;
uint32_t slotres;
b = (kheapblock_t *)addr;
b->next = heap->fblock;
heap->fblock = b;
b->size = size;
size = size - sizeof(kheapblock_t);
b->max = size / (heap->bsize);
stacksz = b->max * 4;
uint32_t tmp = stacksz / heap->bsize;
slotres = tmp * heap->bsize < stacksz ? tmp + 1 : tmp;
b->top = slotres;
stack = (uint32_t *)&b[1];
for (x = slotres; x < b->max; ++x)
stack[x] = x * heap->bsize;
return 1;
}
void *kheap_alloc (kheap_t *heap, uint32_t size) {
kheapblock_t *b;
uint32_t ptr;
uint32_t *stack;
if (size > heap->bsize)
return 0;
for (b = heap->fblock; b; b = b->next) {
if (b->top != b->max) {
stack = (uint32_t *)&b[1];
ptr = stack[b->top++];
ptr = (uint32_t)&b[1] + ptr;
return (void *)ptr;
}
}
return 0;
}
void kheap_free (kheap_t *heap, void *dest) {
kheapblock_t *b;
uint32_t ptr;
uint32_t *stack;
ptr = (uint32_t)dest;
for (b = heap->fblock; b; b = b->next) {
if (ptr > (uint32_t)b && ptr < ((uint32_t)b + b->size))
break;
}
if (!b)
printf ("\n*** [FATAL] Heap corrupted!\n");
return;
stack = (uint32_t *)&b[1];
stack[--b->top] = ptr - (uint32_t)&b[1];
return;
}
<file_sep>/src/includes/hardware/pic.h
#ifndef __pic__
#define __pic__
int init_pic (void);
#endif
<file_sep>/src/includes/stdlib/stdlib.h
#ifndef __stdlib__
#define __stdlib__
#include <system/typedef.h>
#define NULL 0
int strlen(const char *);
char *strrchr(const char *, char);
char *strlchr(const char *, char);
int strindx(const char *, char);
char *strcpy(char *, const char *);
char *strncpy(char *, const char *, size_t);
int strncmp(const char *, const char *, size_t);
int strcmp(const char *, const char *);
char *strcat(char *, const char *);
char *strncat(char *, const char *, size_t);
void reverse(char *);
void itoa(char *, int);
int atoi(char *);
int strtol(char *, int);
void itox(char *, unsigned int);
#endif
<file_sep>/src/includes/hardware/cmos.h
#ifndef __cmos__
#define __cmos__
#include <system/typedef.h>
uint8_t cmos_read (uint8_t);
void cmos_write (uint8_t, uint8_t);
void cmos_dump (uint16_t *);
#endif
<file_sep>/src/tesseract/hardware/gdt.c
#include <hardware/gdt.h>
#include <system/typedef.h>
struct {
uint16_t limit;
void *pointer;
} __attribute__((packed)) gdt_ptr = {
.limit = GDT_ENTRIES * 8 - 1,
.pointer = gdt,
};
void gdt_create_descriptor (size_t, uint32_t, uint32_t, uint16_t);
int init_gdt (void) {
gdt_create_descriptor (0, 0, 0, 0);
gdt_create_descriptor (1, 0, 0x000FFFFF, (GDT_CODE_PL0));
gdt_create_descriptor (2, 0, 0x000FFFFF, (GDT_DATA_PL0));
gdt_create_descriptor (3, 0, 0x000FFFFF, (GDT_CODE_PL3));
gdt_create_descriptor (4, 0, 0x000FFFFF, (GDT_DATA_PL3));
// -> TSS
asm volatile ("lgdt %0" : : "m" (gdt_ptr));
gdt_flush ();
return 1;
}
void gdt_create_descriptor
(size_t i, uint32_t base, uint32_t limit, uint16_t flags) {
uint64_t descriptor;
descriptor = limit & 0x000F0000;
descriptor |= (flags << 8) & 0x00F0FF00;
descriptor |= (base >> 16) & 0x000000FF;
descriptor |= base & 0xFF000000;
descriptor <<= 32;
descriptor |= base << 16;
descriptor |= limit & 0x0000FFFF;
gdt[i] = descriptor;
}
<file_sep>/src/tesseract/hardware/cmos.c
#include <system/typedef.h>
#include <hardware/cmos.h>
#include <io/ports.h>
uint8_t cmos_read (uint8_t offset) {
uint8_t tmp = inb (0x70);
outb (0x70, (tmp & 0x80) | (offset & 0x7F));
return inb (0x71);
}
void cmos_write (uint8_t offset, uint8_t value) {
uint8_t tmp = inb (0x70);
outb (0x70, (tmp & 0x80) | (offset & 0x7F));
outb (0x71, value);
}
void cmos_dump (uint16_t *dest) {
uint16_t i = 0;
for (i; i < 128; ++i) {
outb (0x70, i);
dest[i] = inb (0x71);
}
}
<file_sep>/src/includes/hardware/gdt.h
#ifndef __gdt__
#define __gdt__
#include <system/typedef.h>
#define GDT_ENTRIES 5
#define SEG_DESCTYPE(x) ((x) << 0x04) // Descriptor type
#define SEG_PRESENT(x) ((x) << 0x07) // Present
#define SEG_SAVAIL(x) ((x) << 0x0C) // Available for system use
#define SEG_LONG(x) ((x) << 0x0D) // Long mode
#define SEG_SIZE(x) ((x) << 0x0E) // Size (0 = 16bit, 1 = 32bit)
#define SEG_GRAN(x) ((x) << 0x0F) // Granulatiry (0 = 1MB, 1 = 4GB)
#define SEG_PRIV(x) (((x) & 0x03) << 0x05) // Ring ([0..3])
#define SEG_DATA_RD 0x00 // Read-Only
#define SEG_DATA_RDA 0x01 // Read-Only, accessed
#define SEG_DATA_RDWR 0x02 // Read/Write
#define SEG_DATA_RDWRA 0x03 // Read/Write, accessed
#define SEG_DATA_RDEXPD 0x04 // Read-Only, expand-down
#define SEG_DATA_RDEXPDA 0x05 // Read-Only, expand-down, accessed
#define SEG_DATA_RDWREXPD 0x06 // Read/Write, expand-down
#define SEG_DATA_RDWREXPDA 0x07 // Read/Write, expand-down, accessed
#define SEG_CODE_EX 0x08 // Execute-Only
#define SEG_CODE_EXA 0x09 // Execute-Only, accessed
#define SEG_CODE_EXRD 0x0A // Execute/Read
#define SEG_CODE_EXRDA 0x0B // Execute/Read, accessed
#define SEG_CODE_EXC 0x0C // Execute-Only, conforming
#define SEG_CODE_EXCA 0x0D // Execute-Only, conforming, accessed
#define SEG_CODE_EXRDC 0x0E // Execute/Read, conforming
#define SEG_CODE_EXRDCA 0x0F // Execute/Read, conforming, accessed
#define GDT_CODE_PL0 SEG_DESCTYPE(1) | SEG_PRESENT(1) | SEG_SAVAIL(0) \
| SEG_LONG(0) | SEG_SIZE(1) | SEG_GRAN(1) \
| SEG_PRIV(0) | SEG_CODE_EXRD
#define GDT_DATA_PL0 SEG_DESCTYPE(1) | SEG_PRESENT(1) | SEG_SAVAIL(0) \
| SEG_LONG(0) | SEG_SIZE(1) | SEG_GRAN(1) \
| SEG_PRIV(0) | SEG_DATA_RDWR
#define GDT_CODE_PL3 SEG_DESCTYPE(1) | SEG_PRESENT(1) | SEG_SAVAIL(0) \
| SEG_LONG(0) | SEG_SIZE(1) | SEG_GRAN(1) \
| SEG_PRIV(3) | SEG_CODE_EXRD
#define GDT_DATA_PL3 SEG_DESCTYPE(1) | SEG_PRESENT(1) | SEG_SAVAIL(0) \
| SEG_LONG(0) | SEG_SIZE(1) | SEG_GRAN(1) \
| SEG_PRIV(3) | SEG_DATA_RDWR
static uint64_t gdt[GDT_ENTRIES];
int init_gdt (void);
extern void gdt_flush (void);
#endif
<file_sep>/src/includes/system/multiboot.h
#ifndef __multiboot__
#define __multiboot__
#define MULTIBOOT_SEARCH 8192
#define MULTIBOOT_HEADER_ALIGN 4
#define MULTIBOOT_HEADER_MAGIC 0x1BADB002
#define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002
#define MULTIBOOT_MOD_ALIGN 0x00001000
#define MULTIBOOT_INFO_ALIGN 0x00000004
#define MULTIBOOT_PAGE_ALIGN 0x00000001
#define MULTIBOOT_MEMORY_INFO 0x00000002
#define MULTIBOOT_VIDEO_MODE 0x00000004
#define MULTIBOOT_AOUT_KLUDGE 0x00010000
#define MULTIBOOT_INFO_MEMORY 0x00000001
#define MULTIBOOT_INFO_BOOTDEV 0x00000002
#define MULTIBOOT_INFO_CMDLINE 0x00000004
#define MULTIBOOT_INFO_MODS 0x00000008
#define MULTIBOOT_INFO_AOUT_SYMS 0x00000010
#define MULTIBOOT_INFO_ELF_SHDR 0x00000020
#define MULTIBOOT_INFO_MEM_MAP 0x00000040
#define MULTIBOOT_INFO_DRIVE_INFO 0x00000080
#define MULTIBOOT_INFO_CONFIG_TABLE 0x00000100
#define MULTIBOOT_INFO_BOOT_LOADER_TABLE 0x00000200
#define MULTIBOOT_INFO_APM_TABLE 0x00000400
#define MULTIBOOT_INFO_VBE_INFO 0x00000800
#define MULTIBOOT_INFO_FRAMEBUFFER_INFO 0x00001000
#ifndef ASM_FILE
typedef unsigned char multiboot_uint8_t;
typedef unsigned short multiboot_uint16_t;
typedef unsigned int multiboot_uint32_t;
typedef unsigned long long multiboot_uint64_t;
struct multiboot_header
{
/* Must be MULTIBOOT_MAGIC - see above. */
multiboot_uint32_t magic;
/* Feature flags. */
multiboot_uint32_t flags;
/* The above fields plus this one must equal 0 mod 2^32. */
multiboot_uint32_t checksum;
/* These are only valid if MULTIBOOT_AOUT_KLUDGE is set. */
multiboot_uint32_t header_addr;
multiboot_uint32_t load_addr;
multiboot_uint32_t load_end_addr;
multiboot_uint32_t bss_end_addr;
multiboot_uint32_t entry_addr;
/* These are only valid if MULTIBOOT_VIDEO_MODE is set. */
multiboot_uint32_t mode_type;
multiboot_uint32_t width;
multiboot_uint32_t height;
multiboot_uint32_t depth;
};
/* The symbol table for a.out. */
typedef struct multiboot_aout_symbol_table
{
multiboot_uint32_t tabsize;
multiboot_uint32_t strsize;
multiboot_uint32_t addr;
multiboot_uint32_t reserved;
} multiboot_aout_symbol_table_t;
/* The section header table for ELF. */
typedef struct multiboot_elf_section_header_table
{
multiboot_uint32_t num;
multiboot_uint32_t size;
multiboot_uint32_t addr;
multiboot_uint32_t shndx;
} multiboot_elf_section_header_table_t;
typedef struct multiboot_info
{
/* Multiboot info version number */
multiboot_uint32_t flags;
/* Available memory from BIOS */
multiboot_uint32_t mem_lower;
multiboot_uint32_t mem_upper;
/* "root" partition */
multiboot_uint32_t boot_device;
/* Kernel command line */
multiboot_uint32_t cmdline;
/* Boot-Module list */
multiboot_uint32_t mods_count;
multiboot_uint32_t mods_addr;
union
{
multiboot_aout_symbol_table_t aout_sym;
multiboot_elf_section_header_table_t elf_sec;
} u;
/* Memory Mapping buffer */
multiboot_uint32_t mmap_length;
multiboot_uint32_t mmap_addr;
/* Drive Info buffer */
multiboot_uint32_t drives_length;
multiboot_uint32_t drives_addr;
/* ROM configuration table */
multiboot_uint32_t config_table;
/* Boot Loader Name */
multiboot_uint32_t boot_loader_name;
/* APM table */
multiboot_uint32_t apm_table;
/* Video */
multiboot_uint32_t vbe_control_info;
multiboot_uint32_t vbe_mode_info;
multiboot_uint16_t vbe_mode;
multiboot_uint16_t vbe_interface_seg;
multiboot_uint16_t vbe_interface_off;
multiboot_uint16_t vbe_interface_len;
multiboot_uint64_t framebuffer_addr;
multiboot_uint32_t framebuffer_pitch;
multiboot_uint32_t framebuffer_width;
multiboot_uint32_t framebuffer_height;
multiboot_uint8_t framebuffer_bpp;
#define MULTIBOOT_FRAMEBUFFER_TYPE_INDEXED 0
#define MULTIBOOT_FRAMEBUFFER_TYPE_RGB 1
#define MULTIBOOT_FRAMEBUFFER_TYPE_EGA_TEXT 2
multiboot_uint8_t framebuffer_type;
union
{
struct
{
multiboot_uint32_t framebuffer_palette_addr;
multiboot_uint16_t framebuffer_palette_num_colors;
};
struct
{
multiboot_uint8_t framebuffer_red_field_position;
multiboot_uint8_t framebuffer_red_mask_size;
multiboot_uint8_t framebuffer_green_field_position;
multiboot_uint8_t framebuffer_green_mask_size;
multiboot_uint8_t framebuffer_blue_field_position;
multiboot_uint8_t framebuffer_blue_mask_size;
};
};
} multiboot_info_t;
struct multiboot_color
{
multiboot_uint8_t red;
multiboot_uint8_t green;
multiboot_uint8_t blue;
};
typedef struct __attribute__((packed)) multiboot_mmap_entry
{
multiboot_uint32_t size;
multiboot_uint64_t addr;
multiboot_uint64_t len;
#define MULTIBOOT_MEMORY_AVAILABLE 1
#define MULTIBOOT_MEMORY_RESERVED 2
#define MULTIBOOT_MEMORY_ACPI_RECLAIMABLE 3
#define MULTIBOOT_MEMORY_NVS 4
#define MULTIBOOT_MEMORY_BADRAM 5
multiboot_uint32_t type;
} multiboot_memory_map_t;
typedef struct multiboot_mod_list
{
/* the memory used goes from bytes 'mod_start' to 'mod_end-1' inclusive */
multiboot_uint32_t mod_start;
multiboot_uint32_t mod_end;
/* Module command line */
multiboot_uint32_t cmdline;
/* padding to take it to 16 bytes (must be zero) */
multiboot_uint32_t pad;
} multiboot_module_t;
/* APM BIOS info. */
struct multiboot_apm_info
{
multiboot_uint16_t version;
multiboot_uint16_t cseg;
multiboot_uint32_t offset;
multiboot_uint16_t cseg_16;
multiboot_uint16_t dseg;
multiboot_uint16_t flags;
multiboot_uint16_t cseg_len;
multiboot_uint16_t cseg_16_len;
multiboot_uint16_t dseg_len;
};
#endif /* ASM_FILE */
#endif /* __multiboot__ */
| c15d3fffda3da5a3247150d5d7af3339224e40d1 | [
"C",
"Shell"
] | 31 | Shell | SplittyDev/Tesseract | 5d87cd1fe445a45c91986c959e081ddefe838b11 | c62759e9130ab3180ef6c1e0448258900e156bd6 |
refs/heads/master | <file_sep>print("Este programa te saluda...")
def bienvenida (nombre ):
print(f"Bienvenido {nombre}")<file_sep>texto = input("Ingresa un texto...: ")
unico = []
may = []
min = []
for i in texto:
if i.isnumeric():
if i not in unico:
unico.append(i)
unico.sort()
elif i.isspace():
continue
elif isinstance(i, str):
if i not in may and i.isupper():
may.append(i)
may.sort()
elif i not in min and i.islower():
min.append(i)
min.sort()
print(min)
print(may)
print(unico)
<file_sep># pythonProject1
Este es mi primer reposiorio de pycharm
<file_sep>from saludos.despedida.despedida import despedida
<file_sep>class Coche:
def __init__(self, color="verde", rueda="4", largo=250, enmarcha=False):
self.color = color
self.rueda = rueda
self.largo = largo
self.enmarcha = enmarcha
def arrancar(self):
self.enmarcha = True
def estado(self):
if self.enmarcha:
return "El coche esta en marcha"
else
print("El choche esta apagado")
return "El coche no esta en marcha"
def colorear(self):
self.color = "Black"
return "El coche es color negro"
def masruedas(self):
self.rueda = 6
print(f"el coche tiene {self.rueda} ruedas y es un marcianno")
print("Hola mundo")
print("Puc montejo"))
<file_sep>from setuptools import setup
setup(
name="paquetebienvenida",
version="1.0",
description="Este es un paquete que contiene la bienvenida",
author="HG2905",
url="www.henryhg2905.com",
packages=["bienvenida"]
)
<file_sep>class Carro:
def __init__(self, marca="nissan", color="blanco", modelo="tsuru", peso=400, enmarcha=False):
self.marca = marca
self.color = color
self.modelo = modelo
self.peso = peso
self.enmarcha = enmarcha
def encender(self, encen):
self.enmarcha = encen
if self.enmarcha:
return "El carro esta encendido"
else:
return "El carro esta apagado"
ey papito
def avanzar(self):
pass
def detener(self):
pass
def girarizquierda(self):
pass
def girarderecha(self):
pass
carro1 = Carro("Audi", "rojo", "deportivo", 500)
carro2 = Carro("BMW", "negro", "turismo", 450)
# carro3 = Carro("seat", "plateado", "todoterreno", 600)
| bf79983c4a3abd1eeb6ec04a74c98350de0568b1 | [
"Markdown",
"Python"
] | 7 | Python | HG2905/pythonProject1 | 51245d9607c73228b8a609d640b6011381dbef1f | 9c16801ff151b3d14c55efaffff1338f32b488e4 |
refs/heads/master | <file_sep>fit_RL <- readRDS("_outputs/fit_RL.RData")
loo_RL <- extract_looic(fit_RL,NULL)$looic
aic_RL <- extract_otheric(fit_RL,NULL, np = 2)$myAIC
bic_RL <- extract_otheric(fit_RL,NULL, np = 2)$myBIC
waic_RL <- extract_otheric(fit_RL,NULL, np = 2)$myWAIC$waic
# rm(fit_RL)
fit_RLnc <- readRDS("_outputs/fit_RLnc.RData")
loo_RLnc <- extract_looic(fit_RLnc,NULL)$looic
aic_RLnc <- extract_otheric(fit_RLnc,NULL, np = 2)$myAIC
bic_RLnc <- extract_otheric(fit_RLnc,NULL, np = 2)$myBIC
waic_RLnc <- extract_otheric(fit_RLnc,NULL, np = 2)$myWAIC$waic
#rm(fit_RLnc)
fit_RLcoh <- readRDS("_outputs/fit_RLcoh.RData")
loo_RLcoh <- extract_looic(fit_RLcoh,NULL)$looic
aic_RLcoh <- extract_otheric(fit_RLcoh,NULL, np = 4)$myAIC
bic_RLcoh <- extract_otheric(fit_RLcoh,NULL, np = 4)$myBIC
waic_RLcoh <- extract_otheric(fit_RLcoh,NULL, np = 4)$myWAIC$waic
# rm(fit_RLcoh)
# fit_RLcr <- readRDS("_outputs/fit_RLcumrew.RData")
# loo_RLcr <- extract_looic(fit_RLcr,NULL)$looic
# rm(fit_RLcr)
fit_RLbeta_a1 <- readRDS("_outputs/fit_RLbeta_alt1_c_w_080.RData")
loo_RLbeta_a1 <- extract_looic(fit_RLbeta_a1,core=1)$looic
aic_RLbeta_a1 <- extract_otheric(fit_RLbeta_a1,np = 7)$myAIC
bic_RLbeta_a1 <- extract_otheric(fit_RLbeta_a1,np = 7)$myBIC
waic_RLbeta_a1 <- extract_otheric(fit_RLbeta_a1,np = 7)$myWAIC$waic
#rm(fit_RLbeta_a1)
fit_RLbeta_a2 <- readRDS("_outputs/fit_RLbeta_alt2_c_v2_w_1lr.RData")
loo_RLbeta_a2 <- extract_looic(fit_RLbeta_a2,core=1)$looic
aic_RLbeta_a2 <- extract_otheric(fit_RLbeta_a2,np = 7)$myAIC
bic_RLbeta_a2 <- extract_otheric(fit_RLbeta_a2,np = 7)$myBIC
waic_RLbeta_a2 <- extract_otheric(fit_RLbeta_a2,np = 7)$myWAIC$waic
#rm(fit_RLbeta_a2)
fit_RLbeta_a3 <- readRDS("_outputs/fit_RLbeta_alt3_p2_v1_w_080.RData")
loo_RLbeta_a3 <- extract_looic(fit_RLbeta_a3,core=1)$looic
aic_RLbeta_a3 <- extract_otheric(fit_RLbeta_a3,np = 9)$myAIC
bic_RLbeta_a3 <- extract_otheric(fit_RLbeta_a3,np = 9)$myBIC
waic_RLbeta_a3 <- extract_otheric(fit_RLbeta_a3,np = 9)$myWAIC$waic
#rm(fit_RLbeta_a3)
fit_RLbeta_a4 <- readRDS("_outputs/fit_RLbeta_alt4_c_w_v6.RData")
loo_RLbeta_a4 <- extract_looic(fit_RLbeta_a4,core=1)$looic
aic_RLbeta_a4 <- extract_otheric(fit_RLbeta_a4,np = 8)$myAIC
bic_RLbeta_a4 <- extract_otheric(fit_RLbeta_a4,np = 8)$myBIC
waic_RLbeta_a4 <- extract_otheric(fit_RLbeta_a4,np = 8)$myWAIC$waic
# rm(fit_RLbeta_a4)
AIC_vec <- c(aic_RL, aic_RLnc, aic_RLcoh, aic_RLbeta_a1, aic_RLbeta_a2, aic_RLbeta_a3, aic_RLbeta_a4)
BIC_vec <- c(bic_RL, bic_RLnc, bic_RLcoh, bic_RLbeta_a1, bic_RLbeta_a2, bic_RLbeta_a3, bic_RLbeta_a4)
WAIC_vec <- c(waic_RL, waic_RLnc, waic_RLcoh, waic_RLbeta_a1, waic_RLbeta_a2, waic_RLbeta_a3, waic_RLbeta_a4)
LOOIC_vec <- c(loo_RL, loo_RLnc, loo_RLcoh, loo_RLbeta_a1, loo_RLbeta_a2, loo_RLbeta_a3, loo_RLbeta_a4)
IC_mat <- cbind(AIC_vec, BIC_vec, WAIC_vec, LOOIC_vec)
save(IC_mat, file = '_outputs/ICMat.RData')<file_sep>extract_otheric <- function(stanfit, choice=2, np) {
# extract AIC, NIC, WAIC, from mcmc object
# np: number of parameters
L <- list()
if ( class(stanfit)=='stanfit' ) {
stanfit <- stanfit
} else {
stanfit <- stanfit$fit
}
if ( is.null(choice) ) {
par_name <- "log_lik"
} else if (choice == 1) {
par_name <- "log_likc1"
} else if (choice == 2) {
par_name <- "log_likc2"
}
lik <- extract_log_lik(stanfit, parameter_name = par_name)
myWAIC <- waic(lik)
subjLik <- colMeans(lik) # estimated loglikelihood per subject from the posterior loglik matrix
ns <- dim(lik)[2] # number of subjects
myAIC <- -2 * subjLik + 2 * np
myBIC <- -2 * subjLik + log(ns) * np
L$myAIC <- sum(myAIC)
L$myBIC <- sum(myBIC)
L$myWAIC <- myWAIC
return(L)
}<file_sep>beta_corplot <- function( stanfit, splt = NULL ) {
# beta_corplot() plots the correlation matrix of individuals' BETAs
library(corrplot)
if ( class(stanfit)=='stanfit' ) {
stanfit <- stanfit
} else {
stanfit <- stanfit$fit
}
#### get BETAs from Stanfit output -------------------------------------------------------------
ns <- 129
parm <- get_posterior_mean(stanfit, 'beta')
bMat <- matrix(parm[,5], nrow = ns)
nb <- dim(bMat)[2]
colnames(bMat) <- paste('beta', 1:nb)
### get all the parameters ----------------------
# parm <- get_posterior_mean(stanfit, c('lr', 'disc', 'beta'))
# parMat <- matrix(parm[,5], nrow = ns)
# colnames(parMat) <- c('lr', 'disc',paste('beta', 1:6))
# writeMat('_outputs/param_beta4_alt6.mat', parMat = parMat)
------------------------------------------------------------------------
if (is.null(splt) ) {
corrMat <- cor(bMat)
corrplot(corrMat, method = 'square', diag = FALSE, addCoef.col = T)
} else if (splt == 6) {
bMat_pos <- bMat[bMat[,6] >= 0,]
bMat_neg <- bMat[bMat[,6] < 0,]
corrMat_pos <- cor(bMat_pos)
corrMat_neg <- cor(bMat_neg)
par(mfrow = c(1,2))
corrplot(corrMat_pos, method = 'square', diag = FALSE, addCoef.col = T)
corrplot(corrMat_neg, method = 'square', diag = FALSE, addCoef.col = T)
}
}<file_sep>source("_scripts/stan_source.R")
library(ggplot2)
library(reshape2)
fit_RL <- readRDS("_outputs/fit_RL.RData")
lik_RL <- extract_log_lik(fit_RL, parameter_name = "log_lik")
loo_RL <- loo(lik_RL, cores = 4)
loo_RL_pw <- as.matrix(loo_RL$pointwise[,3] )
fit_RLnc <- readRDS("_outputs/fit_RLnc.RData")
lik_RLnc <- extract_log_lik(fit_RLnc, parameter_name = "log_lik")
loo_RLnc <- loo(lik_RLnc, cores = 4)
loo_RLnc_pw <- as.matrix(loo_RLnc$pointwise[,3] )
fit_RLnc_2lr <- readRDS("_outputs/fit_RLnc_2lr.RData")
lik_RLnc_2lr <- extract_log_lik(fit_RLnc_2lr, parameter_name = "log_lik")
loo_RLnc_2lr <- loo(lik_RLnc_2lr, cores = 4)
loo_RLnc_2lr_pw <- as.matrix(loo_RLnc_2lr$pointwise[,3] )
fit_RLnc_cfa <- readRDS("_outputs/fit_RLnc_cfa.RData")
lik_RLnc_cfa <- extract_log_lik(fit_RLnc_cfa, parameter_name = "log_lik")
loo_RLnc_cfa <- loo(lik_RLnc_cfa, cores = 4)
loo_RLnc_cfa_pw <- as.matrix(loo_RLnc_cfa$pointwise[,3] )
fit_RLnc_2lr_cfa <- readRDS("_outputs/fit_RLnc_2lr_cfa.RData")
lik_RLnc_2lr_cfa <- extract_log_lik(fit_RLnc_2lr_cfa, parameter_name = "log_lik")
loo_RLnc_2lr_cfa <- loo(lik_RLnc_2lr_cfa, cores = 4)
loo_RLnc_2lr_cfa_pw <- as.matrix(loo_RLnc_2lr_cfa$pointwise[,3] )
fit_RLcoh <- readRDS("_outputs/fit_RLcoh.RData")
lik_RLcoh <- extract_log_lik(fit_RLcoh, parameter_name = "log_lik")
loo_RLcoh <- loo(lik_RLcoh, cores = 3)
loo_RLcoh_pw <- as.matrix(loo_RLcoh$pointwise[,3] )
fit_RLcoh_2lr <- readRDS("_outputs/fit_RLcoh_2lr.RData")
lik_RLcoh_2lr <- extract_log_lik(fit_RLcoh_2lr, parameter_name = "log_lik")
loo_RLcoh_2lr <- loo(lik_RLcoh_2lr, cores = 3)
loo_RLcoh_2lr_pw <- as.matrix(loo_RLcoh_2lr$pointwise[,3] )
fit_RLcoh_cfa <- readRDS("_outputs/fit_RLcoh_cfa.RData")
lik_RLcoh_cfa <- extract_log_lik(fit_RLcoh_cfa, parameter_name = "log_lik")
loo_RLcoh_cfa <- loo(lik_RLcoh_cfa, cores = 3)
loo_RLcoh_cfa_pw <- as.matrix(loo_RLcoh_cfa$pointwise[,3] )
fit_RLcoh_2lr_cfa <- readRDS("_outputs/fit_RLcoh_2lr_cfa.RData")
lik_RLcoh_2lr_cfa <- extract_log_lik(fit_RLcoh_2lr_cfa, parameter_name = "log_lik")
loo_RLcoh_2lr_cfa <- loo(lik_RLcoh_2lr_cfa, cores = 3)
loo_RLcoh_2lr_cfa_pw <- as.matrix(loo_RLcoh_2lr_cfa$pointwise[,3] )
fit_RLcr <- readRDS("_outputs/fit_RLcumrew.RData")
lik_RLcr <- extract_log_lik(fit_RLcr, parameter_name = "log_lik")
loo_RLcr <- loo(lik_RLcr, cores = 3)
loo_RLcr_pw <- as.matrix(loo_RLcr$pointwise[,3] )
fit_RLcr_2lr <- readRDS("_outputs/fit_RLcumrew_2lr.RData")
lik_RLcr_2lr <- extract_log_lik(fit_RLcr_2lr, parameter_name = "log_lik")
loo_RLcr_2lr <- loo(lik_RLcr_2lr, cores = 3)
loo_RLcr_2lr_pw <- as.matrix(loo_RLcr_2lr$pointwise[,3] )
fit_RLcr_cfa <- readRDS("_outputs/fit_RLcumrew_cfa.RData")
lik_RLcr_cfa <- extract_log_lik(fit_RLcr_cfa, parameter_name = "log_lik")
loo_RLcr_cfa <- loo(lik_RLcr_cfa, cores = 3)
loo_RLcr_cfa_pw <- as.matrix(loo_RLcr_cfa$pointwise[,3] )
fit_RLcr_2lr_cfa <- readRDS("_outputs/fit_RLcumrew_2lr_cfa.RData")
lik_RLcr_2lr_cfa <- extract_log_lik(fit_RLcr_2lr_cfa, parameter_name = "log_lik")
loo_RLcr_2lr_cfa <- loo(lik_RLcr_2lr_cfa, cores = 3)
loo_RLcr_2lr_cfa_pw <- as.matrix(loo_RLcr_2lr_cfa$pointwise[,3] )
looMat = cbind(loo_RL_pw, loo_RLnc_pw, loo_RLnc_2lr_pw, loo_RLnc_cfa_pw, loo_RLnc_2lr_cfa_pw,
loo_RLcoh_pw, loo_RLcoh_2lr_pw, loo_RLcoh_cfa_pw, loo_RLcoh_2lr_cfa_pw,
loo_RLcr_pw, loo_RLcr_2lr_pw, loo_RLcr_cfa_pw, loo_RLcr_2lr_cfa_pw)
save(looMat, file = '_outputs/looicMat.RData')
#### plot ####
load(file = '_outputs/looicMat.RData')
looDF <- melt(looMat)
colnames(looDF) <- c('subID', 'modelName', 'LOOIC')
looDF$modelName <- c(rep('RL', 129), rep('RLnc',129), rep('RLnc_2lr',129),rep('RLnc_cfa',129),rep('RLnc_2lr_cfa',129),
rep('RLcoh',129),rep('RLcoh_2lr',129),rep('RLcoh_cfa',129),rep('RLcoh_2lr_cfa',129),
rep('RLcumrew',129),rep('RLcumrew_2lr',129),rep('RLcumrew_cfa',129),rep('RLcumrew_2lr_cfa',129))
modelName <- c('RL','RLnc','RLnc_2lr','RLnc_cfa','RLnc_2lr_cfa',
'RLcoh','RLcoh_2lr','RLcoh_cfa','RLcoh_2lr_cfa',
'RLcumrew','RLcumrew_2lr','RLcumrew_cfa','RLcumrew_2lr_cfa')
looDF$modelName <- factor(looDF$modelName, levels = modelName)
theme_set(theme_gray(base_size = 20))
ggplot(data=looDF, aes(modelName, LOOIC)) + geom_boxplot(aes(fill = modelName))
<file_sep>beta_barplot <- function(stanfit, six = FALSE) {
# beta_barplot() plots the BETAs' posterior group mean with a 95% HDI
library(ggplot2)
library(coda)
if ( class(stanfit)=='stanfit' ) {
stanfit <- stanfit
} else {
stanfit <- stanfit$fit
}
#### get BETAs from Stanfit output -------------------------------------------------------------
parm <- get_posterior_mean(stanfit, 'beta_mu')
b_mean <- as.matrix(parm[,5])
nb <- length(b_mean)
b_name <- paste('beta', 1:nb)
df <- data.frame(b_mean = b_mean, b_name = b_name )
#### extract mcmc and calculate the 95% HDI -----------------------------------------------------
mcmcCoda = mcmc.list( lapply( 1:ncol(stanfit) , function(x) {mcmc(as.array(stanfit)[,x,])}))
HDI <- array(0, c(nb,2))
for (B in 1:nb) {
HDI[B,] <- HDIofMCMC( mcmcCoda[, paste0("beta_mu[",B,"]") ] )
}
HDI_lb <- HDI[,1]; HDI_ub <- HDI[,2]
df$HDI_ub <- HDI_ub; df$HDI_lb <- HDI_lb
df <- df[c('b_name','b_mean','HDI_ub','HDI_lb')]
#### plot #### ---------------------------------------------------------------------------------
theme_set(theme_bw(base_size = 18))
g <- ggplot(df, aes(x = b_name, y = b_mean))
dodge <- position_dodge(width=0.9)
limits <- aes(ymax = HDI_ub, ymin = HDI_lb)
if ( six == FALSE) {
g <- g + geom_bar(position=dodge, stat="identity", width = .8,
fill = "deepskyblue2", colour = "black")
g <- g + geom_errorbar(limits, position=dodge, width=0.25,
size = 1, colour = "deepskyblue4")
} else {
g <- g + geom_bar(position=dodge, stat="identity", width = .8,
fill = c("#D55E00","#56B4E9","#999999","#999999","#009E73","#009E73"))
g <- g + geom_errorbar(limits, position=dodge, width=0.25, size = 1,
colour = c("#D55E00","#56B4E9","#999999","#999999","#009E73","#009E73"))
}
g <- g + geom_hline(yintercept=0)
g <- g + ylab("beta values") + xlab("")
print(g)
return(df)
}
#### HDI function adapted from Kruschke's book (2015)
HDIofMCMC = function( sampleVec , credMass=0.95 ) {
if ( class(sampleVec) == "mcmc.list" ) {
sampleVec = as.matrix(sampleVec)
}
sortedPts = sort( sampleVec )
ciIdxInc = ceiling( credMass * length( sortedPts ) )
nCIs = length( sortedPts ) - ciIdxInc
ciWidth = rep( 0 , nCIs )
for ( i in 1:nCIs ) {
ciWidth[ i ] = sortedPts[ i + ciIdxInc ] - sortedPts[ i ]
}
HDImin = sortedPts[ which.min( ciWidth ) ]
HDImax = sortedPts[ which.min( ciWidth ) + ciIdxInc ]
HDIlim = c( HDImin , HDImax )
return( HDIlim )
}
<file_sep>fit_RL <- readRDS("_outputs/fit_RL.RData")
loo_RL <- extract_looic(fit_RL,NULL)$looic
#rm(fit_RL)
fit_RLnc <- readRDS("_outputs/fit_RLnc.RData")
loo_RLnc <- extract_looic(fit_RLnc,NULL)$looic
#rm(fit_RLnc)
fit_RLcoh <- readRDS("_outputs/fit_RLcoh.RData")
loo_RLcoh <- extract_looic(fit_RLcoh,NULL)$looic
#rm(fit_RLcoh)
fit_RLcr <- readRDS("_outputs/fit_RLcumrew.RData")
loo_RLcr <- extract_looic(fit_RLcr,NULL)$looic
# rm(fit_RLcr)
fit_RLbeta_a1 <- readRDS("_outputs/fit_RLbeta_alt1_c_w_080.RData")
loo_RLbeta_a1 <- extract_looic(fit_RLbeta_a1,core=1)$looic
rm(fit_RLbeta_a1)
fit_RLbeta_a2 <- readRDS("_outputs/fit_RLbeta_alt2_c_v2_w_1lr.RData")
loo_RLbeta_a2 <- extract_looic(fit_RLbeta_a2,core=1)$looic
rm(fit_RLbeta_a2)
fit_RLbeta_a3 <- readRDS("_outputs/fit_RLbeta_alt3_p2_v1_w_080.RData")
loo_RLbeta_a3 <- extract_looic(fit_RLbeta_a3,core=1)$looic
rm(fit_RLbeta_a3)
fit_RLbeta_a4 <- readRDS("_outputs/fit_RLbeta_alt4_c_w_v6.RData")
loo_RLbeta_a4 <- extract_looic(fit_RLbeta_a4,core=1)$looic
rm(fit_RLbeta_a4)
# looMat = cbind(loo_RL_pw, loo_RLnc_pw, loo_RLnc_2lr_pw, loo_RLnc_cfa_pw, loo_RLnc_2lr_cfa_pw,
# loo_RLcoh_pw, loo_RLcoh_2lr_pw, loo_RLcoh_cfa_pw, loo_RLcoh_2lr_cfa_pw,
# loo_RLcr_pw, loo_RLcr_2lr_pw, loo_RLcr_cfa_pw, loo_RLcr_2lr_cfa_pw)
# save(looMat, file = '_outputs/looicMat.RData')<file_sep>a <- summary(out1)
a <- a$summary
# get the column-names and row-names
colnames(a)
rownames(a)
parMean <- as.matrix(a[,1])
parMedn <- as.matrix(a[,6])
## calculating is a bit tricky
library(modeest)
#### extract mcmc ####
lr_mu <- extract (out1, "lr_mu")$lr_mu # returns an array
<file_sep>source("_scripts/DBDA2E-utilities.R")
library(coda)
mcmcCoda = mcmc.list( lapply( 1:ncol(out) , function(x) {mcmc(as.array(out)[,x,])}))
fileNameRoot = "some_file_name"
graphFileType = "eps"
diagMCMC(mcmcCoda, parName=c("lr_mu")
# , saveName = fileNameRoot
# , saveType = graphFileType
)
plotPost(mcmcCoda[,"lr_mu"], main = "lr_mu", xlab = bquote(lr_mu),
cenTend = "mode", credMass = 0.95, showCurve = FALSE,
col = "skyblue")
## optional plot input arguments for plotPost:
# border = "skyblue"
# xlim = c(0,1)
# points( lr , 0 , pch="+" , col="red" , cex=3 )
# points() can be used for ploting the true parameter for simulated data
plotPost(mcmcCoda[,"beta_mu[6]"], main = "beta_mu[6]", xlab = bquote(beta_mu[6]),
cenTend = "mean", credMass = 0.95, showCurve = F,
col = "skyblue")
<file_sep># sit_stan
project 'sit': Bayesian hierarchical fitting with Stan
This folder contains all the existing sit(social influence task)-related models. Below is the model index, in a chronological order based on development history.
RevLearn_
- RL: simple RL model with Rescorla Wagner update rule.
- RLnc: ficticious RL model, also model the non-chosen choice (-reward - value[non-chosen]).
- RLnc_2lr: add an additional learning rate to the non-chosen update
- RLnc_cfa: add an additional conterfactual attention parameter, (-cfa*reward)
- RLnc_2lr_cfa: putting 2lr and cfa together
- RLcoh: reweight the values according to decision type (with vs. against)
- RLcoh_2lr
- RLcoh_cfa
- RLcoh_2lr_cfa
- RLcumrew: reweight the values according to coplayers' reward history (cumulative reward)
- RLcumrew_2lr
- RLcumrew_cfa
- RLcumrew_2lr_cfa
- RLcoh_modvalue: the coherence reweight goes into the value directly, the same as RLcoh
- RLcoh_modprob_tempin: the coherence reweight only goes into the softmax transformation, temperature*value + reweight
- RLcoh_modprob_tempout: the coherence reweight only goes into the softmax transformation, temperature*(value + reweight)
- RLbeta_alt1: weighted sum of otherRewards according to subjects' preference towards co-players
- RLbeta_alt2: use beta_cdf to quantify others' choice tendency, and then used to model otherValue
- RLbeta_alt2_c_v1: with evidence weight
- RLbeta_alt2_c_v2: without evidence weight
- RLbeta_alt3: treat each co-player as a separate reinforcer, use a simple RL update to quantify otherValue
- RLbeta_alt3_p1_v1: step1, get lr and tau for the others, single lr and tau
- RLbeta_alt3_p2_v1: 1 lr for chosen and non-chosen choices, with c_rep
- RLbeta_alt3_p1_v2: step1, get lr and tau for the others, 4 lr and tau
- RLbeta_alt3_p2_v2: 1 lr for chosen and non-chosen choices, without c_rep; essentially, this should be the same as _p2_v1
- RLbeta_alt4: (preference) weighted sum of cumulative otherRewards to represent otherValue
- RevLearn_RLbeta_alt4_c_w_v1_1lr: only uses current preference weights and current with/against
- RevLearn_RLbeta_alt4_c_w_v2_1lr: preference weight sum up to one --> [3 2 1 1]/7
- RevLearn_RLbeta_alt4_c_w_v3_1lr: v3_without weight on otherValue when update
- RevLearn_RLbeta_alt4_c_w_v4_1lr: use actual weight and with/against
- RevLearn_RLbeta_alt4_c_w_v5_1lr: beta1-4 separately model myValue and otherValue (chosen vs. non-chosen)
- RevLearn_RLbeta_alt4_c_w_v6_1lr: actual weight but only current with/against
- RevLearn_RLbeta_alt4_c_v6_1lr : use actual with/against, rather than weighted with/against
- RevLearn_RLbeta_alt4_c_w_v6_2lr: actual weight but only current with/against, 2 learning rate
- RevLearn_RLbeta_alt4_c_w_v7_1lr: based on v1, windows size = 4
- RevLearn_RLbeta_alt4_c_w_v8_1lr: same beta for myV, separate beta for otherV
- RevLearn_RLbeta_alt4_c_w_v9_1lr: based on v1, windows size = 5
- RevLearn_RLbeta_alt4_c_w_v10_1lr: based on v1, adding a cfa parameter
- RevLearn_RLbeta_alt4_c_w_v11_1lr: based on v6, normalize the discounted cumulative reward (cr), before using for update otherValue (divided by sum)
- RevLearn_RLbeta_alt4_c_w_v12_1lr: based on v6, use [-1 1] as the discounted reward, rather than [0 1], normalized cr with SOFTMAX (sumup to one)
- RevLearn_RLbeta_alt4_c_w_v13_1lr: based on v6, valdiff = valfun1(c1) - valfun(~c1), instead of valdiff = myValue(c1) - myValue(~c1)
- RevLearn_RLbeta_alt4_c_w_v14_1lr: based on v6, normalize the discounted cumulative reward, 2 * SOFTMAX - 1, --> [-1 1]
- RevLearn_RLbeta_alt4_c_w_v15_1lr_ind: based on v6, fit the model non-hierarchically, (individual fitting)
- RevLearn_RLbeta_alt4_c_w_v16_1lr: based on v6, valdiff = bet * ( V(c1) - V(~c1) )
- RevLearn_RLbeta_alt4_c_w_v17_1lr: based on v6, use 2 beta for Valdiff (+ and -) --> beta4 * (vdiff >=0) * vdiff + beta5 * (vdiff<0) * vdiff
- RevLearn_RLbeta_alt4_c_w_v18_1lr: based on v6, use inv_logit for normalizing cr
- RevLearn_RLbeta_alt4_c_w_v19_1lr: based on v6, use inv_logit for normalizing otherValue, not otherCR
- RevLearn_RLbeta_alt4_c_w_v20_1lr: based on v6, separate beta for general bias: when nWigh >= nAgst, and when aWith < nAgst
- RevLearn_RLbeta_alt4_c_w_v21_1lr: based on v12 & v20, separate beta for general bias, using [-1 1] for cr, inv_logit for normalizing
- RevLearn_RLbeta_alt4_c_w_v22_1lr: based on v6, using other's accuracy as the weight for updating otherValue
- RevLearn_RLbeta_alt4_c_w_v23_1lr: based on v6, adding two temperatures for categorical_logit() and for bernoulli_logit()
- RevLearn_RLbeta_alt4_c_w_v24_1lr: based on v19, use (inv_logit *2 -1) for normalizing otherValue, not otherCR
- RevLearn_RLbeta_alt4_c_w_v25_1lr: --> v24, + 1)different valdiff betas, 2)accuracy as weight, 3)valdiff=diff(valfun), 4) diff(w/a) 2 betas, 5) [-1 1] for otherV
- RevLearn_RLbeta_alt4_c_w_v26_1lr: --> v24, + 1)valdiff=diff(valfun), 2) diff(w/a) 2 betas,
- RevLearn_RLbeta_alt4_c_w_v27_1lr: --> v24, + 1)valdiff=diff(valfun), 2) diff(w/a) 2 betas, 3) [-1 1] for cr
- RevLearn_RLbeta_alt4_c_w_v28_1lr: based on v24, + 1)valdiff=diff(valfun), 2)only uses nAgainst
- RevLearn_RLbeta_alt4_c_w_v29_1lr: based on v26, without general bias
- RevLearn_RLbeta_alt4_c_w_v30_1lr: based on v28, without general bias
- RevLearn_RLbeta_alt4_c_w_v31_1lr: based on v6, add (1) 'inv_logit *2 -1' for normalizing otherValue, (2) valdiff=diff(valfun)
- RevLearn_RLbeta_alt4_c_w_v32_1lr: based on v31, use something like the RLcoh, 1/2 for second choice, not 0/1 switch
- RevLearn_RLbeta_alt4_c_w_v33_1lr: based on v32, without beta[3,s] * valfun2[:]
- RevLearn_RLbeta_alt4_c_w_v34_1lr: based on v31, leave out the general bias
- RevLearn_RLbeta_alt4_c_w_v35_1lr: based on v31, valdiff = bet1 * ( valfun1(c1) - valfun1(~c1) )
- RevLearn_RLbeta_alt4_c_w_v36_1lr: based on v35, otherReward2, use [-1 1] for the current trial, use [0 1] for the past trials
- RevLearn_RLbeta_alt4_c_w_v37_1lr: based on v36, 4) diff(w/a) 2 betas
- RevLearn_RLbeta_alt4_c_w_v38_1lr: based on v37, valdiff = bet1 * valdiff
- RevLearn_RLbeta_alt4_c_w_v39_1lr: based on v6, weighted likelihood function, use nStay/nSwitch as a penalty term
- RevLearn_RLbeta_alt4_c_w_v40_1lr: based on v6, weighted likelihood function, use nStay/nTrial as a penalty term
- RLbeta_alt5: (preference) weighted sum of cumulative otherRewards to represent otherValue, bind beta5 and beta6 together
- RevLearn_RLbeta_alt5_c_w_v1_1lr: no 'general bias', run: vfun2 <- beta3*vDiff + beta4*(wgtWigh - wgtAgst)
- RevLearn_RLbeta_alt5_c_w_v3_1lr: with 'general bias', run: vfun2 <- beta3 + beta4*vDiff + beta5*(wgtWigh - wgtAgst)
- RLbeta_alt6: temperature, regression-like model (e.g. beta[s] ~ N( b0 + b1 * age + b2 * VDiff, sigma) )
- RevLearn_RLbeta_alt1_c_w_v1_1lr: based on alt4_c_w_v6_1lr
- RevLearn_RLbeta_alt1_c_w_v2_1lr: based on v1, but with: bernoulli_logit( tau[s] * (valfun2[3-choice1[s,t]] - valfun2[choice1[s,t]] + beta[3,s]) );
- RevLearn_RLbeta_alt7_c_w_v1_1lr: based on alt4_v37, make a final version, use as the main model
x: value_diff = valfun1(c1) - valfun1(3-c1)
x: 6 betas
x: control otherValue's range between -1 and 1
x: reward history <- rbind( oth_reward[t-2:t-1](i.e. 0 or 1) , actual_oth_reward[t](i.e. -1 or 1) )
- RevLearn_RLbeta_alt7_c_w_v2_1lr: based on V1, adding a 'cfa' parameter
- RevLearn_RLbeta_alt7_c_w_v3_1lr: based on V1, use a beta0, as in valfun1 <- beta0[s] * myV + (2-beta0[s])*otherV
- RevLearn_RLbeta_alt7_c_w_v4_1lr: based on V1, without beta*wgtWith, to see whether the effect of against increases
- RevLearn_RLbeta_alt7_c_w_v5_1lr: based on V1, fit general bias(beta3) individually, not hierarchically
- _w: weighted coherence, i.e. weight .* with, weight .* against
- _n: normalised other Value, i.e. othV(c2) / (othV(c2), othV(~c2))
<file_sep>get_mcmc <- function(stanFit){
library(coda) # for mcmc.list()
library(runjags) # for combine.mcmc()
mcmcCoda <- mcmc.list( lapply( 1:ncol(stanFit), function(x){mcmc(as.array(stanFit)[,x,])}))
mcmc <- combine.mcmc(mcmcCoda)
return(mcmc)
}
<file_sep>extract_looic <- function(stanfit, choice=2, core=4) {
# extract LOOIC, from mcmc object
if ( class(stanfit)=='stanfit' ) {
stanfit <- stanfit
} else {
stanfit <- stanfit$fit
}
if ( is.null(choice) ) {
par_name <- "log_lik"
} else if (choice == 1) {
par_name <- "log_likc1"
} else if (choice == 2) {
par_name <- "log_likc2"
}
lik <- extract_log_lik(stanfit, parameter_name = par_name)
looic <- loo(lik, cores = core)
return(looic)
}<file_sep>run_model <- function(modelStr, test = TRUE, fitObj = NA, adapt = 0.8) {
library(rstan); library(parallel); library(loo)
L <- list()
#### prepare data #### ===========================================================================
dataList <- prep_data(modelStr)
#### preparation for running stan #### ============================================================
# model string in a separate .stan file
modelFile <- paste0("_scripts/",modelStr,".stan")
# setup up Stan configuration
if (test == TRUE) {
options(mc.cores = 1)
nSamples <- 4
nChains <- 1
nBurnin <- 0
nThin <- 1
} else {
options(mc.cores = 4)
nSamples <- 2000#2000
nChains <- 4
nBurnin <- floor(nSamples/2)
nThin <- 1#1
}
# parameter of interest (this could save both memory and space)
poi <- create_pois(modelStr)
#### run stan #### ==============================================================================
cat("Estimating", modelStr, "model... \n")
startTime = Sys.time(); print(startTime)
cat("Calling", nChains, "simulations in Stan... \n")
rstan_options(auto_write = TRUE)
stanfit <- stan(modelFile,
fit = fitObj,
data = dataList,
pars = poi,
chains = nChains,
iter = nSamples,
warmup = nBurnin,
thin = nThin,
init = "random",
#seed = 1581381385, # for RLbeta_alt3_p2_v2, LOOIV 8217
#seed = 295171225, # for RLbeta_alt2_v1, LOOIC 8216
seed = 1450154626, # for alt4_
#seed = 1136699103, # alt4_, seems even lower looic
control = list(adapt_delta = adapt),
verbose = FALSE)
cat("Finishing", modelStr, "model simulation ... \n")
endTime = Sys.time(); print(endTime)
cat("It took",as.character.Date(endTime - startTime), "\n")
L$data <- dataList
L$fit <- stanfit
return(L)
} # function run_model()
#### nested functions #### ===========================================================================
prep_data <- function(modelstr){
load("_data/sit_reversal_betnoshow_129.rdata")
dataList <- list()
sz <- dim(mydata)
nt <- sz[1]; ns <- sz[3]
dataList$nSubjects <- ns; dataList$nTrials <- nt
choice1 <- array(0,dim = c(ns,nt)); choice2 <- array(0,dim = c(ns,nt)); reward <- array(0,dim = c(ns,nt))
choice1 <- t(mydata[,3,]) # 1 OR 2
choice2 <- t(mydata[,10,]) # 1 OR 2
reward <- t(mydata[,14,]) # 1 OR -1
stayBYswitch <- array(0,dim = c(ns)) # nStay/nSwitch, per subject
stayBYtrial <- array(0,dim = c(ns)) # nStay/nTrial, per subject
stayBYswitch <- mydata[100,145,]
stayBYswitch[stayBYswitch==Inf] <- 99
stayBYtrial <- mydata[100,146,]
dataList$choice1 <- choice1
dataList$choice2 <- choice2
dataList$reward <- reward
dataList$stayBYswitch <- stayBYswitch
dataList$stayBYtrial <- stayBYtrial
if ( substr(modelstr,1,14) == "RevLearn_RLcoh" ) {
chswtch <- array(0,dim = c(ns,nt))
bet1 <- array(0,dim = c(ns,nt)); bet2 <- array(0,dim = c(ns,nt))
with <- array(0,dim = c(ns,nt)); against <- array(0,dim = c(ns,nt))
my1 <- 0; other1 <- c(0,0,0,0)
chswtch <- t(mydata[,5,])
bet1 <- t(mydata[,13,]); bet2 <- t(mydata[,19,])
for (s in 1:ns) {
for (tr in 1:nt){
my1 <- mydata[tr,3,s]; other1 <- mydata[tr,6:9,s]
with[s,tr] <- length(which(other1==my1)) /4 # count of with, either 1, 2, 3, or 4, divided by 4
against[s,tr] <- length(which(other1!=my1)) /4 # count of against, either 1, 2, 3, or 4, divided by 4
}
}
dataList$chswtch <- chswtch
dataList$bet1 <- bet1; dataList$bet2 <- bet2
dataList$with <- with; dataList$against <- against
} else if ( substr(modelstr,1,15) == 'RevLearn_RLbeta' ) {
chswtch <- array(0,dim = c(ns,nt))
bet1 <- array(0,dim = c(ns,nt)); bet2 <- array(0,dim = c(ns,nt))
with <- array(0,dim = c(ns,nt)); against <- array(0,dim = c(ns,nt))
my1 <- 0; other1 <- c(0,0,0,0)
otherChoice1 <- array(0,dim = c(ns,nt,4));
otherChoice2 <- array(0,dim = c(ns,nt,4));
otherReward <- array(0,dim = c(ns,nt,4))
pref <- array(0,dim = c(ns,nt,4));
wOthers <- array(0,dim = c(ns,nt,4)) # others' weight [.75 .5 .25 .25]
wOthers_one <- array(0,dim = c(ns,nt,4)) # others' weight [ 3 2 1 1] / 7
wghtValue <- array(0,dim = c(ns,nt,2)) # others' value based on weight
cfsC2 <- array(0,dim = c(ns,nt,4)) # cumulative-window frequency, same as my C2
cfoC2 <- array(0,dim = c(ns,nt,4)) # cumulative-window frequency, opposite to my C2
wgtWith <- array(0,dim = c(ns,nt)); wgtWith_one <- array(0,dim = c(ns,nt))
wgtAgst <- array(0,dim = c(ns,nt)); wgtAgst_one <- array(0,dim = c(ns,nt))
otherCumAcc <- array(0,dim = c(ns,nt,4)); # cumulative accuracy according to reward probability
chswtch <- t(mydata[,5,])
bet1 <- t(mydata[,13,]); bet2 <- t(mydata[,19,])
wgtWith <- t(mydata[,93,]); wgtAgst <- t(mydata[,94,])
wgtWith_one <- t(mydata[,99,])
wgtAgst_one <- t(mydata[,100,])
for (s in 1:ns) {
otherChoice1[s,,] <- mydata[,6:9,s]
otherChoice2[s,,] <- mydata[,55:58,s]
otherReward[s,,] <- mydata[,24:27,s]
pref[s,,] <- mydata[,47:50,s]
wOthers[s,,] <- mydata[,51:54,s]
wOthers_one[s,,] <- mydata[,95:98,s]
wghtValue[s,,] <- mydata[,59:60,s]
cfsC2[s,,] <- mydata[,61:64,s]
cfoC2[s,,] <- mydata[,65:68,s]
otherCumAcc[s,,] <- mydata[,129:132,s]
for (t in 1:nt){
my1 <- mydata[t,3,s]; other1 <- mydata[t,6:9,s]
with[s,t] <- length(which(other1==my1)) /4
against[s,t] <- length(which(other1!=my1)) /4
}
}
dataList$chswtch <- chswtch;
dataList$otherChoice1 <- otherChoice1
dataList$otherChoice2 <- otherChoice2
dataList$otherReward <- otherReward
dataList$wghtValue <- wghtValue
dataList$bet1 <- bet1; dataList$bet2 <- bet2
dataList$with <- with; dataList$against <- against
dataList$pref <- pref; dataList$wOthers <- wOthers
dataList$cfsC2 <- cfsC2; dataList$cfoC2 <- cfoC2;
dataList$wgtWith <- wgtWith; dataList$wgtAgst <- wgtAgst
dataList$wOthers_one <- wOthers_one
dataList$wgtWith_one <- wgtWith_one
dataList$wgtAgst_one <- wgtAgst_one
dataList$otherCumAcc <- otherCumAcc
if ( substr(modelstr,1,20) == 'RevLearn_RLbeta_alt2' ) {
wProb_sC2 <- array(0,dim = c(ns,nt,4))
wProb_oC2 <- array(0,dim = c(ns,nt,4))
wProb_sC2_med <- array(0,dim = c(ns,nt,4))
wProb_oC2_med <- array(0,dim = c(ns,nt,4))
for (s in 1:ns) {
wProb_sC2[s,,] <- mydata[,81:84,s]
wProb_oC2[s,,] <- mydata[,85:88,s]
wProb_sC2_med[s,,] <- mydata[,109:112,s]
wProb_oC2_med[s,,] <- mydata[,113:116,s]
}
dataList$wProb_sC2 <- wProb_sC2
dataList$wProb_oC2 <- wProb_oC2
dataList$wProb_sC2_med <- wProb_sC2_med
dataList$wProb_oC2_med <- wProb_oC2_med
} else if (modelstr == "RevLearn_RLbeta_alt3_p2_v1" || modelstr == "RevLearn_RLbeta_alt3_p2_v1_w") {
L <- cal_prob_v1(dataList)
dataList$wProb_sC2 <- L$wProb_sC2
dataList$wProb_oC2 <- L$wProb_oC2
} else if (modelstr == "RevLearn_RLbeta_alt3_p2_v2") {
L <- cal_prob_v2(dataList)
dataList$wProb_sC2 <- L$wProb_sC2
dataList$wProb_oC2 <- L$wProb_oC2
} else if ( substr(modelstr,1,20) == 'RevLearn_RLbeta_alt4' || substr(modelstr,1,20) == 'RevLearn_RLbeta_alt5' ||
substr(modelstr,1,20) == 'RevLearn_RLbeta_alt6' || substr(modelstr,1,20) == 'RevLearn_RLbeta_alt7' ) {
otherReward2 <- array(0,dim = c(ns,nt,4))
otherReward2_actural <- array(0,dim = c(ns,nt,4))
otherWith2 <- array(0,dim = c(ns,nt,4))
for (s in 1:ns) {
otherReward2[s,,] <- mydata[,24:27,s]
otherWith2[s,,] <- mydata[,89:92,s] # otherChoice2 == myChoice2, with(1) or against(0)
}
otherReward2_actural <- otherReward2
if (modelstr != "RevLearn_RLbeta_alt4_c_w_v12_1lr" && modelstr != "RevLearn_RLbeta_alt4_c_w_v21_1lr" &&
modelstr != "RevLearn_RLbeta_alt4_c_w_v25_1lr" && modelstr != "RevLearn_RLbeta_alt4_c_w_v27_1lr") {
otherReward2[otherReward2 == -1] = 0
}
dataList$otherReward2 <- otherReward2 # [0 1] OR [-1 1]
dataList$otherReward2_actural <- otherReward2_actural ## always [-1 1]
dataList$otherWith2 <- otherWith2
}
} else if ( substr(modelstr,1,17) == "RevLearn_RLcumrew" ) {
otherChoice1 <- array(0,dim = c(ns,nt,4))
otherReward <- array(0,dim = c(ns,nt,4))
otherWith <- array(0,dim = c(ns,nt,4))
for (s in 1:ns) {
otherChoice1[s,,] <- mydata[,6:9,s]
otherReward[s,,] <- mydata[,24:27,s]
otherWith[s,,] <- mydata[,69:72,s] # otherChoice1 == myChoice1, with(1) or against(0)
}
otherReward[otherReward == -1] = 0
dataList$otherChoice1 <- otherChoice1
dataList$otherReward <- otherReward
dataList$otherWith <- otherWith
}
return(dataList)
} # function
# ------------------------------------------------------------------------------------------------------
create_pois <- function(model){
pois <- list()
if (model == "RevLearn_RL" || model == "RevLearn_RLnc"){
pois <- c("lr_mu", "tau_mu",
"lr_sd", "tau_sd",
"lr", "tau",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLnc_2lr") {
pois <- c("lr1_mu", "lr2_mu", "tau_mu",
"lr1_sd", "lr2_sd", "tau_sd",
"lr1", "lr2", "tau",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLnc_cfa") {
pois <- c("lr_mu", "tau_mu", "cfa_mu",
"lr_sd", "tau_sd", "cfa_sd",
"lr", "tau", "cfa",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLnc_2lr_cfa") {
pois <- c("lr1_mu", "lr2_mu", "tau_mu", "cfa_mu",
"lr1_sd", "lr2_sd", "tau_sd", "cfa_sd",
"lr1", "lr2", "tau", "cfa",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcoh"){
pois <- c("lr_mu", "tau_mu", "coha_mu", "cohw_mu",
"lr_sd", "tau_sd", "coha_sd", "cohw_sd",
"lr", "tau", "coha", "cohw",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcoh_2lr"){
pois <- c("lr1_mu", "lr2_mu", "tau_mu", "coha_mu", "cohw_mu",
"lr1_sd", "lr2_sd", "tau_sd", "coha_sd", "cohw_sd",
"lr1", "lr2", "tau", "coha", "cohw",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcoh_cfa") {
pois <- c("lr_mu", "tau_mu", "coha_mu", "cohw_mu", "cfa_mu",
"lr_sd", "tau_sd", "coha_sd", "cohw_sd", "cfa_sd",
"lr", "tau", "coha", "cohw", "cfa",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcoh_2lr_cfa") {
pois <- c("lr1_mu", "lr2_mu", "tau_mu", "coha_mu", "cohw_mu", "cfa_mu",
"lr1_sd", "lr2_sd", "tau_sd", "coha_sd", "cohw_sd", "cfa_sd",
"lr1", "lr2", "tau", "coha", "cohw", "cfa",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcoh_modvalue" || model == "RevLearn_RLcoh_modprob_tempin" || model == "RevLearn_RLcoh_modprob_tempout"){
pois <- c("lr_mu", "tau_mu", "coha_mu", "cohw_mu",
"lr_sd", "tau_sd", "coha_sd", "cohw_sd",
"lr", "tau", "coha", "cohw",
"log_lik1",
"log_lik2", "lp__")
} else if (model == "RevLearn_RLcoh_2lr2t_modvalue" || model == "RevLearn_RLcoh_2lr2t_modprob_tempin" ||
model == "RevLearn_RLcoh_2lr2t_modprob_tempout" || model == "RevLearn_RLcoh_2lr2t_modprob_tempin_bern") {
pois <- c("lr1_mu", "tau1_mu", "lr2_mu", "tau2_mu", "coha_mu", "cohw_mu",
"lr1_sd", "tau1_sd", "lr2_sd", "tau2_sd", "coha_sd", "cohw_sd",
"lr1", "tau1", "lr2", "tau2", "coha", "cohw",
"log_lik1",
"log_lik2", "lp__")
} else if (model == "RevLearn_RLcumrew" ) {
pois <- c("lr_mu", "tau_mu", "disc_mu", "cra_mu", "crw_mu",
"lr_sd", "tau_sd", "disc_sd", "cra_sd", "crw_sd",
"lr", "tau", "disc", "cra", "crw",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcumrew_2lr" ) {
pois <- c("lr1_mu", "lr2_mu", "tau_mu", "disc_mu", "cra_mu", "crw_mu",
"lr1_sd", "lr2_sd", "tau_sd", "disc_sd", "cra_sd", "crw_sd",
"lr1", "lr2", "tau", "disc", "cra", "crw",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcumrew_cfa" ) {
pois <- c("lr_mu", "tau_mu", "disc_mu", "cra_mu", "crw_mu", "cfa_mu",
"lr_sd", "tau_sd", "disc_sd", "cra_sd", "crw_sd", "cfa_sd",
"lr", "tau", "disc", "cra", "crw", "cfa",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLcumrew_2lr_cfa" ) {
pois <- c("lr1_mu", "lr2_mu", "tau_mu", "disc_mu", "cra_mu", "crw_mu", "cfa_mu",
"lr1_sd", "lr2_sd", "tau_sd", "disc_sd", "cra_sd", "crw_sd", "cfa_sd",
"lr1", "lr2", "tau", "disc", "cra", "crw", "cfa",
"c_rep",
"log_lik", "lp__")
} else if (model == "RevLearn_RLbeta_alt1_bc") {
pois <- c("lr_mu", "thrs_mu", "beta_mu",
"lr_sd", "thrs_sd", "beta_sd",
"lr", "thrs", "beta",
"log_likc1", "log_likc2", "log_likb1", "log_likb2", "lp__")
} else if ( substr(model,1,22) == 'RevLearn_RLbeta_alt1_c' || substr(model,1,25) == 'RevLearn_RLbeta_alt2_c_v2' ||
substr(model,1,23) == 'RevLearn_RLbeta_alt3_p2' ) {
pois <- c("lr_mu", "beta_mu",
"lr_sd", "beta_sd",
"lr", "beta",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if (model == "RevLearn_RLbeta_alt2_bc") {
pois <- c("lr_mu", "thrs_mu", "evid_wght_mu", "beta_mu",
"lr_sd", "thrs_sd", "evid_wght_sd", "beta_sd",
"lr", "thrs", "evid_wght", "beta",
"log_likc1", "log_likc2", "log_likb1", "log_likb2", "lp__")
} else if ( substr(model,1,25) == 'RevLearn_RLbeta_alt2_c_v1' ) {
pois <- c("lr_mu", "evidW_mu", "beta_mu",
"lr_sd", "evidW_sd", "beta_sd",
"lr", "evidW", "beta",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if (model == "RevLearn_RLbeta_alt3_p1_v1" || model == "RevLearn_RLbeta_alt3_p1_v2") {
pois <- c("lr_mu", "tau_mu",
"lr_sd", "tau_sd",
"lr", "tau",
"lp__")
} else if ( model == 'RevLearn_RLbeta_alt4_c_w_v10_1lr' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu", "cfa_mu",
"lr_sd", "beta_sd", "disc_sd", "cfa_sd",
"lr", "beta", "disc", "cfa",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( model == 'RevLearn_RLbeta_alt4_c_w_v15_1lr' ) {
pois <- c("lr", "beta", "disc",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( model == 'RevLearn_RLbeta_alt4_c_w_v23_1lr' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu", "tau_mu",
"lr_sd", "beta_sd", "disc_sd", "tau_sd",
"lr", "beta", "disc", "tau",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( substr(model,1,20) == 'RevLearn_RLbeta_alt4' || substr(model,1,20) == 'RevLearn_RLbeta_alt5' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu",
"lr_sd", "beta_sd", "disc_sd",
"lr", "beta", "disc",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if (substr(model,1,20) == 'RevLearn_RLbeta_alt6') {
pois <- c("lr_mu", "beta_mu", "disc_mu", "tau_mu",
"lr_sd", "beta_sd", "disc_sd", "tau_sd",
"lr", "beta", "disc", "tau",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( model == 'RevLearn_RLbeta_alt7_c_w_v2_1lr' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu", "cfa_mu",
"lr_sd", "beta_sd", "disc_sd", "cfa_sd",
"lr", "beta", "disc", "cfa",
"c1_rep", "c2_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( model == 'RevLearn_RLbeta_alt7_c_w_v3_1lr' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu", "beta0_mu",
"lr_sd", "beta_sd", "disc_sd", "beta0_sd",
"lr", "beta", "disc", "beta0",
"c1_rep", "c2_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( model == 'RevLearn_RLbeta_alt7_c_w_v5_1lr' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu", "bias_mean",
"lr_sd", "beta_sd", "disc_sd", "bias_sd",
"lr", "beta", "disc", "beta0", "bias",
"c1_rep", "c2_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( substr(model,1,20) == 'RevLearn_RLbeta_alt7' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu",
"lr_sd", "beta_sd", "disc_sd",
"lr", "beta", "disc",
"c1_rep", "c2_rep",
"log_likc1", "log_likc2", "lp__")
}
return(pois)
} # function
#### end of function ####<file_sep># Get this figure: fig <- py$get_figure("etpinard", 199)
# Get this figure's data: data <- py$get_figure("etpinard", 199)$data
# Add data to this figure: py$plotly(list(x=c(4, 5), y=c(4, 5)), kwargs=list(filename="s4_grades-box-styled2", fileopt="extend"))
# Get y data of first trace: y1 <- py$get_figure("etpinard", 199)$data[[1]]$y
# Get figure documentation: https://plot.ly/r/get-requests/
# Add data documentation: https://plot.ly/r/file-options/
# You can reproduce this figure in R with the following code!
# Learn about API authentication here: https://plot.ly/r/getting-started
# Find your api_key here: https://plot.ly/settings/api
library(plotly)
py <- plotly(username='llsquare', key='90xamoida4')
trace1 <- list(
y = c(90.0, 88.0, 55.0, 88.0, 72.0, 100.0, 88.0, 25.0, 92.0, 100.0, 82.0, 82.0, 90.0, 68.0, 85.0, "", 82.0, 40.0, 100.0, 92.0, 82.0, 55.0, 62.0, 85.0, 100.0, 75.0, 88.0, 78.0, 80.0, "", 92.0, 100.0, 88.0, 72.0, 95.0, 80.0, 90.0, 72.0, 100.0, "", 100.0, 75.0, 82.0, 60.0, 90.0, 85.0, 90.0, 38.0, 78.0, 82.0, 100.0, 90.0, 80.0, "", 80.0, 100.0, 70.0, 100.0, 82.0, 62.0, 92.0, "", 100.0, 80.0, "", 100.0, 88.0, 85.0),
boxmean = "sd",
boxpoints = "all",
jitter = 0.5,
line = list(color = "#1c9099"),
marker = list(
color = "#feb24c",
line = list(
color = "#FFFFFF",
width = 1
),
size = 10
),
name = "Homeworks",
pointpos = -2,
type = "box"
)
trace2 <- list(
y = c(70.0, 65.0, 85.0, 75.0, 72.0, 75.0, 90.0, 88.0, 85.0, 80.0, 92.0, 85.0, 85.0, 75.0, 72.0, "", 80.0, 42.0, 80.0, 95.0, 90.0, 62.0, 65.0, 65.0, 82.0, 68.0, 48.0, 57.0, 95.0, 70.0, 100.0, 80.0, 95.0, 78.0, 80.0, 80.0, 85.0, 90.0, 100.0, 52.0, 85.0, 72.0, 70.0, 45.0, 75.0, 85.0, 95.0, 65.0, 70.0, 85.0, 70.0, 85.0, 35.0, "", 90.0, 95.0, 95.0, 65.0, 62.0, 48.0, 60.0, "", 85.0, 85.0, "", 90.0, 70.0, 68.0),
boxmean = "sd",
boxpoints = "all",
jitter = 0.5,
line = list(color = "#1c9099"),
marker = list(
color = "#feb24c",
line = list(
color = "#FFFFFF",
width = 1
),
size = 10
),
name = "Midterm Exam",
pointpos = -2,
type = "box"
)
trace3 <- list(
y = c(95.0, 75.0, 70.0, 72.0, 52.0, 70.0, 82.0, 90.0, 95.0, 80.0, 68.0, 88.0, 82.0, 52.0, 80.0, "", 78.0, 57.0, 88.0, 88.0, 100.0, 50.0, 65.0, 78.0, 92.0, 65.0, 50.0, 60.0, 88.0, "", 100.0, 50.0, 90.0, 70.0, 60.0, 72.0, 75.0, 95.0, 100.0, 45.0, 68.0, 72.0, 45.0, 60.0, 78.0, 85.0, 92.0, 45.0, 68.0, 70.0, 85.0, 82.0, 62.0, "", 75.0, 100.0, 80.0, 65.0, 52.0, 48.0, 57.0, "", 100.0, 72.0, "", 100.0, 80.0, 65.0),
boxmean = "sd",
boxpoints = "all",
jitter = 0.5,
line = list(color = "#1c9099"),
marker = list(
color = "#feb24c",
line = list(
color = "#FFFFFF",
width = 1
),
size = 10
),
name = "Final Exam",
pointpos = -2,
type = "box"
)
trace4 <- list(
y = c(86.0, 75.9, 70.0, 77.7, 64.0, 80.5, 86.2, 69.9, 91.1, 86.0, 79.4, 85.3, 85.3, 63.7, 79.1, "", 79.8, 47.4, 89.2, 91.3, 91.6, 55.1, 64.1, 76.2, 91.4, 68.9, 60.8, 64.5, 87.7, 21.0, 97.6, 74.0, 90.9, 73.0, 76.5, 76.8, 82.5, 86.6, 100.0, 33.6, 82.7, 72.9, 63.6, 55.5, 80.7, 85.0, 92.3, 48.9, 71.6, 78.1, 85.0, 85.3, 59.3, "", 81.0, 98.5, 81.5, 75.5, 64.0, 52.2, 68.4, "", 95.5, 78.3, "", 97.0, 79.4, 71.9),
boxmean = "sd",
boxpoints = "all",
jitter = 0.5,
line = list(color = "#1c9099"),
marker = list(
color = "#feb24c",
line = list(
color = "#FFFFFF",
width = 1
),
size = 10
),
name = "Course Grade",
pointpos = -2,
type = "box"
)
data <- list(trace1, trace2, trace3, trace4)
layout <- list(
autosize = FALSE,
height = 500,
plot_bgcolor = "#EFECEA",
showlegend = FALSE,
title = "Fig 4.4c: Course Grade Distributions",
width = 650,
xaxis = list(
gridcolor = "#FFFFFF",
showgrid = TRUE,
ticklen = 8,
ticks = "outside",
tickwidth = 1.5,
zeroline = FALSE
),
yaxis = list(
gridcolor = "#FFFFFF",
showgrid = TRUE,
ticklen = 8,
ticks = "outside",
tickwidth = 1.5,
title = "Grade [%]",
zeroline = FALSE
)
)
response <- py$plotly(data, kwargs=list(layout=layout))
url <- response$url<file_sep>N <- 50
x <- rnorm(N)
y <- rnorm(N,3,1.2)
L <- list()
L$N <- N
L$x <- x
L$y <- y
library(rstan)
stanfit <- stan("_scripts/toy_model.stan",
data = L,
chains = 1,
iter = 5,
control = list(adapt_delta=0.85),
init = "random",
verbose = FALSE)
<file_sep>corr_b1b2 <- function(stanfit, plot_sct=FALSE) {
if ( class(stanfit)=='stanfit' ) {
stanfit <- stanfit
} else {
stanfit <- stanfit$fit
}
parm <- get_posterior_mean(stanfit, 'beta')
parm <- as.matrix(parm[1:258,5])
b1 <- parm[1:129]
b2 <- parm[130:258]
r <- cor.test(b1,b2)
if (plot_sct == TRUE) {
library(ggplot2)
q <- qplot(b1,b2,geom='point')
print(q)
}
return(r)
}
<file_sep>ppc <- function(stanfit, type = NULL, swch = FALSE, sid = NULL, gid = NULL) {
## ppc: posterior predictive check=====================================
# type - NULL(default), 1(1st choice) or 2(2nd choice)
# swch - T(2nd choice 0/1) or F(2nd choice 1/2)
# sid - subject ID
# gid - group ID
#### data preparation and initialize -----------------------------------
library(rstan); library(ggplot2); library(reshape2)
load("_data/sit_reversal_betnoshow_129.rdata")
sz <- dim(mydata)
nt <- sz[1]; ns <- sz[3]
choice1 <- array(0,dim = c(ns,nt)); choice2 <- array(0,dim = c(ns,nt)); reversal <- array(0,dim = c(ns,nt))
choice1 <- t(mydata[,3,]); choice2 <- t(mydata[,10,]); reversal <- t(mydata[,2,])
chswtch <- array(0,dim = c(ns,nt)); chswtch <- t(mydata[,5,])
acc <- array(0,dim = c(ns,nt))
if ( class(stanfit)=='stanfit' ) {
stanfit <- stanfit
} else {
stanfit <- stanfit$fit
}
if ( is.null(type) ) {
c_rep <- extract(stanfit, pars="c_rep", permuted=TRUE)$c_rep
choice <- choice2
} else if (type == 1) {
c_rep <- extract(stanfit, pars="c_rep1", permuted=TRUE)$c_rep1
choice <- choice1
} else if (type == 2) {
c_rep <- extract(stanfit, pars="c_rep2", permuted=TRUE)$c_rep2
choice <- choice2
}
niter <- dim(c_rep)[1]
#### calculate ppc accuracy --------------------------------------------
for (s in 1:ns) {
for (t in 1:nt) {
if (swch == FALSE) {
acc[s,t] <- sum(c_rep[,s,t]==choice[s,t]) / niter
} else {
acc[s,t] <- sum(c_rep[,s,t]==chswtch[s,t]) / niter
}
}
}
acc_sub <- rowMeans(acc)
acc_grd <- mean(acc)
#### visualize the results =============================================================
## plot per subject, plus the reversal point -------------------------------------------
if (!is.null(sid)) {
theme_set(theme_bw(base_size = 18))
accuracy = acc[sid,]
trial = 1:nt
df <- data.frame(trial = trial, accuracy=accuracy)
p <- ggplot(df, aes(x = trial, y = accuracy))
p <- p + geom_line(size = 1.2, color = "dodgerblue4") + ylim(0,1)
p <- p + geom_vline(xintercept=which(reversal[sid,]==1), colour="red",
linetype="longdash")
print(p)
}
## plot for total (grand mean) ----- not too much sence...
# qplot(1:100, colMeans(acc), geom ='line')
## plot each subject in a grid (facet), per subject group ------------------------------
## note that there are only 129 subjects!!! therefore this plot is not perfect!!!
if (!is.null(gid)) {
df1 <- as.data.frame(t(acc))
colnames(df1) <- c(paste0("subj", 1:ns))
df1$trial <- 1:nt
df2 <- as.data.frame(t(reversal))
colnames(df2) <- c(paste0("subj", 1:ns))
df2$trial <- 1:nt
# long-format data frame
ldf1 <- melt(df1, id="trial")
ldf2 <- melt(df2, id="trial")
ldf <- ldf1
colnames(ldf) <- c("trial", "subj","accuracy")
ldf$reversal <- ldf2$value
grp <- ldf[(1+(gid-1)*500):(500+(gid-1)*500),]
p2 = ggplot(grp, aes(x = trial, y = accuracy) )
p2 = p2 + geom_line()
p2 = p2 + facet_grid(subj ~ ., scales = "free_y")
p2 = p2 + geom_vline(xintercept=which(grp$reversal[1:100]==1), colour="red", linetype="longdash")
print(p2)
}
return(list(acc=acc,acc_sub=acc_sub,acc_grd=acc_grd))
}
#### end of fucntion<file_sep>cal_prob_v2 <- function(dataList) {
## this function is part of the RLbeta_alt3 model
## it computes the action selection probability based on the learning rate and temperature
## obtained from 'RevLearn_RLbeta_alt3_p1'
## the action probability is then plugged into 'RevLearn_RLbeata_alt3_p2'
L <- list()
ns <- dataList$nSubjects
nt <- dataList$nTrials
choice2 <- dataList$choice2
wOthers <- dataList$wOthers
otherChoice2 <- dataList$otherChoice2
otherReward <- dataList$otherReward
load('_outputs/param_beta_alt3_v2.RData')
params <- array(param_beta_alt3_v2, c(129,8))
lr <- params[,1:4]
tau <- params[,5:8]
pe <- array(0,dim=c(nt,4))
v <- array(0,dim=c(nt+1,4,2))
prob <- array(0,dim=c(ns,nt,4,2))
prob_sC2 <- array(0,dim=c(ns,nt,4))
prob_oC2 <- array(0,dim=c(ns,nt,4))
wProb_sC2 <- array(0,dim=c(ns,nt,4))
wProb_oC2 <- array(0,dim=c(ns,nt,4))
for (s in 1:ns) {
for (t in 1:nt) {
for (o in 1:4) {
prob[s,t,o,1] <- 1 / (1 + exp(tau[s,o] * (v[t,o,2]-v[t,o,1]) ))
prob[s,t,o,2] <- 1 / (1 + exp(tau[s,o] * (v[t,o,1]-v[t,o,2]) ))
pe[t,o] <- otherReward[s,t,o] - v[t,o,otherChoice2[s,t,o]];
v[t+1,o,] <- v[t,o,];
v[t+1,o,otherChoice2[s,t,o]] <- v[t,o,otherChoice2[s,t,o]] + lr[s,o] * pe[t,o];
## calculated weighted action prob as the same/oppose to MY 2nd choice
prob_sC2[s,t,o] <- prob[s,t,o,choice2[s,t]]
}
prob_oC2[s,t,] <- 1 - prob_sC2[s,t,]
wProb_sC2[s,t,] <- wOthers[s,t,] * prob_sC2[s,t,]
wProb_oC2[s,t,] <- wOthers[s,t,] * prob_oC2[s,t,]
} # trial loop
} # subject loop
L$wProb_sC2 <- wProb_sC2
L$wProb_oC2 <- wProb_oC2
return(L)
} # fucntion
# end of function<file_sep>source("_scripts/stan_run.R")
source("_scripts/compute_map.r")
source("_scripts/get_mcmc.R")
source("_scripts/cal_prob_v1.R")
source("_scripts/cal_prob_v2.R")
source("_scripts/ppc.R")
source("_scripts/corr_b1b2.R")
source("_scripts/extract_looic.R")
source("_scripts/extract_otheric.R")
source("_scripts/beta_barplot.R")
source("_scripts/beta_corplot.R")
#source("_scripts/DBDA2E-utilities.R")
library(rstan)
library(shinystan)
library(loo)
library(R.matlab)
# ---- convert .mat data into .RData
# t <- readMat("_data/data3_129.mat")
# mydata <- t$data3
# save(mydata, file = '_data/sit_reversal_betnoshow_129.rdata')
# ---- obtain mcmc -----------------------
# mcmcCoda <- mcmc.list( lapply( 1:ncol(out1), function(x){mcmc(as.array(out1)[,x,])}))
# mcmc <- combine.mcmc(mcmcCoda)
#
# # ---- diagnostic plots ------------------
# diagMCMC(mcmcCoda, parName=c("lr_mu"))
# diagMCMC(mcmcCoda, parName=c("tau_mu"))
# diagMCMC(mcmcCoda, parName=c("lr[1]"))
# diagMCMC(mcmcCoda, parName=c("tau[1]"))
#
# plotPost(mcmcCoda[,"lr_mu"], main = "lr_mu", xlab = bquote(lr_mu), cenTend = "mode")
# plotPost(mcmcCoda[,"tau_mu"], main = "tau_mu", xlab = bquote(tau_mu), cenTend = "mode")
# plotPost(mcmcCoda[,"lr[1]"], main = "lr[1]", xlab = bquote(lr[1]), cenTend = "mode")
# plotPost(mcmcCoda[,"tau[1]"], main = "tau[1]", xlab = bquote(tau[1]), cenTend = "mode")
## end of script ##<file_sep>source("_scripts/stan_source.R")
library(ggplot2)
library(reshape2)
fit_RL <- readRDS("_outputs/fit_RL.RData")
lik_RL <- extract_log_lik(fit_RL, parameter_name = "log_lik")
loo_RL <- loo(lik_RL, cores = 4)
loo_RL_pw <- as.matrix(loo_RL$pointwise[,3] )
fit_RLnc <- readRDS("_outputs/fit_RLnc_2lr.RData")
lik_RLnc <- extract_log_lik(fit_RLnc, parameter_name = "log_lik")
loo_RLnc <- loo(lik_RLnc, cores = 4)
loo_RLnc_pw <- as.matrix(loo_RLnc$pointwise[,3] )
fit_RLcoh <- readRDS("_outputs/fit_RLcoh_2lr_cfa.RData")
lik_RLcoh <- extract_log_lik(fit_RLcoh, parameter_name = "log_lik")
loo_RLcoh <- loo(lik_RLcoh, cores = 3)
loo_RLcoh_pw <- as.matrix(loo_RLcoh$pointwise[,3] )
fit_RLcr <- readRDS("_outputs/fit_RLcumrew_2lr.RData")
lik_RLcr <- extract_log_lik(fit_RLcr, parameter_name = "log_lik")
loo_RLcr <- loo(lik_RLcr, cores = 3)
loo_RLcr_pw <- as.matrix(loo_RLcr$pointwise[,3] )
save(loo_RL_pw, loo_RLnc_pw, loo_RLcoh_pw, loo_RLcr_pw,
file = '_outputs/looic.RData')
looMat = cbind(loo_RL_pw, loo_RLnc_pw, loo_RLcoh_pw, loo_RLcr_pw)
save(looMat, file = '_outputs/looicMat.RData')
#### plot ####
load(file = '_outputs/looicMat.RData')
looDF <- melt(looMat)
colnames(looDF) <- c('subID', 'modelName', 'LOOIC')
looDF$modelName <- c(rep('RL', 129), rep('RLnc',129),
rep('RLcoh',129), rep('RLcumrew',129))
modelName <- c('RL','RLnc','RLcoh','RLcumrew')
looDF$modelName <- factor(looDF$modelName, levels = modelName)
theme_set(theme_gray(base_size = 20))
ggplot(data=looDF, aes(modelName, LOOIC)) + geom_boxplot(aes(fill = modelName))
#### individual ####
source("http://bioconductor.org/biocLite.R")
biocLite("Biobase")
minlooic <- do.call(pmin, as.data.frame(looMat))
minMat <- kronecker(matrix(1,1,4),minlooic)
colSums((minMat == looMat))
#### use subj66 for plot the ppc
source('_scripts/ppc.R')
ppc_RL <- ppc(fit_RL, sid = 66)
ppc_RLnc <- ppc(fit_RLnc, sid = 66)
ppc_RLcoh <- ppc(fit_RLcoh, sid = 66)
ppc_RLcr <- ppc(fit_RLcr, sid = 66)
save(ppc_RL,ppc_RLnc,ppc_RLcoh,ppc_RLcr,file= 'ppc2.RData')
<file_sep>run_model_toy <- function(modelStr, test = TRUE, fitObj = NA, adapt = 0.8) {
library(rstan); library(parallel); library(loo)
L <- list()
#### prepare data #### ===========================================================================
dataList <- prep_data(modelStr)
#### preparation for running stan #### ============================================================
# model string in a separate .stan file
modelFile <- paste0("_scripts/",modelStr,".stan")
# setup up Stan configuration
if (test == TRUE) {
options(mc.cores = 1)
nSamples <- 4
nChains <- 1
nBurnin <- 0
nThin <- 1
} else {
options(mc.cores = 4)
nSamples <- 2000#2000
nChains <- 4
nBurnin <- floor(nSamples/2)
nThin <- 1#1
}
# parameter of interest (this could save both memory and space)
poi <- create_pois(modelStr)
#### run stan #### ==============================================================================
cat("Estimating", modelStr, "model... \n")
startTime = Sys.time(); print(startTime)
cat("Calling", nChains, "simulations in Stan... \n")
rstan_options(auto_write = TRUE)
stanfit <- stan(modelFile,
fit = fitObj,
data = dataList,
pars = poi,
chains = nChains,
iter = nSamples,
warmup = nBurnin,
thin = nThin,
init = "random",
#seed = 1581381385, # for RLbeta_alt3_p2_v2, LOOIV 8217
#seed = 295171225, # for RLbeta_alt2_v1, LOOIC 8216
seed = 1450154626, # for alt4_
#seed = 1136699103, # alt4_, seems even lower looic
control = list(adapt_delta = adapt),
verbose = FALSE)
cat("Finishing", modelStr, "model simulation ... \n")
endTime = Sys.time(); print(endTime)
cat("It took",as.character.Date(endTime - startTime), "\n")
L$data <- dataList
L$fit <- stanfit
return(L)
} # function run_model()
#### nested functions #### ===========================================================================
prep_data <- function(modelstr){
load("_data/sit_reversal_betnoshow_129.rdata")
mydata <- mydata[,,62:63]
dataList <- list()
sz <- dim(mydata)
nt <- sz[1]; ns <- sz[3]
dataList$nSubjects <- ns; dataList$nTrials <- nt
choice1 <- array(0,dim = c(ns,nt)); choice2 <- array(0,dim = c(ns,nt)); reward <- array(0,dim = c(ns,nt))
choice1 <- t(mydata[,3,]) # 1 OR 2
choice2 <- t(mydata[,10,]) # 1 OR 2
reward <- t(mydata[,14,]) # 1 OR -1
dataList$choice1 <- choice1
dataList$choice2 <- choice2
dataList$reward <- reward
chswtch <- array(0,dim = c(ns,nt))
bet1 <- array(0,dim = c(ns,nt)); bet2 <- array(0,dim = c(ns,nt))
with <- array(0,dim = c(ns,nt)); against <- array(0,dim = c(ns,nt))
my1 <- 0; other1 <- c(0,0,0,0)
otherChoice1 <- array(0,dim = c(ns,nt,4));
otherChoice2 <- array(0,dim = c(ns,nt,4));
otherReward <- array(0,dim = c(ns,nt,4))
pref <- array(0,dim = c(ns,nt,4));
wOthers <- array(0,dim = c(ns,nt,4)) # others' weight [.75 .5 .25 .25]
wOthers_one <- array(0,dim = c(ns,nt,4)) # others' weight [ 3 2 1 1] / 7
wghtValue <- array(0,dim = c(ns,nt,2)) # others' value based on weight
cfsC2 <- array(0,dim = c(ns,nt,4)) # cumulative-window frequency, same as my C2
cfoC2 <- array(0,dim = c(ns,nt,4)) # cumulative-window frequency, opposite to my C2
wgtWith <- array(0,dim = c(ns,nt)); wgtWith_one <- array(0,dim = c(ns,nt))
wgtAgst <- array(0,dim = c(ns,nt)); wgtAgst_one <- array(0,dim = c(ns,nt))
otherCumAcc <- array(0,dim = c(ns,nt,4)); # cumulative accuracy according to reward probability
chswtch <- t(mydata[,5,])
bet1 <- t(mydata[,13,]); bet2 <- t(mydata[,19,])
wgtWith <- t(mydata[,93,]); wgtAgst <- t(mydata[,94,])
wgtWith_one <- t(mydata[,99,])
wgtAgst_one <- t(mydata[,100,])
for (s in 1:ns) {
otherChoice1[s,,] <- mydata[,6:9,s]
otherChoice2[s,,] <- mydata[,55:58,s]
otherReward[s,,] <- mydata[,24:27,s]
pref[s,,] <- mydata[,47:50,s]
wOthers[s,,] <- mydata[,51:54,s]
wOthers_one[s,,] <- mydata[,95:98,s]
wghtValue[s,,] <- mydata[,59:60,s]
cfsC2[s,,] <- mydata[,61:64,s]
cfoC2[s,,] <- mydata[,65:68,s]
otherCumAcc[s,,] <- mydata[,129:132,s]
for (t in 1:nt){
my1 <- mydata[t,3,s]; other1 <- mydata[t,6:9,s]
with[s,t] <- length(which(other1==my1)) /4
against[s,t] <- length(which(other1!=my1)) /4
}
}
dataList$chswtch <- chswtch;
dataList$otherChoice1 <- otherChoice1
dataList$otherChoice2 <- otherChoice2
dataList$otherReward <- otherReward
dataList$wghtValue <- wghtValue
dataList$bet1 <- bet1; dataList$bet2 <- bet2
dataList$with <- with; dataList$against <- against
dataList$pref <- pref; dataList$wOthers <- wOthers
dataList$cfsC2 <- cfsC2; dataList$cfoC2 <- cfoC2;
dataList$wgtWith <- wgtWith; dataList$wgtAgst <- wgtAgst
dataList$wOthers_one <- wOthers_one
dataList$wgtWith_one <- wgtWith_one
dataList$wgtAgst_one <- wgtAgst_one
dataList$otherCumAcc <- otherCumAcc
if ( substr(modelstr,1,20) == 'RevLearn_RLbeta_alt4' || substr(modelstr,1,20) == 'RevLearn_RLbeta_alt5' ) {
otherReward2 <- array(0,dim = c(ns,nt,4))
otherWith2 <- array(0,dim = c(ns,nt,4))
for (s in 1:ns) {
otherReward2[s,,] <- mydata[,24:27,s]
otherWith2[s,,] <- mydata[,89:92,s] # otherChoice2 == myChoice2, with(1) or against(0)
}
if (modelstr != "RevLearn_RLbeta_alt4_c_w_v12_1lr" && modelstr != "RevLearn_RLbeta_alt4_c_w_v21_1lr" &&
modelstr != "RevLearn_RLbeta_alt4_c_w_v25_1lr" && modelstr != "RevLearn_RLbeta_alt4_c_w_v27_1lr") {
otherReward2[otherReward2 == -1] = 0
}
dataList$otherReward2 <- otherReward2
dataList$otherWith2 <- otherWith2
}
return(dataList)
} # function
# ------------------------------------------------------------------------------------------------------
create_pois <- function(model){
pois <- list()
if ( model == 'RevLearn_RLbeta_alt4_c_w_v10_1lr' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu", "cfa_mu",
"lr_sd", "beta_sd", "disc_sd", "cfa_sd",
"lr", "beta", "disc", "cfa",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( model == 'RevLearn_RLbeta_alt4_c_w_v15_1lr' ) {
pois <- c("lr", "beta", "disc",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( model == 'RevLearn_RLbeta_alt4_c_w_v23_1lr' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu", "tau_mu",
"lr_sd", "beta_sd", "disc_sd", "tau_sd",
"lr", "beta", "disc", "tau",
"c_rep",
"log_likc1", "log_likc2", "lp__")
} else if ( substr(model,1,20) == 'RevLearn_RLbeta_alt4' || substr(model,1,20) == 'RevLearn_RLbeta_alt5' ) {
pois <- c("lr_mu", "beta_mu", "disc_mu",
"lr_sd", "beta_sd", "disc_sd",
"lr", "beta", "disc",
"c_rep",
"log_likc1", "log_likc2", "lp__")
}
return(pois)
} # function
#### end of function ####<file_sep>compute_map <- function(fitObj, meth = "density", calBeta = F) {
library(modeest); library(coda); library(runjags)
startTime = Sys.time()
if ( class(fitObj) == 'mcmc' ) {
mcmc <- fitObj
} else if ( class(fitObj) == 'mcmc.list' ) {
mcmc <- combine.mcmc(fitObj)
} else {
if (class(fitObj) != 'stanfit') {
fitObj <- fitObj$fit
}
mcmcCoda <- mcmc.list( lapply( 1:ncol(fitObj) , function(x) {mcmc(as.array(fitObj)[,x,])}))
mcmc <- combine.mcmc(mcmcCoda)
}
if (calBeta == T) {
b_start <- which( colnames(mcmc) == 'beta[1,1]' )
b_end <- which( colnames(mcmc) == 'beta[6,129]' )
mcmc <- mcmc[, b_start:b_end]
sz <- dim(mcmc)
map <- array(0,dim=c(sz[2],1))
} else {
sz <- dim(mcmc)
map <- array(0,dim=c(sz[2],1))
}
for (f in 1:sz[2]) {
tmp <- mlv(mcmc[,f], method=meth)
map[f] <- mean(tmp$M)
}
rownames(map) <- colnames(mcmc)
if (calBeta == T) {
map <- t(matrix(map, nrow = 6))
}
endTime = Sys.time()
cat("It took",as.character.Date(endTime - startTime), "\n")
return(map)
}
| c15f8226913fa174cab560b32f64ec31cafd5825 | [
"Markdown",
"R"
] | 21 | R | lei-zhang/sit_stan | be3e2adcf2ce2751ed6e243672f35b16938c7b53 | d475d22393a34891beeb07577baf70c97eb76ab1 |
refs/heads/master | <repo_name>matt90github/BestPropertyMalta<file_sep>/app/database/migrations/2014_02_11_181504_create_interests_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateInterestsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('interests', function ($table) {
$table->increments('interest_id');
$table->unsignedInteger('interest_customerId');
$table->foreign('interest_customerId')
->references('customer_id')->on('customers')
->onDelete('cascade')
->onUpdate('cascade');
$table->unsignedInteger('interest_propertyId');
$table->foreign('interest_propertyId')
->references('property_id')->on('properties')
->onDelete('cascade')
->onUpdate('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('interests');
}
}<file_sep>/app/controllers/WebsiteController.php
<?php
//Official Website Controller Class
class WebsiteController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Show the Official Website home page.
*/
public function get_home(){
$bannerimages = DB::table('banner_images')
->orderBy('created_at','desc')->get();
$aboutus = DB::table('pages')
->where('page_title', '=', 'About Us')
->where('page_isPublished', '=', '1')
->where('page_isDeleted', '=', '0')->get();
$this->layout->content = View::make('home.home')
->with('banner_images', $bannerimages)
->with('aboutus', $aboutus);
}
}<file_sep>/app/database/migrations/2014_02_04_175632_create_property_statuses_table.php
<?php
use Illuminate\Database\Migrations\Migration;
class CreatePropertyStatusesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('property_statuses', function($table){
$table->increments('property_status_id');
$table->string('property_status_name');
$table->longText('property_status_description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('property_statuses');
}
}<file_sep>/app/controllers/FrontEndPropertiesController.php
<?php
//Official Website Property Controller Class
class FrontEndPropertiesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Show the official website's property details page.
*/
public function get_view($property_id){
$property = Property::find($property_id);
if ($property != null) {
$property_typeId = Property::find($property_id)->property_typeId;
$property_typeName = Property_Type::find($property_typeId)->property_type_name;
$property_statusId = Property::find($property_id)->property_statusId;
$property_statusName = Property_Status::find($property_statusId)->property_status_name;
$property_locationId = Property::find($property_id)->property_locationId;
$property_locationName = Location::find($property_locationId)->location_name;
$property_vendorId = Property::find($property_id)->property_vendorId;
$property_vendorName = Customer::find($property_vendorId)->customer_firstName.' '.
Customer::find($property_vendorId)->customer_lastName;
$property_isActive = Property::find($property_id)->property_isActive;
$property_active = 'No';
if($property_isActive==1)
$property_active = 'Yes';
$property_isDeleted = Property::find($property_id)->property_isDeleted;
$property_deleted = 'No';
if($property_isDeleted==1)
$property_deleted = 'Yes';
$property_hasGarage = Property::find($property_id)->property_hasGarage;
$property_garage = 'No';
if($property_hasGarage==1)
$property_garage = 'Yes';
$property_hasGarden = Property::find($property_id)->property_hasGarden;
$property_garden = 'No';
if($property_hasGarden==1)
$property_garden = 'Yes';
$primaryimages = DB::table('images')->where('image_propertyId', $property_id)
->where('image_isPrimary', '1')->paginate(1);
$otherimages = DB::table('images')->where('image_propertyId', $property_id)
->where('image_isPrimary', '0')->paginate(100);
$propertylocation = Property::find($property_id)->property_location;
if(Auth::check()){
$offer_available = null;
$offer_isAvailable = false;
$offer_made = false;
$offer_isRejected = false;
$offer_rejected = null;
$offer_isAccepted = false;
$offer_accepted = null;
$offer_isVendorAccepted = false;
$offer_vendorAccepted = null;
$property_isSold = false;
$property_sold = null;
$property_isVendorSold = false;
$property_vendorSold = null;
$offer_exists = null;
$offer_list = null;
$buyer_list = null;
$acceptedoffer = null;
$customer_interested = null;
$isInterested = false;
$offer_available = Offer::where('offer_isDeleted', '0')
->where('offer_propertyId', $property_id)
->where('offer_buyerId', Auth::user()->getCustomerId())
->whereIn('offer_statusId', array(Offer::getAwaitingApprovalId(),
Offer::getAcceptedId(), Offer::getRejectedId()))
->get();
$offer_exists = Offer::where('offer_isDeleted', '0')
->where('offer_propertyId', $property_id)
->where('offer_buyerId', Auth::user()->getCustomerId())
->where('offer_statusId', Offer::getAwaitingApprovalId())
->get()->lists('offer_id');
$offer_rejected = Offer::where('offer_isDeleted', '0')
->where('offer_propertyId', $property_id)
->where('offer_buyerId', Auth::user()->getCustomerId())
->where('offer_statusId', Offer::getRejectedId())
->get()->lists('offer_id');
$offer_accepted = Offer::where('offer_isDeleted', '0')
->where('offer_propertyId', $property_id)
->where('offer_buyerId', Auth::user()->getCustomerId())
->where('offer_statusId', Offer::getAcceptedId())
->get()->lists('offer_id');
$offer_vendorAccepted = Offer::where('offer_isDeleted', '0')
->where('offer_propertyId', $property_id)
->where('offer_statusId', Offer::getAcceptedId())
->get()->lists('offer_id');
$offer_vendorAcceptedOffer = Offer::where('offer_isDeleted', '0')
->where('offer_propertyId', $property_id)
->where('offer_statusId', Offer::getAcceptedId())
->get();
$property_sold = Property::where('property_isDeleted', '0')
->where('property_id', $property_id)
->where('property_statusId', Offer::getConfirmedId())
->get()->lists('property_id');
$property_vendorSold = Offer::where('offer_isDeleted', '0')
->where('offer_propertyId', $property_id)
->where('offer_statusId', Offer::getConfirmedId())
->get();
$customer_interested = Interest::where('interest_customerId', Auth::user()->getCustomerId())
->where('interest_propertyId', $property_id)
->get()->lists('interest_id');
if($customer_interested != null)
$isInterested = true;
if($offer_available != null)
$offer_isAvailable = true;
if($offer_exists != null)
$offer_made = true;
if($offer_rejected != null)
$offer_isRejected = true;
if($offer_accepted != null)
$offer_isAccepted = true;
if($property_sold != null)
$property_isSold = true;
if($property_vendorSold != null)
$property_isVendorSold = true;
if($offer_vendorAccepted != null)
$offer_isVendorAccepted = true;
if(!$offer_isVendorAccepted){
$offer_list = DB::table('offers')
->where('offer_isDeleted', '!=', '1')
->where('offer_statusId', Offer::getAwaitingApprovalId())
->where('offer_propertyId', $property_id)
->orderBy('created_at')->paginate(20);
}
else{
$offer_list = $offer_vendorAcceptedOffer;
}
$buyer_list = DB::table('customers')
->where('customer_isDeleted', '!=', '1')
->where('customer_type', 'Buyer')
->orderBy('created_at')->get();
if($property->property_isActive == '1')
$this->layout->content = View::make('frontend.properties.view')
->with('property', $property)
->with('offers', $offer_list)
->with('buyers', $buyer_list)
->with('primaryimages', $primaryimages)
->with('propertyimages', $otherimages)
->with('property_type', $property_typeName)
->with('property_status', $property_statusName)
->with('property_vendor', $property_vendorName)
->with('property_vendorId', $property_vendorId)
->with('property_location', $property_locationName)
->with('property_hasGarage', $property_garage)
->with('property_hasGarden', $property_garden)
->with('property_offerMade', $offer_made)
->with('property_offer', $offer_exists)
->with('property_mainoffer', $offer_available)
->with('property_offerAvailable', $offer_isAvailable)
->with('property_offerRejected', $offer_isRejected)
->with('property_offerAccepted', $offer_isAccepted)
->with('property_offerVendorAccepted', $offer_isVendorAccepted)
->with('property_offersold', $property_sold)
->with('property_sold', $property_isSold)
->with('property_vendorSold', $property_isVendorSold)
->with('property_vendorOffer', $property_vendorSold)
->with('property_interested', $isInterested)
->with('property_active', $property_active)
->with('property_deleted', $property_deleted);
else
return Redirect::route('webproperties')
->with('error-message', 'Requested Property was not found');
}
else{
if($property->property_isActive == '1')
$this->layout->content = View::make('frontend.properties.view')
->with('property', $property)
->with('primaryimages', $primaryimages)
->with('propertyimages', $otherimages)
->with('property_type', $property_typeName)
->with('property_status', $property_statusName)
->with('property_vendor', $property_vendorName)
->with('property_location', $property_locationName)
->with('property_hasGarage', $property_garage)
->with('property_hasGarden', $property_garden)
->with('property_active', $property_active)
->with('property_deleted', $property_deleted);
}
}
else {
return Redirect::route('webproperties')
->with('error-message', 'Requested Property was not found');
}
}
/**
* Show the official website's property index page.
*/
public function get_index(){
$allproperties = DB::table('properties')
->where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->where('property_statusId', Property::getForSaleId())
->orderBy('created_at','desc')->paginate(12);
$alllocations = DB::table('locations')->orderBy('location_name')->get();
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
$allimages = DB::table('images')->orderBy('image_propertyId')->get();
$property_type = array('' => 'Select One') +
Property_Type::lists('property_type_name', 'property_type_id');
$property_location = array('' => 'Select One') +
Location::lists('location_name', 'location_id');
$this->layout->content = View::make('frontend.properties.index')
->with('title', 'List of Properties')
->with('property_typeId',$property_type)
->with('property_locationId',$property_location)
->with('properties', $allproperties)
->with('propertylocations', $alllocations)
->with('propertystatuses', $allpropertystatuses)
->with('propertytypes', $allpropertytypes)
->with('propertyimages', $allimages);
}
/**
* Show the official website's filtered property index page.
*/
public function get_filteredindex(){
$query = DB::table('properties')->where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->where('property_statusId', Property::getForSaleId());
$property_statusId = Input::get('property_statusId');
$property_typeId = Input::get('property_typeId');
$property_locationId = Input::get('property_locationId');
if($property_statusId!="")
$query->where('property_statusId', $property_statusId);
if($property_typeId != "")
$query->where('property_typeId', $property_typeId);
if($property_locationId != "")
$query->where('property_locationId', $property_locationId);
$filteredproperties = $query->paginate(12);
$alllocations = DB::table('locations')->orderBy('location_name')->get();
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
$allimages = DB::table('images')->orderBy('image_propertyId')->get();
$property_type = array('' => 'Select One') +
Property_Type::lists('property_type_name', 'property_type_id');
$property_status = array('' => 'Select One') +
Property_Status::lists('property_status_name', 'property_status_id');
$property_location = array('' => 'Select One') +
Location::lists('location_name', 'location_id');
$this->layout->content = View::make('frontend.properties.index', compact('property_typeId'))
->with('title', 'List of Properties')
->with('property_typeId',$property_type)
->with('property_statusId',$property_status)
->with('property_locationId',$property_location)
->with('properties', $filteredproperties)
->with('propertylocations', $alllocations)
->with('propertystatuses', $allpropertystatuses)
->with('propertytypes', $allpropertytypes)
->with('propertyimages', $allimages);
}
/**
* Show the official website's 'My Properties' index page.
*/
public function get_myindex(){
if(Auth::check()){
$customer = Customer::find(Auth::user()->getCustomerId());
if($customer->customer_type == 'Vendor') {
$allproperties = DB::table('properties')
->where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->where('property_vendorId', $customer->customer_id)
->orderBy('created_at','desc')->paginate(12);
}
else {
$alloffers = DB::table('offers')
->where('offer_isDeleted', '!=', '1')
->where('offer_buyerId', $customer->customer_id)
->orderBy('created_at')->get();
$offerpropertyIds = array();
if($alloffers !=null){
foreach ($alloffers as $offer) {
$offerpropertyIds[] = $offer->offer_propertyId;
}
}
$allinterests = DB::table('interests')
->where('interest_customerId', $customer->customer_id)
->orderBy('created_at')->get();
$interestpropertyIds = array();
if($allinterests!=null){
foreach ($allinterests as $interest) {
$interestpropertyIds[] = $interest->interest_propertyId;
}
}
$combinedpropertyIds = array_unique(array_merge($offerpropertyIds, $interestpropertyIds));
if($combinedpropertyIds!=null)
$allproperties = DB::table('properties')
->where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->whereIn('property_id', $combinedpropertyIds)
->orderBy('created_at','desc')->paginate(12);
else
$allproperties = null;
}
$alllocations = DB::table('locations')->orderBy('location_name')->get();
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
$allimages = DB::table('images')->orderBy('image_propertyId')->get();
$this->layout->content = View::make('frontend.myproperties.index')
->with('title', 'List of My Properties')
->with('properties', $allproperties)
->with('propertylocations', $alllocations)
->with('propertystatuses', $allpropertystatuses)
->with('propertytypes', $allpropertytypes)
->with('propertyimages', $allimages);
}
}
}<file_sep>/app/models/Offer_Status.php
<?php
/* Offer Status Model Class */
class Offer_Status extends Eloquent {
//Database table
protected $table = 'offer_statuses';
//Primary key of the offer_statuses table
protected $primaryKey = 'offer_status_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('offer_status_id','offer_status_name', 'offer_status_description');
/**
* Get the offer status id.
*
* @return int
*/
public function getOfferStatusId()
{
return $this->offer_status_id;
}
/**
* Validate offer status creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_offer_status_rules = array(
'offer_status_name'=>'Required|Min:2|Unique:offer_statuses,offer_status_name',
'offer_status_description'=>'Required|Min:20'
);
$create_offer_status_messages = array(
'offer_status_name.unique' => 'Provided Offer Status is already in use'
);
return Validator::make(Input::all(), $create_offer_status_rules, $create_offer_status_messages);
}
/**
* Validate offer status modification method.
*
* @return object Validator
*/
public static function validate_edit($offer_status_id)
{
$edit_offer_status_rules = array(
'offer_status_name'=>'Required|Min:2|Unique:offer_statuses,offer_status_name,'.$offer_status_id.',offer_status_id',
'offer_status_description'=>'Required|Min:20'
);
$edit_offer_status_messages = array(
'offer_status_name.unique' => 'Provided Offer Status is already in use'
);
return Validator::make(Input::all(), $edit_offer_status_rules, $edit_offer_status_messages);
}
}<file_sep>/app/database/migrations/2014_02_04_181620_add_property_statuses.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddPropertyStatuses extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('property_statuses')->insert(array(
'property_status_name'=>'For Sale',
'property_status_description'=>'This property is currently for sale',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_statuses')->insert(array(
'property_status_name'=>'Sold Subject to Contract',
'property_status_description'=>'This property has been sold subject to contract',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_statuses')->insert(array(
'property_status_name'=>'Sold',
'property_status_description'=>'This property has been sold',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('property_statuses')->delete();
}
}<file_sep>/app/controllers/PropertyTypesController.php
<?php
//IMS Property Type Controller Class
class PropertyTypesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS's property type index page.
*/
public function get_index(){
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->paginate(10);
$this->layout->content = View::make('property_types.index')
->with('title', 'List of Property Types')
->with('property_types', $allpropertytypes);
}
/**
* Show the IMS's property type details page.
*/
public function get_view($property_type_id){
if (Property_Type::find($property_type_id) != null) {
$property_typeId = Property_Type::find($property_type_id);
$this->layout->content = View::make('property_types.view')
->with('title', 'Property Type View Page')
->with('property_type', Property_Type::find($property_type_id));
}
else
return Redirect::route('property_types')
->with('error-message', 'Requested Property Type was not found');
}
/**
* Show the IMS's property type creation page.
*/
public function get_new(){
$property_type = array('' => 'Select One') +
Property_Type::lists('property_type_name', 'property_type_id');
$this->layout->content = View::make('property_types.new')
->with('title', 'Add New Property Type')
->with('property_typeId',$property_type);
}
/**
* Validate and create the property type.
*/
public function post_create(){
$validation = Property_Type::validate_create();
if($validation->fails()) {
return Redirect::route('new_property_type')
->withErrors($validation)
->withInput();
}
else {
Property_Type::create(array(
'property_type_name'=>Input::get('property_type_name'),
'property_type_description'=>Input::get('property_type_description')
));
return Redirect::route('property_types')
->with('message', 'The property type was created successfully!');
}
}
/**
* Show the IMS's property type modification page.
*/
public function get_edit($property_type_id){
if(Property_Type::find($property_type_id)!=null){
$this->layout->content = View::make('property_types.edit')
->with('title', 'Edit Property Type')
->with('property_type', Property_Type::find($property_type_id));
}
else
return Redirect::route('property_types')
->with('error-message', 'Requested Property Type was not found');
}
/**
* Validate and edit the property type.
*/
public function put_update(){
$property_type_id = Input::get('property_type_id');
$validation = Property_Type::validate_edit($property_type_id);
if($validation->fails()) {
return Redirect::route('edit_property_type', $property_type_id)
->withErrors($validation);
}
else {
Property_Type::find($property_type_id)->update(array(
'property_type_name'=>Input::get('property_type_name'),
'property_type_description'=>Input::get('property_type_description')
));
return Redirect::route('property_type', $property_type_id)
->with('message', 'The property type was updated successfully!');
}
}
/**
* Show the IMS's property type deletion page.
*/
public function get_destroy($property_typeId){
$this->layout->content = View::make('property_types.confirm-delete')
->with('title', 'Confirm Property Type Deletion')
->with('property_type', Property_Type::find($property_typeId));
}
/**
* Delete the property type.
*/
public function delete_destroy(){
Property_Type::find(Input::get('property_type_id'))->delete();
return Redirect::route('property_types')
->with('message', 'The property type was deleted successfully!');
}
}<file_sep>/app/controllers/OfferStatusesController.php
<?php
//IMS Offer Status Controller Class
class OfferStatusesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS's offer status index page.
*/
public function get_index(){
$allofferstatuses = DB::table('offer_statuses')->orderBy('offer_status_name')->paginate(10);
$this->layout->content = View::make('offer_statuses.index')
->with('title', 'List of Offer Statuses')
->with('offer_statuses', $allofferstatuses);
}
/**
* Show the IMS's offer status details page.
*/
public function get_view($offer_status_id){
if (Offer_Status::find($offer_status_id) != null) {
$offer_statusId = Offer_Status::find($offer_status_id);
$this->layout->content = View::make('offer_statuses.view')
->with('title', 'Offer Status View Page')
->with('offer_status', Offer_Status::find($offer_status_id));
}
else
return Redirect::route('offer_statuses')
->with('error-message', 'Requested Offer Status was not found');
}
/**
* Show the IMS's offer status creation page.
*/
public function get_new(){
$offer_status = array('' => 'Select One') +
Offer_Status::lists('offer_status_name', 'offer_status_id');
$this->layout->content = View::make('offer_statuses.new')
->with('title', 'Add New Offer Status')
->with('offer_statusId',$offer_status);
}
/**
* Validate and create the offer status.
*/
public function post_create(){
$validation = Offer_Status::validate_create();
if($validation->fails()) {
return Redirect::route('new_offer_status')
->withErrors($validation)
->withInput();
}
else {
Offer_Status::create(array(
'offer_status_name'=>Input::get('offer_status_name'),
'offer_status_description'=>Input::get('offer_status_description')
));
return Redirect::route('offer_statuses')
->with('message', 'The offer status was created successfully!');
}
}
/**
* Show the IMS's offer status modification page.
*/
public function get_edit($offer_status_id){
if(Offer_Status::find($offer_status_id) != null){
$this->layout->content = View::make('offer_statuses.edit')
->with('title', 'Edit Offer Status')
->with('offer_status', Offer_Status::find($offer_status_id));
}
else
return Redirect::route('offer_statuses')
->with('error-message', 'Requested Offer Status was not found');
}
/**
* Validate and edit the offer status.
*/
public function put_update(){
$offer_status_id = Input::get('offer_status_id');
$validation = Offer_Status::validate_edit($offer_status_id);
if($validation->fails()) {
return Redirect::route('edit_offer_status', $offer_status_id)
->withErrors($validation);
}
else {
Offer_Status::find($offer_status_id)->update(array(
'offer_status_name'=>Input::get('offer_status_name'),
'offer_status_description'=>Input::get('offer_status_description')
));
return Redirect::route('offer_status', $offer_status_id)
->with('message', 'The offer status was updated successfully!');
}
}
/**
* Show the IMS's offer status deletion page.
*/
public function get_destroy($offer_statusId){
$this->layout->content = View::make('offer_statuses.confirm-delete')
->with('title', 'Confirm Offer Status Deletion')
->with('offer_status', Offer_Status::find($offer_statusId));
}
/**
* Delete the offer status.
*/
public function delete_destroy(){
Offer_Status::find(Input::get('offer_status_id'))->delete();
return Redirect::route('offer_statuses')
->with('message', 'The offer status was deleted successfully!');
}
}<file_sep>/app/controllers/FrontEndOffersController.php
<?php
//Official Website Offer Controller Class
class FrontEndOffersController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Buyer: Show the official website's offer creation page.
*/
public function get_new($propertyId){
$property = Property::find($propertyId);
if(Auth::check() && Auth::user()->getType() == 'Buyer' && $property->property_statusId == Property::getForSaleId()){
$offer_properties = Property::where('property_isDeleted', '0')
->where('property_id', $propertyId)
->get()->lists('property_name', 'property_id');
$offer_buyers = Customer::where('customer_type', 'Buyer')
->where('customer_isDeleted', '0')
->where('customer_id', Auth::user()->getCustomerId())
->get()->lists('fe_full_name', 'customer_id');
$offer_statuses = Offer_Status::where('offer_status_name', 'Awaiting Approval')
->lists('offer_status_name', 'offer_status_id');
$offer_price = Property::find($propertyId)->property_price;
$this->layout->content = View::make('frontend.offers.new')
->with('title', 'Add New Offer')
->with('offer_propertyId',$propertyId)
->with('offer_property',$offer_properties)
->with('offer_buyer', $offer_buyers)
->with('offer_price', $offer_price)
->with('offer_status', $offer_statuses);
}
else{
return Redirect::route('webproperties')
->with('error-message', 'You cannot make a new offer for the chosen property!');
}
}
/**
* Buyer: Validate, create the offer and send the required emails.
*/
public function post_create(){
$validation = Offer::validate_create();
if($validation->fails()) {
return Redirect::back()
->withErrors($validation)
->withInput();
}
else {
if(Input::get('offer_value') >= Input::get('offer_price')){
Offer::create(array(
'offer_value'=>Input::get('offer_value'),
'offer_propertyId'=>Input::get('offer_propertyId'),
'offer_buyerId'=>Input::get('offer_buyerId'),
'offer_statusId'=>Input::get('offer_statusId'),
'offer_isDeleted'=>'0'
));
$other_offers = DB::table('offers')
->where('offer_propertyId', Input::get('offer_propertyId'))
->where('offer_isDeleted', '0')
->where('offer_buyerId', Input::get('offer_buyerId'))
->where('offer_statusId', Offer::getRejectedId())->get();
if($other_offers!=null)
{
foreach ($other_offers as $other_offer) {
$otherofferId = $other_offer->offer_id;
Offer::find($otherofferId)->update(array(
'offer_statusId'=> Offer::getCancelledId(),
'offer_isDeleted'=>'1'
));
}
}
$property_name = Property::find(Input::get('offer_propertyId'))->property_name;
$property_status = Property::find(Input::get('offer_propertyId'))->property_statusId;
$property_status_name = Property_Status::find($property_status)->property_status_name;
$vendor_id = Property::find(Input::get('offer_propertyId'))->property_vendorId;
$property_vendor = Customer::find($vendor_id)->getName();
$vendor_firstName = Customer::find($vendor_id)->customer_firstName;
$vendor_lastName = Customer::find($vendor_id)->customer_lastName;
$vendor_emailAddress = Customer::find($vendor_id)->customer_emailAddress;
$offer_value = Input::get('offer_value');
$offer_status = Offer_Status::find(Input::get('offer_statusId'))->offer_status_name;
$property_buyer = Customer::find(Input::get('offer_buyerId'))->getName();
$buyer_firstName = Customer::find(Input::get('offer_buyerId'))->customer_firstName;
$buyer_lastName = Customer::find(Input::get('offer_buyerId'))->customer_lastName;
$buyer_emailAddress = Customer::find(Input::get('offer_buyerId'))->customer_emailAddress;
$buyeremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_vendor'=>$property_vendor,
'offer_value'=>$offer_value,
'offer_status'=>$offer_status,
'buyer_firstName'=>$buyer_firstName,
'buyer_lastName'=>$buyer_lastName,
'buyer_emailAddress'=>$buyer_emailAddress
);
Mail::send('frontend.offers.mails.buyer_new_offer', $buyeremaildata, function($message) use (
$property_status_name, $property_name, $property_vendor, $offer_value, $offer_status,
$buyer_firstName, $buyer_lastName, $buyer_emailAddress){
$message->to($buyer_emailAddress, $buyer_firstName.' '.$buyer_lastName)
->subject('New Offer for Property '.$property_name);
});
$vendoremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_buyer'=>$property_buyer,
'offer_value'=>$offer_value,
'offer_status'=>$offer_status,
'vendor_firstName'=>$vendor_firstName,
'vendor_lastName'=>$vendor_lastName,
'vendor_emailAddress'=>$vendor_emailAddress
);
Mail::send('frontend.offers.mails.vendor_new_offer', $vendoremaildata, function($message) use (
$property_status_name, $property_name, $property_buyer, $offer_value, $offer_status,
$vendor_firstName,$vendor_lastName, $vendor_emailAddress){
$message->to($vendor_emailAddress, $vendor_firstName.' '.$vendor_lastName)
->subject('New Offer for Property '.$property_name);
});
return Redirect::route('webproperty', Input::get('offer_propertyId'))
->with('message', 'The offer was created successfully. The vendor will be notified accordingly.');
}
else
return Redirect::back()
->with('error-message', 'The offer value must be greater or equal to the original price!');
}
}
/**
* Buyer: Show the official website's offer modification page.
*/
public function get_edit($offer_id){
$offer = Offer::find($offer_id);
if($offer != null){
$offer_isDeleted = Offer::find($offer_id)->offer_isDeleted;
$offer_propertyId = Offer::find($offer_id)->offer_propertyId;
$offer_price = Property::find($offer_propertyId)->property_price;
$offer_buyerId = Offer::find($offer_id)->offer_buyerId;
$offer_statusId = Offer::find($offer_id)->offer_statusId;
$offer_properties = Property::where('property_isDeleted', '0')
->where('property_id', $offer_propertyId)
->get()->lists('property_name', 'property_id');
$offer_buyers = Customer::where('customer_type', 'Buyer')
->where('customer_isDeleted', '0')
->where('customer_id', $offer_buyerId)
->get()->lists('fe_full_name', 'customer_id');
$offer_statuses = Offer_Status::where('offer_status_name', 'Awaiting Approval')
->lists('offer_status_name', 'offer_status_id');
if(Auth::check() && Auth::user()->getType() == 'Buyer' &&
!$offer_isDeleted && $offer_buyerId == Auth::user()->getCustomerId() &&
$offer_statusId == Offer::getAwaitingApprovalId()){
$this->layout->content = View::make('frontend.offers.edit')
->with('title', 'Edit Offer')
->with('offer_price', $offer_price)
->with('offer', Offer::find($offer_id))
->with('offer_buyer', $offer_buyers)
->with('offer_property',$offer_properties)
->with('offer_price', $offer_price)
->with('offer_status', $offer_statuses);
}
else
{
return Redirect::route('webproperties')
->with('error-message', 'You cannot edit the requested offer!');
}
}
else
{
return Redirect::route('webproperties')
->with('error-message', 'You cannot edit the requested offer!');
}
}
/**
* Buyer: Validate, edit the offer and send the required emails.
*/
public function put_update(){
$offer_id = Input::get('offer_id');
$validation = Offer::validate_edit();
if($validation->fails()) {
return Redirect::back()
->withErrors($validation)
->withInput();
}
else {
if(Input::get('offer_value') >= Input::get('offer_price')){
Offer::find($offer_id)->update(array(
'offer_value'=>Input::get('offer_value'),
'offer_propertyId'=>Input::get('offer_propertyId'),
'offer_buyerId'=>Input::get('offer_buyerId'),
'offer_statusId'=>Input::get('offer_statusId'),
'offer_isDeleted'=>'0'
));
$property_name = Property::find(Input::get('offer_propertyId'))->property_name;
$property_status = Property::find(Input::get('offer_propertyId'))->property_statusId;
$property_status_name = Property_Status::find($property_status)->property_status_name;
$vendor_id = Property::find(Input::get('offer_propertyId'))->property_vendorId;
$property_vendor = Customer::find($vendor_id)->getName();
$vendor_firstName = Customer::find($vendor_id)->customer_firstName;
$vendor_lastName = Customer::find($vendor_id)->customer_lastName;
$vendor_emailAddress = Customer::find($vendor_id)->customer_emailAddress;
$offer_value = Input::get('offer_value');
$offer_status = Offer_Status::find(Input::get('offer_statusId'))->offer_status_name;
$property_buyer = Customer::find(Input::get('offer_buyerId'))->getName();
$buyer_firstName = Customer::find(Input::get('offer_buyerId'))->customer_firstName;
$buyer_lastName = Customer::find(Input::get('offer_buyerId'))->customer_lastName;
$buyer_emailAddress = Customer::find(Input::get('offer_buyerId'))->customer_emailAddress;
$buyeremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_vendor'=>$property_vendor,
'offer_value'=>$offer_value,
'offer_status'=>$offer_status,
'buyer_firstName'=>$buyer_firstName,
'buyer_lastName'=>$buyer_lastName,
'buyer_emailAddress'=>$buyer_emailAddress
);
Mail::send('frontend.offers.mails.buyer_updated_offer', $buyeremaildata, function($message) use (
$property_status_name, $property_name, $property_vendor, $offer_value, $offer_status,
$buyer_firstName, $buyer_lastName, $buyer_emailAddress){
$message->to($buyer_emailAddress, $buyer_firstName.' '.$buyer_lastName)
->subject('Updated Offer for Property '.$property_name);
});
$vendoremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_buyer'=>$property_buyer,
'offer_value'=>$offer_value,
'offer_status'=>$offer_status,
'vendor_firstName'=>$vendor_firstName,
'vendor_lastName'=>$vendor_lastName,
'vendor_emailAddress'=>$vendor_emailAddress
);
Mail::send('frontend.offers.mails.vendor_updated_offer', $vendoremaildata, function($message) use (
$property_status_name, $property_name, $property_buyer, $offer_value, $offer_status,
$vendor_firstName, $vendor_lastName, $vendor_emailAddress){
$message->to($vendor_emailAddress, $vendor_firstName.' '.$vendor_lastName)
->subject('Updated Offer for Property '.$property_name);
});
return Redirect::route('webproperty', Input::get('offer_propertyId'))
->with('message', 'The offer was updated successfully!');
}
else
return Redirect::back()
->with('error-message', 'The offer value must be greater or equal to the original price!');
}
}
/**
* Vendor: Reject the offer and send the required emails.
*/
public function put_reject(){
$offer = Offer::find(Input::get('offer_id'));
$offer_propertyId = $offer->offer_propertyId;
$offer->update(array(
'offer_statusId'=>Offer::getRejectedId()
));
$updatedoffer = Offer::find(Input::get('offer_id'));
$property_name = Property::find($offer_propertyId)->property_name;
$property_status = Property::find($offer_propertyId)->property_statusId;
$property_status_name = Property_Status::find($property_status)->property_status_name;
$vendor_id = Property::find($offer_propertyId)->property_vendorId;
$property_vendor = Customer::find($vendor_id)->getName();
$vendor_firstName = Customer::find($vendor_id)->customer_firstName;
$vendor_lastName = Customer::find($vendor_id)->customer_lastName;
$vendor_emailAddress = Customer::find($vendor_id)->customer_emailAddress;
$offer_value = $updatedoffer->offer_value;
$offer_status = $updatedoffer->offer_statusId;
$offer_status_name = Offer_Status::find($offer_status)->offer_status_name;
$property_buyer = $updatedoffer->offer_buyerId;
$property_buyer_name = Customer::find($property_buyer)->getName();
$buyer_firstName = Customer::find($property_buyer)->customer_firstName;
$buyer_lastName = Customer::find($property_buyer)->customer_lastName;
$buyer_emailAddress = Customer::find($property_buyer)->customer_emailAddress;
$buyeremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_vendor'=>$property_vendor,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'buyer_firstName'=>$buyer_firstName,
'buyer_lastName'=>$buyer_lastName,
'buyer_emailAddress'=>$buyer_emailAddress
);
Mail::send('frontend.offers.mails.buyer_reject_offer', $buyeremaildata, function($message) use (
$property_status_name, $property_name, $property_vendor, $offer_value, $offer_status_name,
$buyer_firstName, $buyer_lastName, $buyer_emailAddress){
$message->to($buyer_emailAddress, $buyer_firstName.' '.$buyer_lastName)
->subject('Rejected Offer for Property '.$property_name);
});
$vendoremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_buyer_name'=>$property_buyer_name,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'vendor_firstName'=>$vendor_firstName,
'vendor_lastName'=>$vendor_lastName,
'vendor_emailAddress'=>$vendor_emailAddress
);
Mail::send('frontend.offers.mails.vendor_reject_offer', $vendoremaildata, function($message) use (
$property_status_name, $property_name, $property_buyer_name, $offer_value, $offer_status_name,
$vendor_firstName,$vendor_lastName, $vendor_emailAddress){
$message->to($vendor_emailAddress, $vendor_firstName.' '.$vendor_lastName)
->subject('Rejected Offer for Property '.$property_name);
});
return Redirect::route('webproperty', $offer_propertyId)
->with('message', 'The offer was successfully rejected. The buyer will be notified accordingly.');
}
/**
* Vendor: Confirm the offer and send the required emails.
*/
public function put_confirm(){
$offer = Offer::find(Input::get('offer_id'));
$offer_propertyId = $offer->offer_propertyId;
$offer->update(array(
'offer_statusId'=>Offer::getConfirmedId()
));
$property = DB::table('properties')
->where('property_id', $offer_propertyId)
->where('property_isDeleted', '0')->get();
if($property!=null)
{
Property::find($offer_propertyId)->update(array(
'property_statusId'=>Property::getSoldId(),
'property_price'=>$offer->offer_value
));
}
$updatedoffer = Offer::find(Input::get('offer_id'));
$property_name = Property::find($offer_propertyId)->property_name;
$property_status = Property::find($offer_propertyId)->property_statusId;
$property_status_name = Property_Status::find($property_status)->property_status_name;
$vendor_id = Property::find($offer_propertyId)->property_vendorId;
$property_vendor = Customer::find($vendor_id)->getName();
$vendor_firstName = Customer::find($vendor_id)->customer_firstName;
$vendor_lastName = Customer::find($vendor_id)->customer_lastName;
$vendor_emailAddress = Customer::find($vendor_id)->customer_emailAddress;
$offer_value = $updatedoffer->offer_value;
$offer_status = $updatedoffer->offer_statusId;
$offer_status_name = Offer_Status::find($offer_status)->offer_status_name;
$property_buyer = $updatedoffer->offer_buyerId;
$property_buyer_name = Customer::find($property_buyer)->getName();
$buyer_firstName = Customer::find($property_buyer)->customer_firstName;
$buyer_lastName = Customer::find($property_buyer)->customer_lastName;
$buyer_emailAddress = Customer::find($property_buyer)->customer_emailAddress;
$buyeremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_vendor'=>$property_vendor,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'buyer_firstName'=>$buyer_firstName,
'buyer_lastName'=>$buyer_lastName,
'buyer_emailAddress'=>$buyer_emailAddress
);
Mail::send('frontend.offers.mails.buyer_confirm_offer', $buyeremaildata, function($message) use (
$property_status_name, $property_name, $property_vendor, $offer_value, $offer_status_name,
$buyer_firstName, $buyer_lastName, $buyer_emailAddress){
$message->to($buyer_emailAddress, $buyer_firstName.' '.$buyer_lastName)
->subject('Confirmed Sale of Property '.$property_name);
});
$vendoremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_buyer_name'=>$property_buyer_name,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'vendor_firstName'=>$vendor_firstName,
'vendor_lastName'=>$vendor_lastName,
'vendor_emailAddress'=>$vendor_emailAddress
);
Mail::send('frontend.offers.mails.vendor_confirm_offer', $vendoremaildata, function($message) use (
$property_status_name, $property_name, $property_buyer_name, $offer_value, $offer_status_name,
$vendor_firstName,$vendor_lastName, $vendor_emailAddress){
$message->to($vendor_emailAddress, $vendor_firstName.' '.$vendor_lastName)
->subject('Confirmed Sale of Property '.$property_name);
});
return Redirect::route('webproperty', $offer_propertyId)
->with('message', 'The sale was successfully confirmed. The buyer will be notified accordingly.');
}
/**
* Vendor: Accept the offer and send the required emails.
*/
public function put_accept(){
$offer = Offer::find(Input::get('offer_id'));
$offerId = $offer->offer_id;
$offer_propertyId = $offer->offer_propertyId;
$offer->update(array(
'offer_statusId'=>Offer::getAcceptedId()
));
$property = DB::table('properties')
->where('property_id', $offer_propertyId)
->where('property_isDeleted', '0')->get();
if($property!=null)
{
Property::find($offer_propertyId)->update(array(
'property_statusId'=>Property::getSoldSTCId()
));
}
$otheroffers = DB::table('offers')
->where('offer_id', '!=', $offerId)
->where('offer_propertyId', $offer_propertyId)
->where('offer_isDeleted', '0')->get();
if($otheroffers!=null)
{
foreach ($otheroffers as $otheroffer) {
$otherofferId = $otheroffer->offer_id;
Offer::find($otherofferId)->update(array(
'offer_statusId'=>Offer::getCancelledId(),
'offer_isDeleted'=>'1'
));
}
}
$propertyinterests = DB::table('interests')
->where('interest_propertyId', $offer_propertyId)->get();
if($propertyinterests!=null)
{
foreach ($propertyinterests as $interest) {
$interestId = $interest->interest_id;
Interest::find($interestId)->delete();
}
}
$updatedoffer = Offer::find(Input::get('offer_id'));
$property_name = Property::find($offer_propertyId)->property_name;
$property_status = Property::find($offer_propertyId)->property_statusId;
$property_status_name = Property_Status::find($property_status)->property_status_name;
$vendor_id = Property::find($offer_propertyId)->property_vendorId;
$property_vendor = Customer::find($vendor_id)->getName();
$vendor_firstName = Customer::find($vendor_id)->customer_firstName;
$vendor_lastName = Customer::find($vendor_id)->customer_lastName;
$vendor_emailAddress = Customer::find($vendor_id)->customer_emailAddress;
$offer_value = $updatedoffer->offer_value;
$offer_status = $updatedoffer->offer_statusId;
$offer_status_name = Offer_Status::find($offer_status)->offer_status_name;
$property_buyer = $updatedoffer->offer_buyerId;
$property_buyer_name = Customer::find($property_buyer)->getName();
$buyer_firstName = Customer::find($property_buyer)->customer_firstName;
$buyer_lastName = Customer::find($property_buyer)->customer_lastName;
$buyer_emailAddress = Customer::find($property_buyer)->customer_emailAddress;
$buyeremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_vendor'=>$property_vendor,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'buyer_firstName'=>$buyer_firstName,
'buyer_lastName'=>$buyer_lastName,
'buyer_emailAddress'=>$buyer_emailAddress
);
Mail::send('frontend.offers.mails.buyer_accept_offer', $buyeremaildata, function($message) use (
$property_status_name, $property_name, $property_vendor, $offer_value, $offer_status_name,
$buyer_firstName, $buyer_lastName, $buyer_emailAddress){
$message->to($buyer_emailAddress, $buyer_firstName.' '.$buyer_lastName)
->subject('Accepted Offer for Property '.$property_name);
});
$vendoremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_buyer_name'=>$property_buyer_name,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'vendor_firstName'=>$vendor_firstName,
'vendor_lastName'=>$vendor_lastName,
'vendor_emailAddress'=>$vendor_emailAddress
);
Mail::send('frontend.offers.mails.vendor_accept_offer', $vendoremaildata, function($message) use (
$property_status_name, $property_name, $property_buyer_name, $offer_value, $offer_status_name,
$vendor_firstName,$vendor_lastName, $vendor_emailAddress){
$message->to($vendor_emailAddress, $vendor_firstName.' '.$vendor_lastName)
->subject('Accepted Offer for Property '.$property_name);
});
return Redirect::route('webproperty', $offer_propertyId)
->with('message', 'The offer was successfully accepted. The buyer will be notified accordingly.');
}
/**
* Buyer: Cancel the offer and send the required emails.
*/
public function delete_destroy(){
$offer = Offer::find(Input::get('offer_id'));
$offer_propertyId = $offer->offer_propertyId;
Offer::find(Input::get('offer_id'))->update(array(
'offer_statusId'=>Offer::getCancelledId(),
'offer_isDeleted'=>'1'
));
$updatedoffer = Offer::find(Input::get('offer_id'));
$property_name = Property::find($offer_propertyId)->property_name;
$property_status = Property::find($offer_propertyId)->property_statusId;
$property_status_name = Property_Status::find($property_status)->property_status_name;
$vendor_id = Property::find($offer_propertyId)->property_vendorId;
$property_vendor = Customer::find($vendor_id)->getName();
$vendor_firstName = Customer::find($vendor_id)->customer_firstName;
$vendor_lastName = Customer::find($vendor_id)->customer_lastName;
$vendor_emailAddress = Customer::find($vendor_id)->customer_emailAddress;
$offer_value = $updatedoffer->offer_value;
$offer_status = $updatedoffer->offer_statusId;
$offer_status_name = Offer_Status::find($offer_status)->offer_status_name;
$property_buyer = $updatedoffer->offer_buyerId;
$property_buyer_name = Customer::find($property_buyer)->getName();
$buyer_firstName = Customer::find($property_buyer)->customer_firstName;
$buyer_lastName = Customer::find($property_buyer)->customer_lastName;
$buyer_emailAddress = Customer::find($property_buyer)->customer_emailAddress;
$buyeremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_vendor'=>$property_vendor,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'buyer_firstName'=>$buyer_firstName,
'buyer_lastName'=>$buyer_lastName,
'buyer_emailAddress'=>$buyer_emailAddress
);
Mail::send('frontend.offers.mails.buyer_cancel_offer', $buyeremaildata, function($message) use (
$property_status_name, $property_name, $property_vendor, $offer_value, $offer_status_name,
$buyer_firstName, $buyer_lastName, $buyer_emailAddress){
$message->to($buyer_emailAddress, $buyer_firstName.' '.$buyer_lastName)
->subject('Cancelled Offer for Property '.$property_name);
});
$vendoremaildata = array(
'property_name'=>$property_name,
'property_status_name'=>$property_status_name,
'property_buyer_name'=>$property_buyer_name,
'offer_value'=>$offer_value,
'offer_status_name'=>$offer_status_name,
'vendor_firstName'=>$vendor_firstName,
'vendor_lastName'=>$vendor_lastName,
'vendor_emailAddress'=>$vendor_emailAddress
);
Mail::send('frontend.offers.mails.vendor_cancel_offer', $vendoremaildata, function($message) use (
$property_status_name, $property_name, $property_buyer_name, $offer_value, $offer_status_name,
$vendor_firstName,$vendor_lastName, $vendor_emailAddress){
$message->to($vendor_emailAddress, $vendor_firstName.' '.$vendor_lastName)
->subject('Cancelled Offer for Property '.$property_name);
});
return Redirect::route('webproperty', $offer_propertyId)
->with('message', 'The offer was cancelled successfully!');
}
}<file_sep>/app/controllers/CmsController.php
<?php
//CMS Controller Class
class CmsController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.cmslayout";
/**
* Show the CMS home page.
*/
public function get_home(){
if(Auth::check())
$this->layout->content = View::make('home.cmshome');
else
return Redirect::route('cmslogin')
->with('error-message', 'Please login!');
}
}<file_sep>/app/models/Property.php
<?php
/* Property Model Class */
class Property extends Eloquent {
//Database table
protected $table = 'properties';
//Primary key of the properties table
protected $primaryKey = 'property_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('property_id','property_typeId', 'property_statusId',
'property_vendorId', 'property_name', 'property_description', 'property_locationId',
'property_squareMetres', 'property_bathrooms', 'property_bedrooms', 'property_hasGarage',
'property_hasGarden', 'property_price', 'property_isActive', 'property_isDeleted');
/**
* Get the id of the property.
*
* @return int
*/
public function getPropertyId()
{
return $this->property_id;
}
/**
* Get the id of the property and the property name.
*
* @return string
*/
public function getFullNameAttribute()
{
return $this->attributes['property_id'].': '.$this->attributes['property_name'];
}
/**
* Get the id of the property status depending on the status name.
*
* @return int
*/
public static function getStatusId($status_name)
{
$property_status = DB::table('property_statuses')
->where('property_status_name', $status_name)
->lists('property_status_id');
if($property_status!=null)
{
foreach ($property_status as $status) {
$propertystatus = Property_Status::find($status);
$propertystatusId = $propertystatus->property_status_id;
return $propertystatusId;
}
}
}
/**
* Get the id of the 'for sale' property status.
*
* @return int
*/
public static function getForSaleId()
{
return self::getStatusId('For Sale');
}
/**
* Get the id of the 'sold subject to contract' property status.
*
* @return int
*/
public static function getSoldSTCId()
{
return self::getStatusId('Sold Subject to Contract');
}
/**
* Get the id of the 'sold' property status.
*
* @return int
*/
public static function getSoldId()
{
return self::getStatusId('Sold');
}
/**
* Validate property name while uploading images method.
*
* @return object Validator
*/
public static function validate_upload()
{
$property_upload_rules = array(
'property_name'=>'Required'
);
return Validator::make(Input::all(), $property_upload_rules);
}
/**
* Validate property creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_property_rules = array(
'property_typeId'=>'Required',
'property_statusId'=>'Required',
'property_vendorId'=>'Required',
'property_name'=>'Required|Min:2',
'property_description'=>'Required|Min:20',
'property_locationId'=>'Required',
'property_squareMetres'=>'Required|Numeric',
'property_bathrooms'=>'Required|Numeric',
'property_bedrooms'=>'Required|Numeric',
'property_price'=>'Required|Numeric'
);
return Validator::make(Input::all(), $create_property_rules);
}
/**
* Validate property modification method.
*
* @return object Validator
*/
public static function validate_edit()
{
$edit_property_rules = array(
'property_typeId'=>'Required',
'property_statusId'=>'Required',
'property_vendorId'=>'Required',
'property_name'=>'Required|Min:2',
'property_description'=>'Required|Min:20',
'property_locationId'=>'Required',
'property_squareMetres'=>'Required|Numeric',
'property_bathrooms'=>'Required|Numeric',
'property_bedrooms'=>'Required|Numeric',
'property_price'=>'Required|Numeric'
);
return Validator::make(Input::all(), $edit_property_rules);
}
}<file_sep>/app/controllers/FrontEndContactUsController.php
<?php
//Official Website Contact Us Controller Class
class FrontEndContactUsController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Show the official website contact us page.
*/
public function get_new(){
$titles = array('' => 'Select One','Mr.'=>'Mr.','Mrs.'=>'Mrs.','Ms.'=>'Ms.','Miss'=>'Miss','Master'=>'Master',
'Rev.'=>'Rev. (Reverend)','Fr.'=>'Fr. (Father)','Dr.'=>'Dr. (Doctor)','Atty.'=>'Atty. (Attorney)',
'Prof.'=>'Prof. (Professor)','Hon.'=>'Hon. (Honorable)','Pres.'=>'Pres. (President)',
'Gov.'=>'Gov. (Governor)','Coach'=>'Coach','Ofc.'=>'Ofc. (Officer)');
if (Auth::check()){
$customer_id = Auth::user()->getCustomerId();
$customer = Customer::find($customer_id);
$this->layout->content = View::make('frontend.contactus.form')
->with('title', 'Submit Query')
->with('customer', $customer);
}
else {
$this->layout->content = View::make('frontend.contactus.form')
->with('title', 'Submit Query')
->with('customer_title', $titles);
}
}
/**
* Validate and submit a new query, and send an email.
*/
public function post_create(){
$create_query_rules = array(
'customer_title'=>'Required',
'customer_firstName'=>'Required|Min:2',
'customer_lastName'=>'Required|Min:2',
'customer_emailAddress'=>'Required|Min:6|Email',
'contactus_query'=>'Required|Min:20'
);
$validation = Validator::make(Input::all(), $create_query_rules);
if($validation->fails()) {
return Redirect::route('newquery')
->withErrors($validation)
->withInput();
}
else {
$customer_title = Input::get('customer_title');
$customer_firstName = Input::get('customer_firstName');
$customer_lastName = Input::get('customer_lastName');
$customer_emailAddress = Input::get('customer_emailAddress');
$contactus_query = Input::get('contactus_query');
$customer_registered = 'Not Registered';
if (Auth::check())
$customer_registered = 'Registered';
$data = array(
'customer_title'=>$customer_title,
'customer_firstName'=>$customer_firstName,
'customer_lastName'=>$customer_lastName,
'customer_emailAddress'=>$customer_emailAddress,
'customer_registered'=>$customer_registered,
'contactus_query'=>$contactus_query);
Mail::send('frontend.contactus.mails.query', $data,
function($message) use ($customer_title, $customer_firstName, $customer_lastName,
$customer_emailAddress, $customer_registered, $contactus_query) {
$message->to('<EMAIL>', Input::get('customer_firstName').' '.Input::get('customer_lastName'))->subject('Best Property Malta - New Query by '.
$customer_title.' '.$customer_firstName.' '.$customer_lastName);
}
);
return Redirect::route('home')
->with('message', 'Your query was successfully submitted to Best Property Malta!');
}
}
}<file_sep>/app/database/migrations/2014_02_04_175412_add_staff.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddStaff extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('staff')->insert(array(
'staff_title'=>'Mr.',
'staff_firstName'=>'Anthony',
'staff_lastName'=>'Sacco',
'staff_emailAddress'=>'<EMAIL>',
'staff_username'=>'anthsacc',
'staff_password'=>'<PASSWORD>',
'staff_roleId'=>'1',
'staff_employmentDate'=>'2014-02-04 00:00:00',
'staff_idCardNumber'=>'132190M',
'staff_dateOfBirth'=>'1978-02-04 00:00:00',
'staff_addressLine1'=>'Test Address Test Address',
'staff_addressLine2'=>'Test Address Test Address',
'staff_countryId'=>'151',
'staff_phoneNumber'=>'21447351',
'staff_mobileNumber'=>'99297389',
'staff_isActive'=>'1',
'staff_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('staff')->insert(array(
'staff_title'=>'Ms.',
'staff_firstName'=>'Pauline',
'staff_lastName'=>'Sammut',
'staff_emailAddress'=>'<EMAIL>',
'staff_username'=>'p.sammut',
'staff_password'=>'<PASSWORD>kJe07ISWEYLu.zD9F7hwh1aUigSpZb0kaK',
'staff_roleId'=>'2',
'staff_employmentDate'=>'2010-04-14 00:00:00',
'staff_idCardNumber'=>'099284M',
'staff_dateOfBirth'=>'1984-07-14 00:00:00',
'staff_addressLine1'=>'33, Fireplace, Strait Street',
'staff_addressLine2'=>'Luqa, LQA2008',
'staff_countryId'=>'151',
'staff_phoneNumber'=>'21320248',
'staff_mobileNumber'=>'99236728',
'staff_isActive'=>'1',
'staff_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('staff')->insert(array(
'staff_title'=>'Mr.',
'staff_firstName'=>'George',
'staff_lastName'=>'Caruana',
'staff_emailAddress'=>'<EMAIL>',
'staff_username'=>'gcaruana',
'staff_password'=>'<PASSWORD>',
'staff_roleId'=>'2',
'staff_employmentDate'=>'2012-01-09 00:00:00',
'staff_idCardNumber'=>'221187M',
'staff_dateOfBirth'=>'1987-01-14 00:00:00',
'staff_addressLine1'=>'78, Garden View, Maria Schembri Street',
'staff_addressLine2'=>'Floriana, FLR3113',
'staff_countryId'=>'151',
'staff_phoneNumber'=>'27193001',
'staff_mobileNumber'=>'79100023',
'staff_isActive'=>'1',
'staff_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('staff')->insert(array(
'staff_title'=>'Mr.',
'staff_firstName'=>'David',
'staff_lastName'=>'Phyall',
'staff_emailAddress'=>'<EMAIL>',
'staff_username'=>'dphyall89',
'staff_password'=>'<PASSWORD>',
'staff_roleId'=>'3',
'staff_employmentDate'=>'2012-12-08 00:00:00',
'staff_idCardNumber'=>'108489M',
'staff_dateOfBirth'=>'1989-11-10 00:00:00',
'staff_addressLine1'=>'50, Flower, Republic Street',
'staff_addressLine2'=>'Rabat, RBT1334',
'staff_countryId'=>'151',
'staff_phoneNumber'=>'21334211',
'staff_mobileNumber'=>'99236222',
'staff_isActive'=>'1',
'staff_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('staff')->insert(array(
'staff_title'=>'Mrs.',
'staff_firstName'=>'Doris',
'staff_lastName'=>'Azzopardi',
'staff_emailAddress'=>'<EMAIL>',
'staff_username'=>'d.azzopardi',
'staff_password'=>'<PASSWORD>',
'staff_roleId'=>'4',
'staff_employmentDate'=>'2014-02-01 00:00:00',
'staff_idCardNumber'=>'132188M',
'staff_dateOfBirth'=>'1988-02-04 00:00:00',
'staff_addressLine1'=>'9, Courtfield, Main Road',
'staff_addressLine2'=>'Kirkop, KRP2133',
'staff_countryId'=>'151',
'staff_phoneNumber'=>'27233244',
'staff_mobileNumber'=>'99109133',
'staff_isActive'=>'1',
'staff_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('staff')->delete();
}
}<file_sep>/app/controllers/NewsletterController.php
<?php
//Email Newsletter Controller Class
class NewsletterController extends BaseController {
//Enable restful feature
public $restful = true;
/**
* Send the newsletter to all active customers.
*/
public function post_create(){
$latestproperties = DB::table('properties')
->where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->where('property_statusId', Property::getForSaleId())
->orderBy('property_id','desc')->take(10)->get();
$activecustomers = DB::table('customers')->where('customer_isDeleted', '!=', '1')
->orderBy('customer_firstName')->get();
$alllocations = DB::table('locations')->orderBy('location_name')->get();
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
if($activecustomers!=null) {
foreach($activecustomers as $customer) {
$customer_firstName = $customer->customer_firstName;
$customer_lastName = $customer->customer_lastName;
$customer_emailAddress = $customer->customer_emailAddress;
$emaildata = array(
'latestproperties'=>$latestproperties,
'propertylocations'=>$alllocations,
'propertystatuses'=>$allpropertystatuses,
'propertytypes'=>$allpropertytypes,
'customer_firstName'=>$customer_firstName,
'customer_lastName'=>$customer_lastName,
'customer_emailAddress'=>$customer_emailAddress
);
Mail::queue('newsletter.email', $emaildata, function($message)
use ($latestproperties, $alllocations, $allpropertystatuses, $allpropertytypes,
$customer, $customer_firstName, $customer_lastName, $customer_emailAddress){
$message->to($customer_emailAddress, $customer_firstName.' '.$customer_lastName)
->subject('Weekly Email Newsletter');
});
}
return Redirect::route('imshome')
->with('message', 'The newsletter was successfully sent!');
}
else
return Redirect::route('imshome')
->with('error-message', 'No customers are currently available!');
}
}<file_sep>/public/js/customer-form-validator.js
//Customer Validation Script
$(document).ready(function(){
$('#login-details').validate({
rules: {
customer_password: {
minlength: 8,
required: true
},
customer_emailAddress: {
minlength: 6,
required: true,
email: true
},
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.form-control').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('#login-details').on('submit', function () {
if ($('#login-details').valid()) {
$("#customer-login").fadeTo("fast", .5).removeAttr("href");
$("#customer-login").addClass("disabled_anchor");
}
});
$('#login-details').keypress(function(e){
if(e.which == 13){
if ($('#login-details').valid()) {
if (!$("#customer-login").hasClass("disabled_anchor")) {
$("#customer-login").click();
}
}
}
});
$('#customer-password-details').validate({
rules: {
customer_old_password: {
minlength: 8,
required: true
},
customer_new_password: {
minlength: 8,
required: true
},
customer_new_password_confirmation: {
minlength: 8,
required: true,
equalTo: "#customer_new_password"
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.form-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('#customer-password-details').on('submit', function () {
if ($('#customer-password-details').valid()) {
$("#update-password").fadeTo("fast", .5).removeAttr("href");
$("#update-password").addClass("disabled_anchor");
}
});
$('#customer-password-details').keypress(function(e){
if(e.which == 13){
if ($('#customer-password-details').valid()) {
if (!$("#update-password").hasClass("disabled_anchor")) {
$("#update-password").click();
}
}
}
});
$('#customer-details').validate({
rules: {
customer_type: {
required: true
},
customer_title: {
required: true
},
customer_firstName: {
minlength: 2,
required: true
},
customer_lastName: {
minlength: 2,
required: true
},
customer_idCardNumber: {
minlength: 6,
required: true
},
customer_username: {
minlength: 6,
required: true
},
customer_password: {
minlength: 8,
required: true
},
customer_password_confirmation: {
minlength: 8,
required: true,
equalTo: "#customer_password"
},
customer_phoneNumber: {
minlength: 8,
digits: true
},
customer_mobileNumber: {
minlength: 8,
required: true,
digits: true
},
customer_emailAddress: {
minlength: 6,
required: true,
email: true
},
customer_addressLine1: {
minlength: 20,
required: true
},
customer_countryId: {
required: true
},
customer_dateOfBirth: {
date: true,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('#customer-details').on('submit', function () {
if ($('#customer-details').valid()) {
$("#customer").fadeTo("fast", .5).removeAttr("href");
$("#customer").addClass("disabled_anchor");
}
});
$('#customer-details').keypress(function(e){
if(e.which == 13){
return false;
}
});
$("#confirm-remove").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
$("#confirm-remove").addClass("disabled_anchor");
});
}); // end document.ready<file_sep>/app/database/migrations/2014_02_04_181209_add_property_types.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddPropertyTypes extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('property_types')->insert(array(
'property_type_name'=>'Maisonette',
'property_type_description'=>'This is a maisonette.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_types')->insert(array(
'property_type_name'=>'Flat',
'property_type_description'=>'This is a flat.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_types')->insert(array(
'property_type_name'=>'Villa',
'property_type_description'=>'This is a villa.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_types')->insert(array(
'property_type_name'=>'Penthouse',
'property_type_description'=>'This is a penthouse.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_types')->insert(array(
'property_type_name'=>'House of Character',
'property_type_description'=>'This is a house of character.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_types')->insert(array(
'property_type_name'=>'Town House',
'property_type_description'=>'This is a town house.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('property_types')->insert(array(
'property_type_name'=>'Bungalow',
'property_type_description'=>'This is a bungalow.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('property_types')->delete();
}
}<file_sep>/app/controllers/PropertiesController.php
<?php
//CMS Property Controller Class
class PropertiesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.cmslayout";
/**
* Show the CMS's property index page.
*/
public function get_index(){
$allproperties = DB::table('properties')->where('property_isDeleted', '!=', '1')->orderBy('created_at','desc')->paginate(10);
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
$allpropertyvendors = DB::table('customers')->where('customer_type', 'Vendor')->orderBy('customer_firstName')->get();
$this->layout->content = View::make('properties.index')
->with('title', 'List of Properties')
->with('properties', $allproperties)
->with('propertytypes', $allpropertytypes)
->with('propertyvendors', $allpropertyvendors)
->with('propertystatuses', $allpropertystatuses);
}
/**
* Show the CMS's property index page filtered by 'for sale' properties.
*/
public function get_forsaleindex(){
$allproperties = DB::table('properties')->where('property_isDeleted', '!=', '1')
->where('property_statusId', '1')
->orderBy('created_at','desc')->paginate(10);
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
$allpropertyvendors = DB::table('customers')->where('customer_type', 'Vendor')->orderBy('customer_firstName')->get();
$this->layout->content = View::make('properties.index')
->with('title', 'List of Properties')
->with('properties', $allproperties)
->with('propertytypes', $allpropertytypes)
->with('propertyvendors', $allpropertyvendors)
->with('propertystatuses', $allpropertystatuses);
}
/**
* Show the CMS's property index page filtered by 'sold subject to contract' properties.
*/
public function get_soldstcindex(){
$allproperties = DB::table('properties')->where('property_isDeleted', '!=', '1')
->where('property_statusId', '2')
->orderBy('created_at','desc')->paginate(10);
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
$allpropertyvendors = DB::table('customers')->where('customer_type', 'Vendor')->orderBy('customer_firstName')->get();
$this->layout->content = View::make('properties.index')
->with('title', 'List of Properties')
->with('properties', $allproperties)
->with('propertytypes', $allpropertytypes)
->with('propertyvendors', $allpropertyvendors)
->with('propertystatuses', $allpropertystatuses);
}
/**
* Show the CMS's property index page filtered by 'sold' properties.
*/
public function get_soldindex(){
$allproperties = DB::table('properties')->where('property_isDeleted', '!=', '1')
->where('property_statusId', '3')
->orderBy('created_at','desc')->paginate(10);
$allpropertytypes = DB::table('property_types')->orderBy('property_type_name')->get();
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->get();
$allpropertyvendors = DB::table('customers')->where('customer_type', 'Vendor')->orderBy('customer_firstName')->get();
$this->layout->content = View::make('properties.index')
->with('title', 'List of Properties')
->with('properties', $allproperties)
->with('propertytypes', $allpropertytypes)
->with('propertyvendors', $allpropertyvendors)
->with('propertystatuses', $allpropertystatuses);
}
/**
* Show the CMS's property details page.
*/
public function get_view($property_id){
if (Property::find($property_id) != null && !Property::find($property_id)->property_isDeleted) {
$property_typeId = Property::find($property_id)->property_typeId;
$property_typeName = Property_Type::find($property_typeId)->property_type_name;
$property_statusId = Property::find($property_id)->property_statusId;
$property_statusName = Property_Status::find($property_statusId)->property_status_name;
$property_locationId = Property::find($property_id)->property_locationId;
$property_locationName = Location::find($property_locationId)->location_name;
$property_vendorId = Property::find($property_id)->property_vendorId;
$property_vendorName = Customer::find($property_vendorId)->customer_firstName.' '.
Customer::find($property_vendorId)->customer_lastName;
$property_isActive = Property::find($property_id)->property_isActive;
$property_active = 'No';
if($property_isActive==1)
$property_active = 'Yes';
$property_isDeleted = Property::find($property_id)->property_isDeleted;
$property_deleted = 'No';
if($property_isDeleted==1)
$property_deleted = 'Yes';
$property_hasGarage = Property::find($property_id)->property_hasGarage;
$property_garage = 'No';
if($property_hasGarage==1)
$property_garage = 'Yes';
$property_hasGarden = Property::find($property_id)->property_hasGarden;
$property_garden = 'No';
if($property_hasGarden==1)
$property_garden = 'Yes';
$this->layout->content = View::make('properties.view')
->with('title', 'Property View Page')
->with('property', Property::find($property_id))
->with('property_type', $property_typeName)
->with('property_status', $property_statusName)
->with('property_vendor', $property_vendorName)
->with('property_location', $property_locationName)
->with('property_hasGarage', $property_garage)
->with('property_hasGarden', $property_garden)
->with('property_active', $property_active)
->with('property_deleted', $property_deleted);
}
else
return Redirect::route('properties')
->with('error-message', 'Requested Property was not found');
}
/**
* Show the CMS's property creation page.
*/
public function get_new(){
$property_type = array('' => 'Select One') +
Property_Type::lists('property_type_name', 'property_type_id');
$property_status = array('' => 'Select One') +
Property_Status::lists('property_status_name', 'property_status_id');
$property_vendor = array('' => 'Select One') +
Customer::where('customer_type', 'Vendor')
->where('customer_isDeleted', '0')
->get()->lists('full_name', 'customer_id');
$property_location = array('' => 'Select One') +
Location::lists('location_name', 'location_id');
$this->layout->content = View::make('properties.new')
->with('title', 'Add New Property')
->with('property_typeId',$property_type)
->with('property_statusId',$property_status)
->with('property_vendorId',$property_vendor)
->with('property_locationId',$property_location);
}
/**
* Validate and create the property.
*/
public function post_create(){
if(Input::has('property_isActive'))
$isActive = 1;
else
$isActive = 0;
if(Input::has('property_hasGarage'))
$hasGarage = 1;
else
$hasGarage = 0;
if(Input::has('property_hasGarden'))
$hasGarden = 1;
else
$hasGarden = 0;
$validation = Property::validate_create();
if($validation->fails()) {
return Redirect::route('new_property')
->withErrors($validation)
->withInput();
}
else {
Property::create(array(
'property_typeId'=>Input::get('property_typeId'),
'property_statusId'=>Input::get('property_statusId'),
'property_vendorId'=>Input::get('property_vendorId'),
'property_name'=>Input::get('property_name'),
'property_description'=>Input::get('property_description'),
'property_locationId'=>Input::get('property_locationId'),
'property_squareMetres'=>Input::get('property_squareMetres'),
'property_bathrooms'=>Input::get('property_bathrooms'),
'property_bedrooms'=>Input::get('property_bedrooms'),
'property_hasGarage'=>$hasGarage,
'property_hasGarden'=>$hasGarden,
'property_price'=>Input::get('property_price'),
'property_isActive'=>$isActive,
'property_isDeleted'=>'0'
));
return Redirect::route('properties')
->with('message', 'The property was created successfully!');
}
}
/**
* Show the CMS's property modification page.
*/
public function get_edit($property_id){
if(Property::find($property_id) != null){
$property_location = array('' => 'Select One') +
Location::lists('location_name', 'location_id');
$property_type = array('' => 'Select One') +
Property_Type::lists('property_type_name', 'property_type_id');
$property_status = array('' => 'Select One') +
Property_Status::lists('property_status_name', 'property_status_id');
$property_vendor = array('' => 'Select One') +
Customer::where('customer_type', 'Vendor')
->where('customer_isDeleted', '0')
->get()->lists('full_name', 'customer_id');
$property_isActive = Property::find($property_id)->property_isActive;
if($property_isActive==1)
$property_checkbox_enabled=true;
else
$property_checkbox_enabled=false;
$property_hasGarage = Property::find($property_id)->property_hasGarage;
if($property_hasGarage==1)
$garage_checkbox_enabled=true;
else
$garage_checkbox_enabled=false;
$property_hasGarden = Property::find($property_id)->property_hasGarden;
if($property_hasGarden==1)
$garden_checkbox_enabled=true;
else
$garden_checkbox_enabled=false;
$this->layout->content = View::make('properties.edit')
->with('title', 'Edit Property')
->with('property', Property::find($property_id))
->with('property_typeId',$property_type)
->with('property_statusId',$property_status)
->with('property_vendorId',$property_vendor)
->with('property_locationId',$property_location)
->with('property_checkbox_enabled', $property_checkbox_enabled)
->with('garage_checkbox_enabled', $garage_checkbox_enabled)
->with('garden_checkbox_enabled', $garden_checkbox_enabled);
}
else{
return Redirect::route('properties')
->with('error-message', 'Requested Property was not found');
}
}
/**
* Validate and edit the property.
*/
public function put_update(){
$property_id = Input::get('property_id');
if(Input::has('property_isActive'))
$isActive = 1;
else
$isActive = 0;
if(Input::has('property_hasGarage'))
$hasGarage = 1;
else
$hasGarage = 0;
if(Input::has('property_hasGarden'))
$hasGarden = 1;
else
$hasGarden = 0;
$validation = Property::validate_edit();
if($validation->fails()) {
return Redirect::route('edit_property',$property_id)
->withErrors($validation)
->withInput();
}
else {
Property::find($property_id)->update(array(
'property_typeId'=>Input::get('property_typeId'),
'property_statusId'=>Input::get('property_statusId'),
'property_vendorId'=>Input::get('property_vendorId'),
'property_name'=>Input::get('property_name'),
'property_description'=>Input::get('property_description'),
'property_locationId'=>Input::get('property_locationId'),
'property_squareMetres'=>Input::get('property_squareMetres'),
'property_bathrooms'=>Input::get('property_bathrooms'),
'property_bedrooms'=>Input::get('property_bedrooms'),
'property_hasGarage'=>$hasGarage,
'property_hasGarden'=>$hasGarden,
'property_price'=>Input::get('property_price'),
'property_isActive'=>$isActive,
'property_isDeleted'=>'0'
));
return Redirect::route('property', $property_id)
->with('message', 'The property was updated successfully!');
}
}
/**
* Show the CMS's property deletion page.
*/
public function get_destroy($property_id){
$this->layout->content = View::make('properties.confirm-delete')
->with('title', 'Confirm Property Deletion')
->with('property', Property::find($property_id));
}
/**
* Update the property's state to deleted.
*/
public function delete_destroy(){
Property::find(Input::get('property_id'))->update(array(
'property_isActive'=>'0',
'property_isDeleted'=>'1'
));
return Redirect::route('properties')
->with('message', 'The property was deleted successfully!');
}
}<file_sep>/app/models/Interest.php
<?php
/* Interest (Wish List) Model Class */
class Interest extends Eloquent {
//Database table
protected $table = 'interests';
//Primary key of the interests table
protected $primaryKey = 'interest_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('interest_id', 'interest_customerId', 'interest_propertyId');
}<file_sep>/app/controllers/StaffRolesController.php
<?php
//IMS Staff Role Controller Class
class StaffRolesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS's staff role index page.
*/
public function get_index(){
$allstaffroles = DB::table('staff_roles')->orderBy('staff_role_name')->paginate(10);
$this->layout->content = View::make('staff_roles.index')
->with('title', 'List of Staff Roles')
->with('staff_roles', $allstaffroles);
}
/**
* Show the IMS's staff role details page.
*/
public function get_view($staff_role_id){
if (Staff_Role::find($staff_role_id) != null) {
$staff_roleId = Staff_Role::find($staff_role_id);
$this->layout->content = View::make('staff_roles.view')
->with('title', 'Staff Role View Page')
->with('staff_role', Staff_Role::find($staff_role_id));
}
else
return Redirect::route('staff_roles')
->with('error-message', 'Requested Staff Role was not found');
}
/**
* Show the IMS's staff role creation page.
*/
public function get_new(){
$staff_role = array('' => 'Select One') +
Staff_Role::lists('staff_role_name', 'staff_role_id');
$this->layout->content = View::make('staff_roles.new')
->with('title', 'Add New Staff Role')
->with('staff_roleId',$staff_role);
}
/**
* Validate and create the staff role.
*/
public function post_create(){
$validation = Staff_Role::validate_create();
if($validation->fails()) {
return Redirect::route('new_staff_role')
->withErrors($validation)
->withInput();
}
else {
Staff_Role::create(array(
'staff_role_name'=>Input::get('staff_role_name'),
'staff_role_description'=>Input::get('staff_role_description')
));
return Redirect::route('staff_roles')
->with('message', 'The staff role was created successfully!');
}
}
/**
* Show the IMS's staff role modification page.
*/
public function get_edit($staff_role_id){
if(Staff_Role::find($staff_role_id)!=null){
$this->layout->content = View::make('staff_roles.edit')
->with('title', 'Edit Staff Role')
->with('staff_role', Staff_Role::find($staff_role_id));
}
else{
return Redirect::route('staff_roles')
->with('error-message', 'Requested Staff Role was not found');
}
}
/**
* Validate and edit the staff role.
*/
public function put_update(){
$staff_role_id = Input::get('staff_role_id');
$validation = Staff_Role::validate_edit($staff_role_id);
if($validation->fails()) {
return Redirect::route('edit_staff_role', $staff_role_id)
->withErrors($validation);
}
else {
Staff_Role::find($staff_role_id)->update(array(
'staff_role_name'=>Input::get('staff_role_name'),
'staff_role_description'=>Input::get('staff_role_description')
));
return Redirect::route('staff_role', $staff_role_id)
->with('message', 'The staff role was updated successfully!');
}
}
/**
* Show the IMS's staff role deletion page.
*/
public function get_destroy($staff_roleId){
$this->layout->content = View::make('staff_roles.confirm-delete')
->with('title', 'Confirm Staff Role Deletion')
->with('staff_role', Staff_Role::find($staff_roleId));
}
/**
* Delete the staff role.
*/
public function delete_destroy(){
Staff_Role::find(Input::get('staff_role_id'))->delete();
return Redirect::route('staff_roles')
->with('message', 'The staff role was deleted successfully!');
}
}<file_sep>/app/controllers/ImsStaffController.php
<?php
use Illuminate\Auth\AdminGuard;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Hashing\BcryptHasher;
//IMS Staff Controller Class
class ImsStaffController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS's staff login page.
*/
public function get_login(){
if (!Auth::guest())
return Redirect::route('imshome')->with('message', 'You are already logged in!');
else
$this->layout->content = View::make('staff.loginims');
}
/**
* Validate and login the staff member.
*/
public function post_signedin(){
$staffdata = array(
'staff_emailAddress' => Input::get('staff_emailAddress'),
'password' => Input::get('<PASSWORD>')
);
$validation = Staff::validate_login();
if($validation->fails()) {
return Redirect::route('imslogin')
->withErrors($validation)
->withInput();
}
else {
if (Auth::attempt($staffdata)) {
$staff_role = Auth::user()->getRole();
if ($staff_role == 'Content Editor'){
Auth::logout();
return Redirect::route('imslogin')
->with('error-message', 'You cannot access the IMS as a content editor!')
->withInput();
}
else {
$session_staff_id = Auth::user()->staff_id;
return Redirect::route('imshome')->with('message', 'You are now logged in!');
}
} else {
return Redirect::route('imslogin')
->with('error-message', 'Your email address/password combination was incorrect. Please try again.')
->withInput();
}
}
}
/**
* Logout the staff member and show the IMS staff logout page.
*/
public function get_logout()
{
Auth::logout();
return Redirect::route('imslogin')->with('message', 'You are now logged out!');
}
/**
* Show the IMS's staff member index page.
*/
public function get_index(){
$allstaff = DB::table('staff')->where('staff_isDeleted', '!=', '1')->orderBy('staff_firstName')->paginate(10);
$allstaffroles = DB::table('staff_roles')->orderBy('staff_role_name')->get();
$this->layout->content = View::make('staff.index')
->with('title', 'List of Staff')
->with('staff', $allstaff)
->with('staffroles', $allstaffroles);
}
/**
* Show the IMS's staff member details page.
*/
public function get_view($staff_id){
if (Staff::find($staff_id) != null && !Staff::find($staff_id)->staff_isDeleted) {
$staff_roleId = Staff::find($staff_id)->staff_roleId;
$staff_roleName = Staff_Role::find($staff_roleId)->staff_role_name;
$staff_countryId = Staff::find($staff_id)->staff_countryId;
$staff_countryName = Country::find($staff_countryId)->country_name;
$staff_addressLine2 = Staff::find($staff_id)->staff_addressLine2;
if($staff_addressLine2=="")
$staff_addressLine2 = 'N/A';
$staff_phoneNumber = Staff::find($staff_id)->staff_phoneNumber;
if($staff_phoneNumber=="")
$staff_phoneNumber = 'N/A';
$staff_isActive = Staff::find($staff_id)->staff_isActive;
$staff_active = 'No';
if($staff_isActive==1)
$staff_active = 'Yes';
$staff_isDeleted = Staff::find($staff_id)->staff_isDeleted;
$staff_deleted = 'No';
if($staff_isDeleted==1)
$staff_deleted = 'Yes';
$this->layout->content = View::make('staff.view')
->with('title', 'Staff View Page')
->with('staff', Staff::find($staff_id))
->with('staff_role', $staff_roleName)
->with('staff_country', $staff_countryName)
->with('staff_addressLine2', $staff_addressLine2)
->with('staff_phoneNumber', $staff_phoneNumber)
->with('staff_active', $staff_active)
->with('staff_deleted', $staff_deleted);
}
else
return Redirect::route('stafflist')
->with('error-message', 'Requested Staff Member was not found');
}
/**
* Show the IMS's staff member creation page.
*/
public function get_new(){
$staff_role = array('' => 'Select One') +
Staff_Role::lists('staff_role_name', 'staff_role_id');
$countries = array('' => 'Select One') +
Country::lists('country_name', 'country_id');
$titles = array('' => 'Select One','Mr.'=>'Mr.','Mrs.'=>'Mrs.','Ms.'=>'Ms.','Miss'=>'Miss','Master'=>'Master',
'Rev.'=>'Rev. (Reverend)','Fr.'=>'Fr. (Father)','Dr.'=>'Dr. (Doctor)','Atty.'=>'Atty. (Attorney)',
'Prof.'=>'Prof. (Professor)','Hon.'=>'Hon. (Honorable)','Pres.'=>'Pres. (President)',
'Gov.'=>'Gov. (Governor)','Coach'=>'Coach','Ofc.'=>'Ofc. (Officer)');
$this->layout->content = View::make('staff.new')
->with('title', 'Add New Staff Member')
->with('staff_roleId',$staff_role)
->with('staff_countryId', $countries)
->with('staff_title', $titles);
}
/**
* Validate and create the staff member.
*/
public function post_create(){
$dob = str_replace("/", "-", Input::get('staff_dateOfBirth'));
$date_dob = new DateTime($dob);
$formatted_dob = date_format($date_dob, 'Y-m-d H:i:s');
$doe = str_replace("/", "-", Input::get('staff_employmentDate'));
$date_doe = new DateTime($doe);
$formatted_doe = date_format($date_doe, 'Y-m-d H:i:s');
$now = new DateTime();
if(Input::has('staff_isActive'))
$isActive = 1;
else
$isActive = 0;
$validation = Staff::validate_create();
if($validation->fails()) {
return Redirect::route('new_staff')
->withErrors($validation)
->withInput();
}
else {
Staff::create(array(
'staff_title'=>Input::get('staff_title'),
'staff_firstName'=>Input::get('staff_firstName'),
'staff_lastName'=>Input::get('staff_lastName'),
'staff_emailAddress'=>Input::get('staff_emailAddress'),
'staff_username'=>Input::get('staff_username'),
'staff_password'=>Hash::make(Input::get('staff_password')),
'staff_roleId'=>Input::get('staff_roleId'),
'staff_idCardNumber'=>Input::get('staff_idCardNumber'),
'staff_dateOfBirth'=>$formatted_dob,
'staff_employmentDate'=>$formatted_doe,
'staff_addressLine1'=>Input::get('staff_addressLine1'),
'staff_addressLine2'=>Input::get('staff_addressLine2'),
'staff_countryId'=>Input::get('staff_countryId'),
'staff_phoneNumber'=>Input::get('staff_phoneNumber'),
'staff_mobileNumber'=>Input::get('staff_mobileNumber'),
'staff_isActive'=>$isActive,
'staff_isDeleted'=>'0'
));
return Redirect::route('stafflist')
->with('message', 'The staff member was created successfully!');
}
}
/**
* Show the IMS's staff member modification page.
*/
public function get_edit($staff_id){
if(Staff::find($staff_id) != null){
$staff_role = array('' => 'Select One') +
Staff_Role::lists('staff_role_name', 'staff_role_id');
$countries = array('' => 'Select One') +
Country::lists('country_name', 'country_id');
$titles = array('' => 'Select One','Mr.'=>'Mr.','Mrs.'=>'Mrs.','Ms.'=>'Ms.','Miss'=>'Miss','Master'=>'Master',
'Rev.'=>'Rev. (Reverend)','Fr.'=>'Fr. (Father)','Dr.'=>'Dr. (Doctor)','Atty.'=>'Atty. (Attorney)',
'Prof.'=>'Prof. (Professor)','Hon.'=>'Hon. (Honorable)','Pres.'=>'Pres. (President)',
'Gov.'=>'Gov. (Governor)','Coach'=>'Coach','Ofc.'=>'Ofc. (Officer)');
$staff_isActive = Staff::find($staff_id)->staff_isActive;
if($staff_isActive==1)
$checkbox_enabled=true;
else
$checkbox_enabled=false;
$this->layout->content = View::make('staff.edit')
->with('title', 'Edit Staff Member')
->with('staff', Staff::find($staff_id))
->with('staff_roleId',$staff_role)
->with('staff_countryId', $countries)
->with('staff_title', $titles)
->with('checkbox_enabled', $checkbox_enabled);
}
else
return Redirect::route('stafflist')
->with('error-message', 'Requested Staff Member was not found');
}
/**
* Validate and edit the staff member.
*/
public function put_update(){
$staff_id = Input::get('staff_id');
$dob = str_replace("/", "-", Input::get('staff_dateOfBirth'));
$formatted_dob = date_format(new DateTime($dob), 'Y-m-d H:i:s');
$doe = str_replace("/", "-", Input::get('staff_employmentDate'));
$formatted_doe = date_format(new DateTime($doe), 'Y-m-d H:i:s');
$now = new DateTime();
if(Input::has('staff_isActive'))
$isActive = 1;
else
$isActive = 0;
$validation = Staff::validate_edit($staff_id);
if($validation->fails()) {
return Redirect::route('edit_staff', $staff_id)
->withErrors($validation);
}
else {
Staff::find($staff_id)->update(array(
'staff_title'=>Input::get('staff_title'),
'staff_firstName'=>Input::get('staff_firstName'),
'staff_lastName'=>Input::get('staff_lastName'),
'staff_emailAddress'=>Input::get('staff_emailAddress'),
'staff_username'=>Input::get('staff_username'),
'staff_roleId'=>Input::get('staff_roleId'),
'staff_idCardNumber'=>Input::get('staff_idCardNumber'),
'staff_dateOfBirth'=>$formatted_dob,
'staff_employmentDate'=>$formatted_doe,
'staff_addressLine1'=>Input::get('staff_addressLine1'),
'staff_addressLine2'=>Input::get('staff_addressLine2'),
'staff_countryId'=>Input::get('staff_countryId'),
'staff_phoneNumber'=>Input::get('staff_phoneNumber'),
'staff_mobileNumber'=>Input::get('staff_mobileNumber'),
'staff_isActive'=>$isActive,
'staff_isDeleted'=>'0'
));
return Redirect::route('staff', $staff_id)
->with('message', 'The staff member was updated successfully!');
}
}
/**
* Show the IMS staff member password modification page.
*/
public function get_changepassword($staff_id){
$this->layout->content = View::make('staff.changepassword')
->with('title', 'Change Password')
->with('staff', Staff::find($staff_id));
}
/**
* Validate and update the staff member's password.
*/
public function put_updatepassword(){
$staff_id = Input::get('staff_id');
$staff = Staff::find($staff_id);
$validation = Staff::validate_changepassword();
if($validation->fails()) {
return Redirect::route('change_staff_password', $staff_id)
->withErrors($validation);
}
else {
if (Hash::check(Input::get('staff_old_password'), $staff->staff_password)) {
Staff::find($staff_id)->update(array(
'staff_password'=>Hash::make(Input::get('staff_new_password')),
));
return Redirect::route('staff', $staff_id)
->with('message', 'The password was updated successfully!');
}
else {
return Redirect::route('change_staff_password', $staff_id)
->with('error-message', 'The old password inputted is not correct!');
}
}
}
/**
* Show the IMS's staff member deletion page.
*/
public function get_destroy($staff_id){
$this->layout->content = View::make('staff.confirm-delete')
->with('title', 'Confirm Staff Member Deletion')
->with('staff', Staff::find($staff_id));
}
/**
* Update the staff member to a deleted state.
*/
public function delete_destroy(){
Staff::find(Input::get('staff_id'))->update(array(
'staff_isActive'=>'0',
'staff_isDeleted'=>'1'
));
return Redirect::route('stafflist')
->with('message', 'The staff member was deleted successfully!');
}
}<file_sep>/app/controllers/BannerImagesController.php
<?php
//Banner Images Controller Class
class BannerImagesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.cmslayout";
/**
* Show the banner images index page.
*/
public function get_mainindex(){
$this->layout->content = View::make('banner_images.index')
->with('title', 'List of Images')
->with('bannerImages', Banner_Image::orderBy ('created_at', 'desc')
->paginate('6'));
}
/**
* Show the banner images upload page.
*/
public function get_upload(){
$this->layout->content = View::make('banner_images.upload')
->with('title', 'Add New Images');
}
/**
* Upload the banner images.
*/
public function post_upload()
{
$files = Input::file('file');
$serializedFile = array();
foreach ($files as $file) {
// Validate files from input file
$validation = Banner_Image::validateBannerImage(array('file'=> $file));
if (!$validation->fails() && $file->isValid()) {
$fileName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$destinationPath = 'uploads/bannerImages';
// Move file to generated folder
$file->move($destinationPath, $fileName);
// Resize image (using Intervention Image Class)
BImage::make($destinationPath . '/' . $fileName)
->resize(1135, 250)
->save($destinationPath . '/' . $fileName);
Banner_Image::create(array(
'banner_image_name' => $fileName,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
));
}
else {
return Redirect::route('new_banner_images')
->with('status', 'alert-danger')
->with('image-message', 'There was a problem uploading your
image(s)!');
}
}
return Redirect::route('new_banner_images')
->with('status', 'alert-success')
->with('image-message',
'Your image(s) were successfully uploaded');
}
/**
* Delete the banner images.
*/
public function delete_destroy($bannerImageId)
{
Banner_Image::find($bannerImageId)->delete();
return Redirect::back()
->with('status', 'alert-success')
->with('message', 'Image removed successfully');
}
}<file_sep>/app/controllers/OffersController.php
<?php
//IMS Offer Controller Class
class OffersController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS's active offer index page.
*/
public function get_index(){
$alloffers = DB::table('offers')
->where('offer_isDeleted', '!=', '1')
->orderBy('created_at', 'desc')
->paginate(10);
$allproperties = DB::table('properties')->where('property_isDeleted', '!=', '1')->orderBy('property_name')->get();
$allofferstatuses = DB::table('offer_statuses')->orderBy('offer_status_name')->get();
$allbuyers = DB::table('customers')->where('customer_type', 'Buyer')->orderBy('customer_firstName')->get();
$this->layout->content = View::make('offers.index')
->with('title', 'List of Offers')
->with('offers', $alloffers)
->with('properties', $allproperties)
->with('offerstatuses', $allofferstatuses)
->with('buyers', $allbuyers);
}
/**
* Show the IMS's cancelled offer index page.
*/
public function get_cancelledindex(){
$alloffers = DB::table('offers')
->where('offer_isDeleted', '1')
->orderBy('created_at', 'desc')
->paginate(10);
$allproperties = DB::table('properties')->where('property_isDeleted', '!=', '1')->orderBy('property_name')->paginate(10);
$allofferstatuses = DB::table('offer_statuses')->orderBy('offer_status_name')->get();
$allbuyers = DB::table('customers')->where('customer_type', 'Buyer')->orderBy('customer_firstName')->get();
$this->layout->content = View::make('offers.cancelledindex')
->with('title', 'List of Offers')
->with('offers', $alloffers)
->with('properties', $allproperties)
->with('offerstatuses', $allofferstatuses)
->with('buyers', $allbuyers);
}
/**
* Show the IMS's active offer details page.
*/
public function get_view($offer_id){
if (Offer::find($offer_id) != null && !Offer::find($offer_id)->offer_isDeleted) {
$offer_propertyId = Offer::find($offer_id)->offer_propertyId;
$offer_propertyName = Property::find($offer_propertyId)->property_name;
$offer_buyerId = Offer::find($offer_id)->offer_buyerId;
$offer_buyerName = Customer::find($offer_buyerId)->customer_firstName.' '.Customer::find($offer_buyerId)->customer_lastName;
$offer_statusId = Offer::find($offer_id)->offer_statusId;
$offer_statusName = Offer_Status::find($offer_statusId)->offer_status_name;
$offer_isDeleted = Offer::find($offer_id)->offer_isDeleted;
$offer_deleted = 'No';
if($offer_isDeleted==1)
$offer_deleted = 'Yes';
$this->layout->content = View::make('offers.view')
->with('title', 'Offer View Page')
->with('offer', Offer::find($offer_id))
->with('offer_property', $offer_propertyName)
->with('offer_buyer', $offer_buyerName)
->with('offer_status', $offer_statusName)
->with('offer_deleted', $offer_deleted);
}
else
return Redirect::route('offers')
->with('error-message', 'Requested Offer was not found');
}
/**
* Show the IMS's offer creation page.
*/
public function get_new(){
$offer_properties = array('' => 'Select One') +
Property::where('property_isDeleted', '0')
->where('property_statusId', Property::getForSaleId())
->get()->lists('full_name', 'property_id');
$offer_buyers = array('' => 'Select One') +
Customer::where('customer_type', 'Buyer')
->where('customer_isDeleted', '0')
->get()->lists('full_name', 'customer_id');
$offer_statuses = array('' => 'Select One') +
Offer_Status::lists('offer_status_name', 'offer_status_id');
$this->layout->content = View::make('offers.new')
->with('title', 'Add New Offer')
->with('offer_property',$offer_properties)
->with('offer_buyer', $offer_buyers)
->with('offer_status', $offer_statuses);
}
/**
* Validate and create the offer.
*/
public function post_create(){
$validation = Offer::validate_create();
if($validation->fails()) {
return Redirect::route('new_offer')
->withErrors($validation)
->withInput();
}
else {
Offer::create(array(
'offer_value'=>Input::get('offer_value'),
'offer_propertyId'=>Input::get('offer_propertyId'),
'offer_buyerId'=>Input::get('offer_buyerId'),
'offer_statusId'=>Input::get('offer_statusId'),
'offer_isDeleted'=>'0'
));
return Redirect::route('offers')
->with('message', 'The offer was created successfully!');
}
}
/**
* Show the IMS's offer modification page.
*/
public function get_edit($offer_id){
if(Offer::find($offer_id) != null){
$offer_properties = array('' => 'Select One') +
Property::where('property_isDeleted', '0')
->get()->lists('full_name', 'property_id');
$offer_buyers = array('' => 'Select One') +
Customer::where('customer_type', 'Buyer')
->where('customer_isDeleted', '0')
->get()->lists('full_name', 'customer_id');
$offer_statuses = array('' => 'Select One') +
Offer_Status::lists('offer_status_name', 'offer_status_id');
$this->layout->content = View::make('offers.edit')
->with('title', 'Edit Offer')
->with('offer', Offer::find($offer_id))
->with('offer_property',$offer_properties)
->with('offer_buyer', $offer_buyers)
->with('offer_status', $offer_statuses);
}
else
return Redirect::route('offers')
->with('error-message', 'Requested Offer was not found');
}
/**
* Validate and edit the offer.
*/
public function put_update(){
$offer_id = Input::get('offer_id');
$validation = Offer::validate_edit();
if($validation->fails()) {
return Redirect::route('edit_offer', $offer_id)
->withErrors($validation)
->withInput();
}
else {
Offer::find($offer_id)->update(array(
'offer_value'=>Input::get('offer_value'),
'offer_propertyId'=>Input::get('offer_propertyId'),
'offer_buyerId'=>Input::get('offer_buyerId'),
'offer_statusId'=>Input::get('offer_statusId'),
'offer_isDeleted'=>'0'
));
return Redirect::route('offer', $offer_id)
->with('message', 'The offer was updated successfully!');
}
}
/**
* Show the IMS's offer deletion page.
*/
public function get_destroy($offer_id){
$this->layout->content = View::make('offers.confirm-delete')
->with('title', 'Confirm Offer Deletion')
->with('offer', Offer::find($offer_id));
}
/**
* Update the offer's status to 'Cancelled'.
*/
public function delete_destroy(){
Offer::find(Input::get('offer_id'))->update(array(
'offer_statusId'=>Offer::getCancelledId(),
'offer_isDeleted'=>'1'
));
return Redirect::route('offers')
->with('message', 'The offer was deleted successfully!');
}
}<file_sep>/app/models/Image.php
<?php
/* Property Image Model Class */
class Image extends Eloquent {
//Database table
protected $table = 'images';
//Primary key of the image table
protected $primaryKey = 'image_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('image_id','image_name', 'image_propertyId', 'image_isPrimary');
/**
* Get the id of the property image.
*
* @return int
*/
public function getImageId()
{
return $this->image_id;
}
/**
* Upload image validation rules.
* File must be of type image and has a maximum size of 2048KB
*
* @var array
*/
public static $rules = array(
'file' => 'image|max:2048'
);
/**
* Validate image method.
*
* @param file $data
* @return object Validator
*/
public static function validateImage($data)
{
return Validator::make($data, static::$rules);
}
/**
* Relation with properties table.
*
* @return void
*/
public function property()
{
return $this->belongsTo('Property', 'property_id');
}
}<file_sep>/app/controllers/CustomersController.php
<?php
//IMS Customer Controller Class
class CustomersController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS customer index page.
*/
public function get_index(){
$allcustomers = DB::table('customers')->where('customer_isDeleted', '!=', '1')->orderBy('customer_firstName')->paginate(10);
$this->layout->content = View::make('customers.index')
->with('title', 'List of Customers')
->with('customers', $allcustomers);
}
/**
* Show the IMS customer index page filtered by buyers.
*/
public function get_buyersindex(){
$allcustomers = DB::table('customers')
->where('customer_isDeleted', '!=', '1')
->where('customer_type', 'Buyer')
->orderBy('customer_firstName')->paginate(10);
$this->layout->content = View::make('customers.index')
->with('title', 'List of Customers')
->with('customers', $allcustomers);
}
/**
* Show the IMS customer index page filtered by vendors.
*/
public function get_vendorsindex(){
$allcustomers = DB::table('customers')
->where('customer_isDeleted', '!=', '1')
->where('customer_type', 'Vendor')
->orderBy('customer_firstName')->paginate(10);
$this->layout->content = View::make('customers.index')
->with('title', 'List of Customers')
->with('customers', $allcustomers);
}
/**
* Show the IMS customer details page.
*/
public function get_view($customer_id){
if (Customer::find($customer_id) != null && !Customer::find($customer_id)->customer_isDeleted) {
$customer_countryId = Customer::find($customer_id)->customer_countryId;
$customer_countryName = Country::find($customer_countryId)->country_name;
$customer_addressLine2 = Customer::find($customer_id)->customer_addressLine2;
if($customer_addressLine2=="")
$customer_addressLine2 = 'N/A';
$customer_phoneNumber = Customer::find($customer_id)->customer_phoneNumber;
if($customer_phoneNumber=="")
$customer_phoneNumber = 'N/A';
$customer_isActive = Customer::find($customer_id)->customer_isActive;
$customer_active = 'No';
if($customer_isActive==1)
$customer_active = 'Yes';
$customer_isDeleted = Customer::find($customer_id)->customer_isDeleted;
$customer_deleted = 'No';
if($customer_isDeleted==1)
$customer_deleted = 'Yes';
$this->layout->content = View::make('customers.view')
->with('title', 'Customer View Page')
->with('customer', Customer::find($customer_id))
->with('customer_country', $customer_countryName)
->with('customer_addressLine2', $customer_addressLine2)
->with('customer_phoneNumber', $customer_phoneNumber)
->with('customer_active', $customer_active)
->with('customer_deleted', $customer_deleted);
}
else
return Redirect::route('customers')
->with('error-message', 'Requested Customer was not found');
}
/**
* Show the IMS customer creation page.
*/
public function get_new(){
$customer_types = array('' => 'Select One','Buyer'=>'Buyer','Vendor'=>'Vendor');
$countries = array('' => 'Select One') +
Country::lists('country_name', 'country_id');
$titles = array('' => 'Select One','Mr.'=>'Mr.','Mrs.'=>'Mrs.','Ms.'=>'Ms.','Miss'=>'Miss','Master'=>'Master',
'Rev.'=>'Rev. (Reverend)','Fr.'=>'Fr. (Father)','Dr.'=>'Dr. (Doctor)','Atty.'=>'Atty. (Attorney)',
'Prof.'=>'Prof. (Professor)','Hon.'=>'Hon. (Honorable)','Pres.'=>'Pres. (President)',
'Gov.'=>'Gov. (Governor)','Coach'=>'Coach','Ofc.'=>'Ofc. (Officer)');
$this->layout->content = View::make('customers.new')
->with('title', 'Add New Customer')
->with('customer_type',$customer_types)
->with('customer_countryId', $countries)
->with('customer_title', $titles);
}
/**
* Validate and create the customer.
*/
public function post_create(){
$dob = str_replace("/", "-", Input::get('customer_dateOfBirth'));
$date_dob = new DateTime($dob);
$formatted_dob = date_format($date_dob, 'Y-m-d H:i:s');
$now = new DateTime();
if(Input::has('customer_isActive'))
$isActive = 1;
else
$isActive = 0;
$validation = Customer::validate_create();
if($validation->fails()) {
return Redirect::route('new_customer')
->withErrors($validation)
->withInput();
}
else {
Customer::create(array(
'customer_title'=>Input::get('customer_title'),
'customer_firstName'=>Input::get('customer_firstName'),
'customer_lastName'=>Input::get('customer_lastName'),
'customer_emailAddress'=>Input::get('customer_emailAddress'),
'customer_username'=>Input::get('customer_username'),
'customer_password'=>Hash::make(Input::get('customer_password')),
'customer_type'=>Input::get('customer_type'),
'customer_idCardNumber'=>Input::get('customer_idCardNumber'),
'customer_dateOfBirth'=>$formatted_dob,
'customer_addressLine1'=>Input::get('customer_addressLine1'),
'customer_addressLine2'=>Input::get('customer_addressLine2'),
'customer_countryId'=>Input::get('customer_countryId'),
'customer_phoneNumber'=>Input::get('customer_phoneNumber'),
'customer_mobileNumber'=>Input::get('customer_mobileNumber'),
'customer_isActive'=>$isActive,
'customer_isDeleted'=>'0'
));
// Mail::send('customers.mails.welcome', array(
// 'firstname'=>Input::get('customer_firstName')), function($message){
// $message->to(Input::get('customer_emailAddress'), Input::get('customer_firstName').' '.Input::get('customer_lastName'))->subject('Your Registration with Best Property Malta');
// });
return Redirect::route('customers')
->with('message', 'The customer was created successfully!');
}
}
/**
* Show the IMS customer modification page.
*/
public function get_edit($customer_id){
if(Customer::find($customer_id)!=null){
$customer_types = array('' => 'Select One','Buyer'=>'Buyer','Vendor'=>'Vendor');
$countries = array('' => 'Select One') +
Country::lists('country_name', 'country_id');
$titles = array('' => 'Select One','Mr.'=>'Mr.','Mrs.'=>'Mrs.','Ms.'=>'Ms.','Miss'=>'Miss','Master'=>'Master',
'Rev.'=>'Rev. (Reverend)','Fr.'=>'Fr. (Father)','Dr.'=>'Dr. (Doctor)','Atty.'=>'Atty. (Attorney)',
'Prof.'=>'Prof. (Professor)','Hon.'=>'Hon. (Honorable)','Pres.'=>'Pres. (President)',
'Gov.'=>'Gov. (Governor)','Coach'=>'Coach','Ofc.'=>'Ofc. (Officer)');
$customer_isActive = Customer::find($customer_id)->customer_isActive;
if($customer_isActive==1)
$checkbox_enabled=true;
else
$checkbox_enabled=false;
$this->layout->content = View::make('customers.edit')
->with('title', 'Edit Customer')
->with('customer', Customer::find($customer_id))
->with('customer_type',$customer_types)
->with('customer_countryId', $countries)
->with('customer_title', $titles)
->with('checkbox_enabled', $checkbox_enabled);
}
else{
return Redirect::route('customers')
->with('error-message', 'Requested Customer was not found');
}
}
/**
* Validate and edit the customer.
*/
public function put_update(){
$customer_id = Input::get('customer_id');
$dob = str_replace("/", "-", Input::get('customer_dateOfBirth'));
$formatted_dob = date_format(new DateTime($dob), 'Y-m-d H:i:s');
$now = new DateTime();
if(Input::has('customer_isActive'))
$isActive = 1;
else
$isActive = 0;
$validation = Customer::validate_edit($customer_id);
if($validation->fails()) {
return Redirect::route('edit_customer', $customer_id)
->withErrors($validation);
}
else {
Customer::find($customer_id)->update(array(
'customer_title'=>Input::get('customer_title'),
'customer_firstName'=>Input::get('customer_firstName'),
'customer_lastName'=>Input::get('customer_lastName'),
'customer_emailAddress'=>Input::get('customer_emailAddress'),
'customer_username'=>Input::get('customer_username'),
'customer_type'=>Input::get('customer_type'),
'customer_idCardNumber'=>Input::get('customer_idCardNumber'),
'customer_dateOfBirth'=>$formatted_dob,
'customer_addressLine1'=>Input::get('customer_addressLine1'),
'customer_addressLine2'=>Input::get('customer_addressLine2'),
'customer_countryId'=>Input::get('customer_countryId'),
'customer_phoneNumber'=>Input::get('customer_phoneNumber'),
'customer_mobileNumber'=>Input::get('customer_mobileNumber'),
'customer_isActive'=>$isActive,
'customer_isDeleted'=>'0'
));
return Redirect::route('customer', $customer_id)
->with('message', 'The customer was updated successfully!');
}
}
/**
* Show the IMS customer password modification page.
*/
public function get_changepassword($customer_id){
$this->layout->content = View::make('customers.changepassword')
->with('title', 'Change Password')
->with('customer', Customer::find($customer_id));
}
/**
* Validate and update the customer's password.
*/
public function put_updatepassword(){
$customer_id = Input::get('customer_id');
$customer = Customer::find($customer_id);
$validation = Customer::validate_changepassword();
if($validation->fails()) {
return Redirect::back()
->withErrors($validation);
}
else {
if (Hash::check(Input::get('customer_old_password'), $customer->customer_password)) {
Customer::find($customer_id)->update(array(
'customer_password'=><PASSWORD>::make(Input::get('customer_new_password')),
));
return Redirect::route('customer', $customer_id)
->with('message', 'The password was updated successfully!');
}
else {
return Redirect::route('change_customer_password', $customer_id)
->with('error-message', 'The old password inputted is not correct!');
}
}
}
/**
* Show the IMS customer deletion page.
*/
public function get_destroy($customer_id){
$this->layout->content = View::make('customers.confirm-delete')
->with('title', 'Confirm Customer Deletion')
->with('customer', Customer::find($customer_id));
}
/**
* Update the customer to a deleted state.
*/
public function delete_destroy(){
Customer::find(Input::get('customer_id'))->update(array(
'customer_isActive'=>'0',
'customer_isDeleted'=>'1'
));
return Redirect::route('customers')
->with('message', 'The customer was deleted successfully!');
}
}<file_sep>/app/database/migrations/2014_02_03_172956_create_customers_table.php
<?php
use Illuminate\Database\Migrations\Migration;
class CreateCustomersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('customers', function($table){
$table->increments('customer_id');
$table->string('customer_title');
$table->string('customer_firstName');
$table->string('customer_lastName');
$table->string('customer_emailAddress');
$table->string('customer_username');
$table->string('customer_password');
$table->string('customer_type');
$table->string('customer_idCardNumber');
$table->dateTime('customer_dateOfBirth');
$table->string('customer_addressLine1');
$table->string('customer_addressLine2')->nullable();
$table->unsignedInteger('customer_countryId');
$table->foreign('customer_countryId')
->references('country_id')->on('countries')
->onDelete('cascade')
->onUpdate('cascade');
$table->string('customer_phoneNumber')->nullable();
$table->string('customer_mobileNumber');
$table->tinyInteger('customer_isActive');
$table->tinyInteger('customer_isDeleted');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('customers');
}
}<file_sep>/app/database/migrations/2014_02_04_175737_create_properties_table.php
<?php
use Illuminate\Database\Migrations\Migration;
class CreatePropertiesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('properties', function($table){
$table->increments('property_id');
$table->unsignedInteger('property_typeId');
$table->foreign('property_typeId')
->references('property_type_id')->on('property_types')
->onDelete('cascade')
->onUpdate('cascade');
$table->unsignedInteger('property_statusId');
$table->foreign('property_statusId')
->references('property_status_id')->on('property_statuses')
->onDelete('cascade')
->onUpdate('cascade');
$table->unsignedInteger('property_vendorId');
$table->foreign('property_vendorId')
->references('customer_id')->on('customers')
->onDelete('cascade')
->onUpdate('cascade');
$table->string('property_name');
$table->longText('property_description');
$table->unsignedInteger('property_locationId');
$table->foreign('property_locationId')
->references('location_id')->on('locations')
->onDelete('cascade')
->onUpdate('cascade');
$table->float('property_squareMetres');
$table->integer('property_bathrooms');
$table->integer('property_bedrooms');
$table->tinyInteger('property_hasGarage');
$table->tinyInteger('property_hasGarden');
$table->decimal('property_price', 10, 2);
$table->tinyInteger('property_isActive');
$table->tinyInteger('property_isDeleted');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('properties');
}
}<file_sep>/app/controllers/PagesController.php
<?php
//CMS Page Controller Class
class PagesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.cmslayout";
/**
* Show the CMS's page index view.
*/
public function get_index(){
$allpages = DB::table('pages')->where('page_isDeleted', '!=', '1')
->orderBy('created_at','desc')->paginate(10);
$this->layout->content = View::make('pages.index')
->with('title', 'List of Pages')
->with('pages', $allpages);
}
/**
* Show the CMS's page details view.
*/
public function get_view($page_id){
if (Page::find($page_id) != null && !Page::find($page_id)->page_isDeleted) {
$page_isPublished = Page::find($page_id)->page_isPublished;
$page_published = 'No';
if($page_isPublished==1)
$page_published = 'Yes';
$page_isDeleted = Page::find($page_id)->page_isDeleted;
$page_deleted = 'No';
if($page_isDeleted==1)
$page_deleted = 'Yes';
$this->layout->content = View::make('pages.view')
->with('title', 'Page View Page')
->with('page', Page::find($page_id))
->with('page_published', $page_published)
->with('page_deleted', $page_deleted);
}
else
return Redirect::route('pages')
->with('error-message', 'Requested Page was not found');
}
/**
* Show the CMS's page creation view.
*/
public function get_new(){
$this->layout->content = View::make('pages.new')
->with('title', 'Add New Page');
}
/**
* Validate and create the page.
*/
public function post_create(){
if(Input::has('page_isPublished'))
$isPublished = 1;
else
$isPublished = 0;
$validation = Page::validate_create();
if($validation->fails()) {
return Redirect::route('new_page')
->withErrors($validation)
->withInput();
}
else {
Page::create(array(
'page_title'=>Input::get('page_title'),
'page_content'=>Input::get('page_content'),
'page_isPublished'=>$isPublished,
'page_isDeleted'=>'0'
));
return Redirect::route('pages')
->with('message', 'The page was created successfully!');
}
}
/**
* Show the CMS's page modification view.
*/
public function get_edit($page_id){
if(Page::find($page_id) != null){
$page_isPublished = Page::find($page_id)->page_isPublished;
if($page_isPublished==1)
$checkbox_enabled=true;
else
$checkbox_enabled=false;
$this->layout->content = View::make('pages.edit')
->with('title', 'Edit Page')
->with('page', Page::find($page_id))
->with('checkbox_enabled', $checkbox_enabled);
}
else
return Redirect::route('pages')
->with('error-message', 'Requested Page was not found');
}
/**
* Validate and edit the page.
*/
public function put_update(){
$page_id = Input::get('page_id');
if(Input::has('page_isPublished'))
$isPublished = 1;
else
$isPublished = 0;
$validation = Page::validate_edit($page_id);
if($validation->fails()) {
return Redirect::route('edit_page', $page_id)
->withErrors($validation);
}
else {
Page::find($page_id)->update(array(
'page_title'=>Input::get('page_title'),
'page_content'=>Input::get('page_content'),
'page_isPublished'=>$isPublished,
'page_isDeleted'=>'0'
));
return Redirect::route('page', $page_id)
->with('message', 'The page was updated successfully!');
}
}
/**
* Show the CMS's page deletion view.
*/
public function get_destroy($page_id){
$this->layout->content = View::make('pages.confirm-delete')
->with('title', 'Confirm Page Deletion')
->with('page', Page::find($page_id));
}
/**
* Update the page's state to deleted.
*/
public function delete_destroy(){
Page::find(Input::get('page_id'))->update(array(
'page_isPublished'=>'0',
'page_isDeleted'=>'1'
));
return Redirect::route('pages')
->with('message', 'The page was deleted successfully!');
}
}
<file_sep>/app/controllers/InterestsController.php
<?php
//Interest (Wish List) Controller Class
class InterestsController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Add the property to the customer's wish list.
*/
public function post_create(){
Interest::create(array(
'interest_customerId'=>Auth::user()->getCustomerId(),
'interest_propertyId'=>Input::get('property_id')
));
return Redirect::back()
->with('message', 'The property was successfully added to your wishlist!');
}
/**
* Remove the property from the customer's wish list.
*/
public function delete_destroy(){
Interest::where('interest_customerId', Auth::user()->getCustomerId())
->where('interest_propertyId', Input::get('property_id'))
->delete();
return Redirect::back()
->with('message', 'The property was successfully removed from your wishlist!');
}
}<file_sep>/app/routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
//Filter for registered staff members for the CMS
Route::filter('registered_cms_user', function()
{
if (Auth::guest())
{
return Redirect::route('cmslogin')
->with('error-message', 'Please login!');
}
});
//Filter for registered staff members for the IMS
Route::filter('registered_ims_user', function()
{
if (Auth::guest())
{
return Redirect::route('imslogin')
->with('error-message', 'Please login!');
}
});
//Filter for registered customers on the official website
Route::filter('registered_frontend_user', function()
{
if (Auth::guest())
{
return Redirect::route('customerlogin')
->with('error-message', 'Please login!');
}
});
//Filter for registered administrators
Route::filter('registered_administrator', function()
{
if (Auth::user()->getRole()!="Administrator")
{
return Redirect::route('imshome')
->with('error-message', 'Restricted Area!');
}
});
//Filter for registered administrators and content editors
Route::filter('registered_administrator_contenteditor', function()
{
if (Auth::user()->getRole()!="Administrator" && Auth::user()->getRole()!="Content Editor")
{
return Redirect::route('cmshome')
->with('error-message', 'Restricted Area!');
}
});
//Filter for registered administrators and estate agents
Route::filter('registered_administrator_estateagent', function()
{
if (Auth::user()->getRole()!="Administrator" && Auth::user()->getRole()!="Estate Agent")
{
return Redirect::route('imshome')
->with('error-message', 'Restricted Area!');
}
});
//Paths accessible to all users
Route::get('/', array('as' => 'home', 'uses' => 'WebsiteController@get_home'));
Route::get('customer/login', ['http', 'as' => 'customerlogin', 'uses' => 'FrontEndCustomersController@get_login']);
Route::get('customer/loggedout', array('as'=>'customerloggedout', 'uses' => 'FrontEndCustomersController@get_logout'));
Route::post('customer/signedin', array('uses'=>'FrontEndCustomersController@post_signedin'));
Route::get('customer/new', array('as'=>'newcustomer', 'uses'=>'FrontEndCustomersController@get_new'));
Route::post('customer/create', array('before'=>'csrf', 'uses'=>'FrontEndCustomersController@post_create'));
Route::get('search', array('uses'=>'SearchController@get_search'));
Route::post('search', array('uses'=>'SearchController@post_search'));
Route::get('page/{page_id}', array('as' => 'webpage', 'uses' => 'FrontEndPagesController@get_view'));
Route::get('about-us', array('as' => 'aboutus', 'uses' => 'FrontEndPagesController@get_aboutus'));
Route::get('properties', array('as'=>'webproperties','uses'=>'FrontEndPropertiesController@get_index'));
Route::get('properties/filtered', array('as'=>'webpropertiesfiltered','uses'=>'FrontEndPropertiesController@get_filteredindex'));
Route::get('property/{property_id}', array('as' => 'webproperty', 'uses' => 'FrontEndPropertiesController@get_view'));
Route::get('query/new', array('as'=>'newquery', 'uses'=>'FrontEndContactUsController@get_new'));
Route::post('query/create', array('before'=>'csrf', 'uses'=>'FrontEndContactUsController@post_create'));
Route::get('/ims', array('as' => 'imshome', 'uses' => 'ImsController@get_home'));
Route::get('ims/staff/login', ['http', 'as' => 'imslogin', 'uses' => 'ImsStaffController@get_login']);
Route::get('ims/staff/loggedout', array('as'=>'imsloggedout', 'uses' => 'ImsStaffController@get_logout'));
Route::post('ims/staff/signedin', array('uses'=>'ImsStaffController@post_signedin'));
Route::get('/cms', array('as' => 'cmshome', 'uses' => 'CmsController@get_home'));
Route::get('cms/staff/login', ['http', 'as' => 'cmslogin', 'uses' => 'CmsStaffController@get_login']);
Route::get('cms/staff/loggedout', array('as'=>'cmsloggedout', 'uses' => 'CmsStaffController@get_logout'));
Route::post('cms/staff/signedin', array('uses'=>'CmsStaffController@post_signedin'));
//Paths accessible only to registered customers on the official website
Route::group(array('before' => 'registered_frontend_user'), function()
{
Route::get('customerprofile', array('as'=>'customer_profile','uses'=>'FrontEndCustomersController@get_view'));
Route::get('customerprofile/edit', array('as'=>'edit_customer_profile', 'uses'=>'FrontEndCustomersController@get_edit'));
Route::put('customerprofile/update', array('before'=>'csrf', 'uses'=>'FrontEndCustomersController@put_update'));
Route::get('customerprofile/changepassword', array('as'=>'change_customer_profile_password', 'uses'=>'FrontEndCustomersController@get_changepassword'));
Route::put('customerprofile/updatepassword', array('before'=>'csrf', 'uses'=>'FrontEndCustomersController@put_updatepassword'));
Route::get('properties/myproperties', array('as'=>'mywebproperties','uses'=>'FrontEndPropertiesController@get_myindex'));
Route::get('offers', array('as'=>'buyer_offers','uses'=>'FrontEndOffersController@get_index'));
Route::get('offer/{offer_id}', array('as'=>'buyer_offer','uses'=>'FrontEndOffersController@get_view'));
Route::get('offers/{property_id}/new', array('as'=>'new_buyer_offer', 'uses'=>'FrontEndOffersController@get_new'));
Route::post('offers/create', array('before'=>'csrf', 'uses'=>'FrontEndOffersController@post_create'));
Route::get('offer/{offer_id}/edit', array('as'=>'edit_buyer_offer', 'uses'=>'FrontEndOffersController@get_edit'));
Route::put('offers/update', array('before'=>'csrf', 'uses'=>'FrontEndOffersController@put_update'));
Route::put('offers/accept', array('before'=>'csrf', 'uses'=>'FrontEndOffersController@put_accept'));
Route::put('offers/reject', array('before'=>'csrf', 'uses'=>'FrontEndOffersController@put_reject'));
Route::put('offers/confirm', array('before'=>'csrf', 'uses'=>'FrontEndOffersController@put_confirm'));
Route::delete('offers/delete', array('before'=>'csrf', 'uses'=>'FrontEndOffersController@delete_destroy'));
Route::post('interests/create', array('as'=>'addwatch', 'before'=>'csrf', 'uses'=>'InterestsController@post_create'));
Route::delete('interests/delete', array('as'=>'removewatch', 'before'=>'csrf', 'uses'=>'InterestsController@delete_destroy'));
});
//Paths accessible only to staff member roles within the IMS
Route::group(array('before' => 'registered_ims_user'), function()
{
//Paths accessible only to administrators
Route::group(array('before' => 'registered_administrator'), function()
{
Route::post('ims/newsletter/create', array('before'=>'csrf', 'uses'=>'NewsletterController@post_create'));
Route::get('ims/customers', array('as'=>'customers','uses'=>'CustomersController@get_index'));
Route::get('ims/customer/{customer_id}', array('as'=>'customer','uses'=>'CustomersController@get_view'));
Route::get('ims/customers/buyers', array('as'=>'buyers','uses'=>'CustomersController@get_buyersindex'));
Route::get('ims/customers/vendors', array('as'=>'vendors','uses'=>'CustomersController@get_vendorsindex'));
Route::get('ims/customers/new', array('as'=>'new_customer', 'uses'=>'CustomersController@get_new'));
Route::post('ims/customers/create', array('before'=>'csrf', 'uses'=>'CustomersController@post_create'));
Route::get('ims/customer/{customer_id}/edit', array('as'=>'edit_customer', 'uses'=>'CustomersController@get_edit'));
Route::put('ims/customers/update', array('before'=>'csrf', 'uses'=>'CustomersController@put_update'));
Route::get('ims/customer/{customer_id}/changepassword', array('as'=>'change_customer_password', 'uses'=>'CustomersController@get_changepassword'));
Route::put('ims/customers/updatepassword', array('before'=>'csrf', 'uses'=>'CustomersController@put_updatepassword'));
Route::get('ims/customer/{customer_id}/delete', array('as'=>'confirm_customer_delete','uses'=>'CustomersController@get_destroy'));
Route::delete('ims/customers/delete', array('as'=>'delete_customer','before'=>'csrf', 'uses'=>'CustomersController@delete_destroy'));
Route::get('ims/staff', array('as'=>'stafflist','uses'=>'ImsStaffController@get_index'));
Route::get('ims/staffmember/{staff_id}', array('as'=>'staff','uses'=>'ImsStaffController@get_view'));
Route::get('ims/staff/new', array('as'=>'new_staff', 'uses'=>'ImsStaffController@get_new'));
Route::post('ims/staff/create', array('before'=>'csrf', 'uses'=>'ImsStaffController@post_create'));
Route::get('ims/staffmember/{staff_id}/edit', array('as'=>'edit_staff', 'uses'=>'ImsStaffController@get_edit'));
Route::put('ims/staff/update', array('before'=>'csrf', 'uses'=>'ImsStaffController@put_update'));
Route::get('ims/staff/{staff_id}/changepassword', array('as'=>'change_staff_password', 'uses'=>'ImsStaffController@get_changepassword'));
Route::put('ims/staff/updatepassword', array('before'=>'csrf', 'uses'=>'ImsStaffController@put_updatepassword'));
Route::get('ims/staffmember/{staff_id}/delete', array('as'=>'confirm_staff_delete', 'uses'=>'ImsStaffController@get_destroy'));
Route::delete('ims/staff/delete', array('before'=>'csrf', 'uses'=>'ImsStaffController@delete_destroy'));
Route::get('ims/staff_roles', array('as'=>'staff_roles','uses'=>'StaffRolesController@get_index'));
Route::get('ims/staff_role/{staff_role_id}', array('as'=>'staff_role','uses'=>'StaffRolesController@get_view'));
Route::get('ims/staff_roles/new', array('as'=>'new_staff_role', 'uses'=>'StaffRolesController@get_new'));
Route::post('ims/staff_roles/create', array('before'=>'csrf', 'uses'=>'StaffRolesController@post_create'));
Route::get('ims/staff_role/{staff_role_id}/edit', array('as'=>'edit_staff_role', 'uses'=>'StaffRolesController@get_edit'));
Route::put('ims/staff_roles/update', array('before'=>'csrf', 'uses'=>'StaffRolesController@put_update'));
Route::get('ims/staff_role/{staff_role_id}/delete', array('as'=>'confirm_staff_role_delete', 'uses'=>'StaffRolesController@get_destroy'));
Route::delete('ims/staff_roles/delete', array('before'=>'csrf', 'uses'=>'StaffRolesController@delete_destroy'));
Route::get('ims/property_types', array('as'=>'property_types','uses'=>'PropertyTypesController@get_index'));
Route::get('ims/property_type/{property_type_id}', array('as'=>'property_type','uses'=>'PropertyTypesController@get_view'));
Route::get('ims/property_types/new', array('as'=>'new_property_type', 'uses'=>'PropertyTypesController@get_new'));
Route::post('ims/property_types/create', array('before'=>'csrf', 'uses'=>'PropertyTypesController@post_create'));
Route::get('ims/property_type/{property_type_id}/edit', array('as'=>'edit_property_type', 'uses'=>'PropertyTypesController@get_edit'));
Route::put('ims/property_types/update', array('before'=>'csrf', 'uses'=>'PropertyTypesController@put_update'));
Route::get('ims/property_type/{property_type_id}/delete', array('as'=>'confirm_property_type_delete','uses'=>'PropertyTypesController@get_destroy'));
Route::delete('ims/property_types/delete', array('before'=>'csrf', 'uses'=>'PropertyTypesController@delete_destroy'));
Route::get('ims/property_statuses', array('as'=>'property_statuses','uses'=>'PropertyStatusesController@get_index'));
Route::get('ims/property_status/{property_status_id}', array('as'=>'property_status','uses'=>'PropertyStatusesController@get_view'));
Route::get('ims/property_statuses/new', array('as'=>'new_property_status', 'uses'=>'PropertyStatusesController@get_new'));
Route::post('ims/property_statuses/create', array('before'=>'csrf', 'uses'=>'PropertyStatusesController@post_create'));
Route::get('ims/property_status/{property_status_id}/edit', array('as'=>'edit_property_status', 'uses'=>'PropertyStatusesController@get_edit'));
Route::put('ims/property_statuses/update', array('before'=>'csrf', 'uses'=>'PropertyStatusesController@put_update'));
Route::get('ims/property_status/{property_status_id}/delete', array('as'=>'confirm_property_status_delete','uses'=>'PropertyStatusesController@get_destroy'));
Route::delete('ims/property_statuses/delete', array('before'=>'csrf', 'uses'=>'PropertyStatusesController@delete_destroy'));
Route::get('ims/offer_statuses', array('as'=>'offer_statuses','uses'=>'OfferStatusesController@get_index'));
Route::get('ims/offer_status/{offer_status_id}', array('as'=>'offer_status','uses'=>'OfferStatusesController@get_view'));
Route::get('ims/offer_statuses/new', array('as'=>'new_offer_status', 'uses'=>'OfferStatusesController@get_new'));
Route::post('ims/offer_statuses/create', array('before'=>'csrf', 'uses'=>'OfferStatusesController@post_create'));
Route::get('ims/offer_status/{offer_status_id}/edit', array('as'=>'edit_offer_status', 'uses'=>'OfferStatusesController@get_edit'));
Route::put('ims/offer_statuses/update', array('before'=>'csrf', 'uses'=>'OfferStatusesController@put_update'));
Route::get('ims/offer_status/{offer_status_id}/delete', array('as'=>'confirm_offer_status_delete','uses'=>'OfferStatusesController@get_destroy'));
Route::delete('ims/offer_statuses/delete', array('before'=>'csrf', 'uses'=>'OfferStatusesController@delete_destroy'));
});
//Paths accessible only to administrators and estate agents
Route::group(array('before' => 'registered_administrator_estateagent'), function()
{
Route::get('ims/offers', array('as'=>'offers','uses'=>'OffersController@get_index'));
Route::get('ims/offers/cancelled', array('as'=>'cancelledoffers','uses'=>'OffersController@get_cancelledindex'));
Route::get('ims/offer/{offer_id}', array('as'=>'offer','uses'=>'OffersController@get_view'));
Route::get('ims/offers/new', array('as'=>'new_offer', 'uses'=>'OffersController@get_new'));
Route::post('ims/offers/create', array('before'=>'csrf', 'uses'=>'OffersController@post_create'));
Route::get('ims/offer/{offer_id}/edit', array('as'=>'edit_offer', 'uses'=>'OffersController@get_edit'));
Route::put('ims/offers/update', array('before'=>'csrf', 'uses'=>'OffersController@put_update'));
Route::get('ims/offer/{offer_id}/delete', array('as'=>'confirm_offer_delete','uses'=>'OffersController@get_destroy'));
Route::delete('ims/offers/delete', array('before'=>'csrf', 'uses'=>'OffersController@delete_destroy'));
});
});
//Paths accessible only to staff member roles within the CMS
Route::group(array('before' => 'registered_cms_user'), function()
{
//Paths accessible only to administrators and estate agents
Route::group(array('before' => 'registered_administrator_estateagent'), function()
{
Route::get('cms/properties', array('as'=>'properties','uses'=>'PropertiesController@get_index'));
Route::get('cms/properties/forsale', array('as'=>'propertiesforsale','uses'=>'PropertiesController@get_forsaleindex'));
Route::get('cms/properties/soldstc', array('as'=>'stcproperties','uses'=>'PropertiesController@get_soldstcindex'));
Route::get('cms/properties/sold', array('as'=>'soldproperties','uses'=>'PropertiesController@get_soldindex'));
Route::get('cms/property/{property_id}', array('as'=>'property','uses'=>'PropertiesController@get_view'));
Route::get('cms/properties/new', array('as'=>'new_property', 'uses'=>'PropertiesController@get_new'));
Route::post('cms/properties/create', array('before'=>'csrf', 'uses'=>'PropertiesController@post_create'));
Route::get('cms/property/{property_id}/edit', array('as'=>'edit_property', 'uses'=>'PropertiesController@get_edit'));
Route::put('cms/properties/update', array('before'=>'csrf', 'uses'=>'PropertiesController@put_update'));
Route::get('cms/property/{property_id}/delete', array('as'=>'confirm_property_delete','uses'=>'PropertiesController@get_destroy'));
Route::delete('cms/properties/delete', array('before'=>'csrf', 'uses'=>'PropertiesController@delete_destroy'));
});
//Paths accessible only to administrators and content editors
Route::group(array('before' => 'registered_administrator_contenteditor'), function()
{
Route::get('cms/images', array('as'=>'images','uses'=>'ImagesController@get_mainindex'));
Route::get('cms/images/add', array('as'=>'new_images','uses'=>'ImagesController@get_upload'));
Route::post('cms/images/upload', array('uses'=>'ImagesController@post_upload'));
Route::get('cms/images/{property_id}', array('as'=>'propertyimages','uses'=>'ImagesController@get_propertyindex'));
Route::put('cms/images/setasprimary/{property_id}/{image_id}', array('before'=>'csrf', 'uses'=>'ImagesController@put_setPrimary'));
Route::delete('cms/images/delete/{image_id}', array('before'=>'csrf', 'uses'=>'ImagesController@delete_destroy'));
Route::get('cms/banner_images', array('as'=>'banner_images','uses'=>'BannerImagesController@get_mainindex'));
Route::get('cms/banner_images/add', array('as'=>'new_banner_images','uses'=>'BannerImagesController@get_upload'));
Route::post('cms/banner_images/upload', array('uses'=>'BannerImagesController@post_upload'));
Route::delete('cms/banner_images/delete/{banner_image_id}', array('before'=>'csrf', 'uses'=>'BannerImagesController@delete_destroy'));
Route::get('cms/pages', array('as'=>'pages','uses'=>'PagesController@get_index'));
Route::get('cms/page/{page_id}', array('as'=>'page','uses'=>'PagesController@get_view'));
Route::get('cms/pages/new', array('as'=>'new_page', 'uses'=>'PagesController@get_new'));
Route::post('cms/pages/create', array('before'=>'csrf', 'uses'=>'PagesController@post_create'));
Route::get('cms/page/{page_id}/edit', array('as'=>'edit_page', 'uses'=>'PagesController@get_edit'));
Route::put('cms/pages/update', array('before'=>'csrf', 'uses'=>'PagesController@put_update'));
Route::get('cms/page/{page_id}/delete', array('as'=>'confirm_page_delete','uses'=>'PagesController@get_destroy'));
Route::delete('cms/pages/delete', array('as'=>'delete_page','before'=>'csrf', 'uses'=>'PagesController@delete_destroy'));
});
});<file_sep>/app/models/Customer.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
/* Customer Model Class */
class Customer extends Eloquent implements UserInterface, RemindableInterface {
//Database table
protected $table = 'customers';
//Primary key of the customers table
protected $primaryKey = 'customer_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('customer_id','customer_type', 'customer_title', 'customer_firstName',
'customer_lastName', 'customer_idCardNumber', 'customer_username', 'customer_password', 'customer_phoneNumber',
'customer_mobileNumber', 'customer_emailAddress', 'customer_addressLine1', 'customer_addressLine2',
'customer_countryId', 'customer_dateOfBirth', 'customer_isActive', 'customer_isDeleted');
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('customer_password');
protected $guarded = array('customer_id', 'customer_password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->customer_password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->customer_emailAddress;
}
/**
* Get the id of the customer.
*
* @return int
*/
public function getCustomerId()
{
return $this->customer_id;
}
/**
* Get the customer's full name.
*
* @return string
*/
public function getName()
{
return $this->customer_firstName. ' ' . $this->customer_lastName;
}
/**
* Get the customer's first name.
*
* @return string
*/
public function getFirstName()
{
return $this->customer_firstName;
}
/**
* Get the customer's last name.
*
* @return string
*/
public function getLastName()
{
return $this->customer_lastName;
}
/**
* Get the customer's email address.
*
* @return string
*/
public function getEmailAddress()
{
return $this->customer_emailAddress;
}
/**
* Get the customer type.
*
* @return string
*/
public function getType()
{
return $this->customer_type;
}
/**
* Get the customer title.
*
* @return string
*/
public function getTitle()
{
return $this->customer_title;
}
/**
* Get the customer's id and full name.
*
* @return string
*/
public function getFullNameAttribute()
{
return $this->attributes['customer_id'].': '.$this->attributes['customer_firstName'].' '.$this->attributes['customer_lastName'];
}
/**
* Get the customer's full name.
*
* @return string
*/
public function getFEFullNameAttribute()
{
return $this->attributes['customer_firstName'].' '.$this->attributes['customer_lastName'];
}
/**
* Validate login method.
*
* @return object Validator
*/
public static function validate_login()
{
$customer_login_rules = array(
'customer_emailAddress'=>'Required|Min:6|Email',
'customer_password'=>'<PASSWORD>'
);
return Validator::make(Input::all(), $customer_login_rules);
}
/**
* Validate password change method.
*
* @return object Validator
*/
public static function validate_changePassword()
{
$customer_cp_rules = array(
'customer_old_password'=>'<PASSWORD>',
'customer_new_password'=>'<PASSWORD>|Min:8|Same:customer_new_password_confirmation',
'customer_new_password_confirmation'=>'<PASSWORD>'
);
return Validator::make(Input::all(), $customer_cp_rules);
}
/**
* Validate customer creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_customer_rules = array(
'customer_type'=>'Required',
'customer_title'=>'Required',
'customer_firstName'=>'Required|Min:2',
'customer_lastName'=>'Required|Min:2',
'customer_idCardNumber'=>'Required|Min:6',
'customer_username'=>'Required|Min:6|Unique:customers,customer_username',
'customer_password'=>'<PASSWORD>|Min:8|Same:customer_password_confirmation',
'customer_password_confirmation'=>'<PASSWORD>',
'customer_phoneNumber'=>'Numeric',
'customer_mobileNumber'=>'Required|Numeric',
'customer_emailAddress'=>'Required|Min:6|Email|Unique:customers,customer_emailAddress',
'customer_addressLine1'=>'Required|Min:20',
'customer_countryId'=>'Required',
'customer_dateOfBirth'=>'Required'
);
$create_customer_messages = array(
'customer_emailAddress.unique' => 'Provided Email Address is already in use',
'customer_username.unique' => 'Provided Username is already in use'
);
return Validator::make(Input::all(), $create_customer_rules, $create_customer_messages);
}
/**
* Validate customer modification method.
*
* @return object Validator
*/
public static function validate_edit($customer_id)
{
$edit_customer_rules = array(
'customer_type'=>'Required',
'customer_title'=>'Required',
'customer_firstName'=>'Required|Min:2',
'customer_lastName'=>'Required|Min:2',
'customer_idCardNumber'=>'Required|Min:6',
'customer_username'=>'Required|Min:6|Unique:customers,customer_username,'.$customer_id.',customer_id',
'customer_phoneNumber'=>'Numeric|Min:8',
'customer_mobileNumber'=>'Required|Numeric|Min:8',
'customer_emailAddress'=>'Required|Min:6|Email|Unique:customers,customer_emailAddress,'.$customer_id.',customer_id',
'customer_addressLine1'=>'Required|Min:20',
'customer_countryId'=>'Required',
'customer_dateOfBirth'=>'Required'
);
$edit_customer_messages = array(
'customer_emailAddress.unique' => 'Provided Email Address is already in use',
'customer_username.unique' => 'Provided Username is already in use'
);
return Validator::make(Input::all(), $edit_customer_rules, $edit_customer_messages);
}
}<file_sep>/app/models/Offer.php
<?php
/* Offer Model Class */
class Offer extends Eloquent {
//Database table
protected $table = 'offers';
//Primary key of the offers table
protected $primaryKey = 'offer_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('offer_id','offer_value', 'offer_propertyId',
'offer_buyerId', 'offer_statusId', 'offer_isDeleted');
/**
* Get the status id depending on the status name.
*
* @return int
*/
public static function getStatusId($status_name)
{
$offer_status = DB::table('offer_statuses')
->where('offer_status_name', $status_name)
->lists('offer_status_id');
if($offer_status!=null)
{
foreach ($offer_status as $status) {
$offerstatus = Offer_Status::find($status);
$offerstatusId = $offerstatus->offer_status_id;
return $offerstatusId;
}
}
}
/**
* Get the awaiting approval status id.
*
* @return int
*/
public static function getAwaitingApprovalId()
{
return self::getStatusId('Awaiting Approval');
}
/**
* Get the accepted status id.
*
* @return int
*/
public static function getAcceptedId()
{
return self::getStatusId('Accepted');
}
/**
* Get the confirmed status id.
*
* @return int
*/
public static function getConfirmedId()
{
return self::getStatusId('Confirmed');
}
/**
* Get the rejected status id.
*
* @return int
*/
public static function getRejectedId()
{
return self::getStatusId('Rejected');
}
/**
* Get the cancelled status id.
*
* @return int
*/
public static function getCancelledId()
{
return self::getStatusId('Cancelled');
}
/**
* Validate offer creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_offer_rules = array(
'offer_value'=>'Required|Numeric',
'offer_propertyId'=>'Required',
'offer_buyerId'=>'Required',
'offer_statusId'=>'Required'
);
return Validator::make(Input::all(), $create_offer_rules);
}
/**
* Validate offer modification method.
*
* @return object Validator
*/
public static function validate_edit()
{
$edit_offer_rules = array(
'offer_value'=>'Required|Numeric',
'offer_propertyId'=>'Required',
'offer_buyerId'=>'Required',
'offer_statusId'=>'Required'
);
return Validator::make(Input::all(), $edit_offer_rules);
}
}<file_sep>/app/models/Location.php
<?php
/* Location Model Class */
class Location extends Eloquent {
//Database table
protected $table = 'locations';
//Primary key of the locations table
protected $primaryKey = 'location_id';
}<file_sep>/app/controllers/SearchController.php
<?php
//Official Website Search Controller Class
class SearchController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Redirect the user to the home page if he goes directly to the search results page.
*/
public function get_search(){
return Redirect::route('home')
->with('error-message', 'You must specify a search term!');
}
/**
* Show the official website's search results page.
*/
public function post_search(){
$searchterms = Input::get('searchterms');
if (empty($searchterms) || (strlen($searchterms) > 0 && strlen(trim($searchterms)) == 0)){
return Redirect::route('home')
->with('error-message', 'You must specify a search term!');
}
else{
$properties = Property::where('property_isActive', '=', '1')
->where( function ( $properties ) use ($searchterms)
{
$properties->where( 'property_name', 'LIKE', '%'.$searchterms.'%' )
->orWhere( 'property_description', 'LIKE', '%'.$searchterms.'%' );
})
->where('property_isDeleted', '=', '0')
->orderBy('property_name', 'asc')
->get();
$pages = Page::where('page_isPublished', '=', '1')
->where( function ( $pages ) use ($searchterms)
{
$pages->where( 'page_title', 'LIKE', '%'.$searchterms.'%' )
->orWhere( 'page_content', 'LIKE', '%'.$searchterms.'%' );
})
->where('page_isDeleted', '=', '0')
->orderBy('page_title', 'asc')
->get();
$this->layout->content = View::make('frontend.search.search-results')
->with('searchterms', $searchterms)
->with('properties',$properties)
->with('pages',$pages);
}
}
}
<file_sep>/app/database/migrations/2014_02_11_175604_create_offers_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOffersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('offers', function ($table) {
$table->increments('offer_id');
$table->decimal('offer_value', '10','2');
$table->unsignedInteger('offer_propertyId');
$table->foreign('offer_propertyId')
->references('property_id')->on('properties')
->onDelete('cascade')
->onUpdate('cascade');
$table->unsignedInteger('offer_buyerId');
$table->foreign('offer_buyerId')
->references('customer_id')->on('customers')
->onDelete('cascade')
->onUpdate('cascade');
$table->unsignedInteger('offer_statusId');
$table->foreign('offer_statusId')
->references('offer_status_id')->on('offer_statuses')
->onDelete('cascade')
->onUpdate('cascade');
$table->boolean('offer_isDeleted')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::drop('offers');
}
}<file_sep>/public/js/page-form-validator.js
//Page Validation Script
$(document).ready(function(){
$('#page-details').validate({
rules: {
page_title: {
minlength: 2,
required: true
},
page_content: {
minlength: 20,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.form-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('#page-details').on('submit', function () {
if ($('#page-details').valid()) {
$("#modify-page").fadeTo("fast", .5).removeAttr("href");
$("#modify-page").addClass("disabled_anchor");
}
});
$('#page-details').keypress(function(e){
if(e.which == 13){
return false;
}
});
$("#confirm-remove").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
$("#confirm-remove").addClass("disabled_anchor");
});
}); // end document.ready<file_sep>/app/database/migrations/2014_02_03_182219_add_locations.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddLocations extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('locations')->insert(array('location_name'=>'Attard'));
DB::table('locations')->insert(array('location_name'=>'Balzan'));
DB::table('locations')->insert(array('location_name'=>'Bidnija'));
DB::table('locations')->insert(array('location_name'=>'Birgu'));
DB::table('locations')->insert(array('location_name'=>'Birkirkara'));
DB::table('locations')->insert(array('location_name'=>'Birzebbuġia'));
DB::table('locations')->insert(array('location_name'=>'Bormla'));
DB::table('locations')->insert(array('location_name'=>'Dingli'));
DB::table('locations')->insert(array('location_name'=>'Fgura'));
DB::table('locations')->insert(array('location_name'=>'Fontana'));
DB::table('locations')->insert(array('location_name'=>'Furjana'));
DB::table('locations')->insert(array('location_name'=>'Għajnsielem'));
DB::table('locations')->insert(array('location_name'=>'Għarb'));
DB::table('locations')->insert(array('location_name'=>'Għargħur'));
DB::table('locations')->insert(array('location_name'=>'Għasri'));
DB::table('locations')->insert(array('location_name'=>'Għaxaq'));
DB::table('locations')->insert(array('location_name'=>'Gudja'));
DB::table('locations')->insert(array('location_name'=>'Gżira'));
DB::table('locations')->insert(array('location_name'=>'Ħamrun'));
DB::table('locations')->insert(array('location_name'=>'Iklin'));
DB::table('locations')->insert(array('location_name'=>'Kalkara'));
DB::table('locations')->insert(array('location_name'=>'Kerċem'));
DB::table('locations')->insert(array('location_name'=>'Kirkop'));
DB::table('locations')->insert(array('location_name'=>'Lija'));
DB::table('locations')->insert(array('location_name'=>'Luqa'));
DB::table('locations')->insert(array('location_name'=>'Marsa'));
DB::table('locations')->insert(array('location_name'=>'Marsalforn'));
DB::table('locations')->insert(array('location_name'=>'Marsaskala'));
DB::table('locations')->insert(array('location_name'=>'Marsaxlokk'));
DB::table('locations')->insert(array('location_name'=>'Mdina'));
DB::table('locations')->insert(array('location_name'=>'Mellieħa'));
DB::table('locations')->insert(array('location_name'=>'Mġarr'));
DB::table('locations')->insert(array('location_name'=>'Mosta'));
DB::table('locations')->insert(array('location_name'=>'Mqabba'));
DB::table('locations')->insert(array('location_name'=>'Msida'));
DB::table('locations')->insert(array('location_name'=>'Mtarfa'));
DB::table('locations')->insert(array('location_name'=>'Munxar'));
DB::table('locations')->insert(array('location_name'=>'Nadur'));
DB::table('locations')->insert(array('location_name'=>'Naxxar'));
DB::table('locations')->insert(array('location_name'=>'Paola'));
DB::table('locations')->insert(array('location_name'=>'Pembroke'));
DB::table('locations')->insert(array('location_name'=>'Pieta'));
DB::table('locations')->insert(array('location_name'=>'Qala'));
DB::table('locations')->insert(array('location_name'=>'Qormi'));
DB::table('locations')->insert(array('location_name'=>'Qrendi'));
DB::table('locations')->insert(array('location_name'=>'Rabat, Gozo'));
DB::table('locations')->insert(array('location_name'=>'Rabat, Malta'));
DB::table('locations')->insert(array('location_name'=>'Safi'));
DB::table('locations')->insert(array('location_name'=>'San Ġwann'));
DB::table('locations')->insert(array('location_name'=>'Santa Luċija'));
DB::table('locations')->insert(array('location_name'=>'Santa Venera'));
DB::table('locations')->insert(array('location_name'=>'Senglea'));
DB::table('locations')->insert(array('location_name'=>'Siġġiewi'));
DB::table('locations')->insert(array('location_name'=>'Sliema'));
DB::table('locations')->insert(array('location_name'=>'San Ġiljan'));
DB::table('locations')->insert(array('location_name'=>'San Lawrenz'));
DB::table('locations')->insert(array('location_name'=>'San Pawl il-Baħar'));
DB::table('locations')->insert(array('location_name'=>'Sannat'));
DB::table('locations')->insert(array('location_name'=>'Swieqi'));
DB::table('locations')->insert(array('location_name'=>'Tarxien'));
DB::table('locations')->insert(array('location_name'=>'Ta Xbiex'));
DB::table('locations')->insert(array('location_name'=>'Valletta'));
DB::table('locations')->insert(array('location_name'=>'Xgħajra'));
DB::table('locations')->insert(array('location_name'=>'Xagħra'));
DB::table('locations')->insert(array('location_name'=>'Xewkija'));
DB::table('locations')->insert(array('location_name'=>'Xlendi'));
DB::table('locations')->insert(array('location_name'=>'Żabbar'));
DB::table('locations')->insert(array('location_name'=>'Żebbuġ, Gozo'));
DB::table('locations')->insert(array('location_name'=>'Żebbuġ, Malta'));
DB::table('locations')->insert(array('location_name'=>'Żejtun'));
DB::table('locations')->insert(array('location_name'=>'Żurrieq'));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('locations')->delete();
}
}<file_sep>/app/database/migrations/2014_02_11_175420_add_offer_statuses.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddOfferStatuses extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('offer_statuses')->insert(array(
'offer_status_name'=>'Awaiting Approval',
'offer_status_description'=>'This offer is currently awaiting approval',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('offer_statuses')->insert(array(
'offer_status_name'=>'Accepted',
'offer_status_description'=>'This offer has been accepted by the vendor',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('offer_statuses')->insert(array(
'offer_status_name'=>'Confirmed',
'offer_status_description'=>'This offer has been confirmed by the buyer',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('offer_statuses')->insert(array(
'offer_status_name'=>'Rejected',
'offer_status_description'=>'This offer has been rejected by the vendor',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('offer_statuses')->insert(array(
'offer_status_name'=>'Cancelled',
'offer_status_description'=>'This offer has been cancelled by the buyer',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('offer_statuses')->delete();
}
}<file_sep>/app/models/Property_Status.php
<?php
/* Property Status Model Class */
class Property_Status extends Eloquent {
//Database table
protected $table = 'property_statuses';
//Primary key of the property_statuses table
protected $primaryKey = 'property_status_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('property_status_id','property_status_name', 'property_status_description');
/**
* Validate property status creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_property_status_rules = array(
'property_status_name'=>'Required|Min:2|Unique:property_statuses,property_status_name',
'property_status_description'=>'Required|Min:20'
);
$create_property_status_messages = array(
'property_status_name.unique' => 'Provided Property Status is already in use'
);
return Validator::make(Input::all(), $create_property_status_rules, $create_property_status_messages);
}
/**
* Validate property status modification method.
*
* @return object Validator
*/
public static function validate_edit($property_status_id)
{
$edit_property_status_rules = array(
'property_status_name'=>'Required|Min:2|Unique:property_statuses,property_status_name,'.$property_status_id.',property_status_id',
'property_status_description'=>'Required|Min:20'
);
$edit_property_status_messages = array(
'property_status_name.unique' => 'Provided Property Status is already in use'
);
return Validator::make(Input::all(), $edit_property_status_rules, $edit_property_status_messages);
}
}<file_sep>/app/models/Property_Type.php
<?php
/* Property Type Model Class */
class Property_Type extends Eloquent {
//Database table
protected $table = 'property_types';
//Primary key of the property_types table
protected $primaryKey = 'property_type_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('property_type_id','property_type_name', 'property_type_description');
/**
* Validate property type creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_property_type_rules = array(
'property_type_name'=>'Required|Min:2|Unique:property_types,property_type_name',
'property_type_description'=>'Required|Min:20'
);
$create_property_type_messages = array(
'property_type_name.unique' => 'Provided Property Type is already in use'
);
return Validator::make(Input::all(), $create_property_type_rules, $create_property_type_messages);
}
/**
* Validate property type modification method.
*
* @return object Validator
*/
public static function validate_edit($property_type_id)
{
$edit_property_type_rules = array(
'property_type_name'=>'Required|Min:2|Unique:property_types,property_type_name,'.$property_type_id.',property_type_id',
'property_type_description'=>'Required|Min:20'
);
$edit_property_type_messages = array(
'property_type_name.unique' => 'Provided Property Type is already in use'
);
return Validator::make(Input::all(), $edit_property_type_rules, $edit_property_type_messages);
}
}<file_sep>/app/controllers/FrontEndPagesController.php
<?php
//Official Website Page Controller Class
class FrontEndPagesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Show the official website's page view.
*/
public function get_view($page_id){
$page = Page::find($page_id);
if ($page != null) {
if($page->page_isPublished == '1')
$this->layout->content = View::make('frontend.pages.view')
->with('page', $page);
else
return Redirect::route('home')
->with('error-message', 'Requested Page was not found');
}
else {
return Redirect::route('home')
->with('error-message', 'Requested Page was not found');
}
}
/**
* Show the official website's about us page.
*/
public function get_aboutus(){
$aboutus = DB::table('pages')
->where('page_title', '=', 'About Us')
->where('page_isPublished', '=', '1')
->where('page_isDeleted', '=', '0')->get();
if($aboutus!=null)
{
$page = null;
foreach ($aboutus as $aboutuspage) {
$page = Page::find($aboutuspage->page_id);
}
$this->layout->content = View::make('frontend.pages.view')
->with('page', $page);
}
else
return Redirect::route('home')
->with('error-message', 'Requested Page was not found');
}
}<file_sep>/app/controllers/FrontEndCustomersController.php
<?php
//Official Website Customer Controller Class
class FrontEndCustomersController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.frontend";
/**
* Show the official website's login page.
*/
public function get_login(){
if (!Auth::guest())
return Redirect::to('/')->with('message', 'You are already logged in!');
else
$this->layout->content = View::make('frontend.customers.login');
}
/**
* Validate and login the customer.
*/
public function post_signedin(){
$customerdata = array(
'customer_emailAddress' => Input::get('customer_emailAddress'),
'password' => Input::get('<PASSWORD>')
);
$validation = Customer::validate_login();
if($validation->fails()) {
return Redirect::back()
->withErrors($validation)
->withInput();
}
else{
if (Auth::attempt($customerdata)) {
$session_customer_id = Auth::user()->customer_id;
return Redirect::to('/')->with('message', 'You are now logged in!');
} else {
return Redirect::route('customerlogin')
->with('error-message', 'Your email address/password combination was incorrect. Please try again.')
->withInput();
}
}
}
/**
* Logout the customer and show the official website's logout page.
*/
public function get_logout()
{
Auth::logout();
return Redirect::route('home')->with('message', 'You are now logged out!');
}
/**
* Show the official website's customer profile page.
*/
public function get_view(){
if (Auth::check()){
$customer_id = Auth::user()->customer_id;
$customer_countryId = Customer::find($customer_id)->customer_countryId;
$customer_countryName = Country::find($customer_countryId)->country_name;
$customer_addressLine2 = Customer::find($customer_id)->customer_addressLine2;
if($customer_addressLine2=="")
$customer_addressLine2 = 'N/A';
$customer_phoneNumber = Customer::find($customer_id)->customer_phoneNumber;
if($customer_phoneNumber=="")
$customer_phoneNumber = 'N/A';
$this->layout->content = View::make('frontend.customers.view')
->with('title', 'Customer View Page')
->with('customer', Customer::find($customer_id))
->with('customer_country', $customer_countryName)
->with('customer_addressLine2', $customer_addressLine2)
->with('customer_phoneNumber', $customer_phoneNumber);
}
}
/**
* Show the official website's customer registration page.
*/
public function get_new(){
$customer_types = array('' => 'Select One','Buyer'=>'Buyer','Vendor'=>'Vendor');
$countries = array('' => 'Select One') +
Country::lists('country_name', 'country_id');
$titles = array('' => 'Select One','Mr.'=>'Mr.','Mrs.'=>'Mrs.','Ms.'=>'Ms.','Miss'=>'Miss','Master'=>'Master',
'Rev.'=>'Rev. (Reverend)','Fr.'=>'Fr. (Father)','Dr.'=>'Dr. (Doctor)','Atty.'=>'Atty. (Attorney)',
'Prof.'=>'Prof. (Professor)','Hon.'=>'Hon. (Honorable)','Pres.'=>'Pres. (President)',
'Gov.'=>'Gov. (Governor)','Coach'=>'Coach','Ofc.'=>'Ofc. (Officer)');
$this->layout->content = View::make('frontend.customers.new')
->with('title', 'Register Customer')
->with('customer_type',$customer_types)
->with('customer_countryId', $countries)
->with('customer_title', $titles);
}
/**
* Validate, create and login the customer and send the customer registration email.
*/
public function post_create(){
$dob = str_replace("/", "-", Input::get('customer_dateOfBirth'));
$date_dob = new DateTime($dob);
$formatted_dob = date_format($date_dob, 'Y-m-d H:i:s');
$now = new DateTime();
$validation = Customer::validate_create();
if($validation->fails()) {
return Redirect::route('newcustomer')
->withErrors($validation)
->withInput();
}
else {
$customer_title = Input::get('customer_title');
$customer_firstName = Input::get('customer_firstName');
$customer_lastName = Input::get('customer_lastName');
$customer_emailAddress = Input::get('customer_emailAddress');
$customer_username = Input::get('customer_username');
$customer_password = Input::get('customer_password');
$customer_type = Input::get('customer_type');
$customer_idCardNumber = Input::get('customer_idCardNumber');
$customer_dateOfBirth = Input::get('customer_dateOfBirth');
$customer_addressLine1 = Input::get('customer_addressLine1');
$customer_addressLine2 = Input::get('customer_addressLine2');
$customer_countryId = Input::get('customer_countryId');
$customer_countryName = Country::find($customer_countryId)->country_name;
$customer_phoneNumber = Input::get('customer_phoneNumber');
$customer_mobileNumber = Input::get('customer_mobileNumber');
$data = array(
'customer_title'=>$customer_title,
'customer_firstName'=>$customer_firstName,
'customer_lastName'=>$customer_lastName,
'customer_emailAddress'=>$customer_emailAddress,
'customer_username'=>$customer_username,
'customer_password'=><PASSWORD>($<PASSWORD>),
'customer_type'=>$customer_type,
'customer_idCardNumber'=>$customer_idCardNumber,
'customer_dateOfBirth'=>$formatted_dob,
'customer_addressLine1'=>$customer_addressLine1,
'customer_addressLine2'=>$customer_addressLine2,
'customer_countryId'=>$customer_countryId,
'customer_phoneNumber'=>$customer_phoneNumber,
'customer_mobileNumber'=>$customer_mobileNumber,
'customer_isActive'=>'1',
'customer_isDeleted'=>'0'
);
Customer::create($data);
$emaildata = array(
'customer_title'=>$customer_title,
'customer_firstName'=>$customer_firstName,
'customer_lastName'=>$customer_lastName,
'customer_emailAddress'=>$customer_emailAddress,
'customer_username'=>$customer_username,
'customer_password'=>$customer_<PASSWORD>,
'customer_type'=>$customer_type,
'customer_idCardNumber'=>$customer_idCardNumber,
'customer_dateOfBirth'=>$customer_dateOfBirth,
'customer_addressLine1'=>$customer_addressLine1,
'customer_addressLine2'=>$customer_addressLine2,
'customer_countryName'=>$customer_countryName,
'customer_phoneNumber'=>$customer_phoneNumber,
'customer_mobileNumber'=>$customer_mobileNumber
);
Mail::send('frontend.customers.mails.welcome', $emaildata, function($message) use ($customer_title,
$customer_firstName, $customer_lastName, $customer_emailAddress, $customer_username,
$customer_password, $customer_type, $customer_idCardNumber, $customer_dateOfBirth,
$customer_addressLine1, $customer_addressLine2, $customer_countryName, $customer_phoneNumber,
$customer_mobileNumber){
$message->to($customer_emailAddress, $customer_firstName.' '.$customer_lastName)
->subject('Your Registration with Best Property Malta');
});
$customerdata = array(
'customer_emailAddress' => Input::get('customer_emailAddress'),
'password' => Input::get('customer_password')
);
if (Auth::attempt($customerdata)) {
$session_customer_id = Auth::user()->customer_id;
return Redirect::route('customer_profile')
->with('message', 'You have successfully registered!');
}
}
}
/**
* Show the official website's customer modification page.
*/
public function get_edit(){
if (Auth::check()){
$customer_id = Auth::user()->customer_id;
$customer_types = array('' => 'Select One','Buyer'=>'Buyer','Vendor'=>'Vendor');
$countries = array('' => 'Select One') +
Country::lists('country_name', 'country_id');
$titles = array('' => 'Select One','Mr.'=>'Mr.','Mrs.'=>'Mrs.','Ms.'=>'Ms.','Miss'=>'Miss','Master'=>'Master',
'Rev.'=>'Rev. (Reverend)','Fr.'=>'Fr. (Father)','Dr.'=>'Dr. (Doctor)','Atty.'=>'Atty. (Attorney)',
'Prof.'=>'Prof. (Professor)','Hon.'=>'Hon. (Honorable)','Pres.'=>'Pres. (President)',
'Gov.'=>'Gov. (Governor)','Coach'=>'Coach','Ofc.'=>'Ofc. (Officer)');
$this->layout->content = View::make('frontend.customers.edit')
->with('title', 'Edit Customer')
->with('customer', Customer::find($customer_id))
->with('customer_type',$customer_types)
->with('customer_countryId', $countries)
->with('customer_title', $titles);
}
}
/**
* Validate and update the customer.
*/
public function put_update(){
$customer_id = Input::get('customer_id');
$dob = str_replace("/", "-", Input::get('customer_dateOfBirth'));
$formatted_dob = date_format(new DateTime($dob), 'Y-m-d H:i:s');
$now = new DateTime();
$validation = Customer::validate_edit($customer_id);
if($validation->fails()) {
return Redirect::route('edit_customer_profile')
->withErrors($validation);
}
else {
Customer::find($customer_id)->update(array(
'customer_title'=>Input::get('customer_title'),
'customer_firstName'=>Input::get('customer_firstName'),
'customer_lastName'=>Input::get('customer_lastName'),
'customer_emailAddress'=>Input::get('customer_emailAddress'),
'customer_username'=>Input::get('customer_username'),
'customer_type'=>Input::get('customer_type'),
'customer_idCardNumber'=>Input::get('customer_idCardNumber'),
'customer_dateOfBirth'=>$formatted_dob,
'customer_addressLine1'=>Input::get('customer_addressLine1'),
'customer_addressLine2'=>Input::get('customer_addressLine2'),
'customer_countryId'=>Input::get('customer_countryId'),
'customer_phoneNumber'=>Input::get('customer_phoneNumber'),
'customer_mobileNumber'=>Input::get('customer_mobileNumber'),
'customer_isActive'=>'1',
'customer_isDeleted'=>'0'
));
return Redirect::route('customer_profile')
->with('message', 'The customer was updated successfully!');
}
}
/**
* Show the official website's customer password modification page.
*/
public function get_changepassword(){
if (Auth::check()){
$customer_id = Auth::user()->customer_id;
$this->layout->content = View::make('frontend.customers.changepassword')
->with('title', 'Change Password')
->with('customer', Customer::find($customer_id));
}
}
/**
* Validate and update the customer password.
*/
public function put_updatepassword(){
$customer_id = Input::get('customer_id');
$customer = Customer::find($customer_id);
$validation = Customer::validate_changepassword();
if($validation->fails()) {
return Redirect::back()
->withErrors($validation);
}
else {
if (Hash::check(Input::get('customer_old_password'), $customer->customer_password)) {
Customer::find($customer_id)->update(array(
'customer_password'=><PASSWORD>::make(Input::get('customer_new_password')),
));
return Redirect::route('customer_profile')
->with('message', 'The password was updated successfully!');
}
else {
return Redirect::route('change_customer_profile_password')
->with('error-message', 'The old password inputted is not correct!');
}
}
}
}<file_sep>/app/models/Staff.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
/* Staff Model Class */
class Staff extends Eloquent implements UserInterface, RemindableInterface {
//Database table
protected $table = 'staff';
//Primary key of the staff table
protected $primaryKey = 'staff_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('staff_id','staff_roleId', 'staff_title', 'staff_firstName',
'staff_lastName', 'staff_idCardNumber', 'staff_username', 'staff_password', 'staff_phoneNumber',
'staff_mobileNumber', 'staff_emailAddress', 'staff_addressLine1', 'staff_addressLine2',
'staff_countryId', 'staff_dateOfBirth', 'staff_employmentDate','staff_isActive', 'staff_isDeleted');
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('staff_password');
protected $guarded = array('staff_id', 'staff_password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->staff_password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->staff_emailAddress;
}
/**
* Get the id of the staff member.
*
* @return int
*/
public function getStaffId()
{
return $this->staff_id;
}
/**
* Get the staff member's full name.
*
* @return string
*/
public function getName()
{
return $this->staff_firstName. ' ' . $this->staff_lastName;
}
/**
* Get the staff member's first name.
*
* @return string
*/
public function getFirstName()
{
return $this->staff_firstName;
}
/**
* Get the staff member's role.
*
* @return string
*/
public function getRole()
{
return Staff_Role::find($this->staff_roleId)->staff_role_name;
}
/**
* Validate login method.
*
* @return object Validator
*/
public static function validate_login()
{
$staff_login_rules = array(
'staff_emailAddress'=>'Required|Min:6|Email',
'staff_password'=>'<PASSWORD>'
);
return Validator::make(Input::all(), $staff_login_rules);
}
/**
* Validate password change method.
*
* @return object Validator
*/
public static function validate_changePassword()
{
$staff_cp_rules = array(
'staff_old_password'=>'<PASSWORD>',
'staff_new_password'=>'<PASSWORD>:<PASSWORD>',
'staff_new_password_confirmation'=>'<PASSWORD>'
);
return Validator::make(Input::all(), $staff_cp_rules);
}
/**
* Validate staff member creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_staff_rules = array(
'staff_roleId'=>'Required',
'staff_title'=>'Required',
'staff_firstName'=>'Required|Min:2',
'staff_lastName'=>'Required|Min:2',
'staff_idCardNumber'=>'Required|Min:6',
'staff_username'=>'Required|Min:6|Unique:staff,staff_username',
'staff_password'=>'<PASSWORD>|Same:<PASSWORD>',
'staff_password_confirmation'=>'<PASSWORD>',
'staff_phoneNumber'=>'Numeric',
'staff_mobileNumber'=>'Required|Numeric',
'staff_emailAddress'=>'Required|Min:6|Email|Unique:staff,staff_emailAddress',
'staff_addressLine1'=>'Required|Min:20',
'staff_countryId'=>'Required',
'staff_dateOfBirth'=>'Required',
'staff_employmentDate'=>'Required'
);
$create_staff_messages = array(
'staff_emailAddress.unique' => 'Provided Email Address is already in use',
'staff_username.unique' => 'Provided Username is already in use'
);
return Validator::make(Input::all(), $create_staff_rules, $create_staff_messages);
}
/**
* Validate staff member modification method.
*
* @return object Validator
*/
public static function validate_edit($staff_id)
{
$edit_staff_rules = array(
'staff_roleId'=>'Required',
'staff_title'=>'Required',
'staff_firstName'=>'Required|Min:2',
'staff_lastName'=>'Required|Min:2',
'staff_idCardNumber'=>'Required|Min:6',
'staff_username'=>'Required|Min:6|Unique:staff,staff_username,'.$staff_id.',staff_id',
'staff_phoneNumber'=>'Numeric|Min:8',
'staff_mobileNumber'=>'Required|Numeric|Min:8',
'staff_emailAddress'=>'Required|Min:6|Email|Unique:staff,staff_emailAddress,'.$staff_id.',staff_id',
'staff_addressLine1'=>'Required|Min:20',
'staff_countryId'=>'Required',
'staff_dateOfBirth'=>'Required',
'staff_employmentDate'=>'Required',
);
$edit_staff_messages = array(
'staff_emailAddress.unique' => 'Provided Email Address is already in use',
'staff_username.unique' => 'Provided Username is already in use'
);
return Validator::make(Input::all(), $edit_staff_rules, $edit_staff_messages);
}
}<file_sep>/app/models/Page.php
<?php
/* Page Model Class */
class Page extends Eloquent {
//Database table
protected $table = 'pages';
//Primary key of the pages table
protected $primaryKey = 'page_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('page_id','page_title', 'page_content', 'page_isPublished', 'page_isDeleted');
/**
* Validate page creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_page_rules = array(
'page_title'=>'Required|Min:2|Unique:pages,page_title',
'page_content'=>'Required|Min:20'
);
$create_page_messages = array(
'page_title.unique' => 'Provided Page Title is already in use'
);
return Validator::make(Input::all(), $create_page_rules, $create_page_messages);
}
/**
* Validate page modification method.
*
* @return object Validator
*/
public static function validate_edit($page_id)
{
$edit_page_rules = array(
'page_title'=>'Required|Min:2|Unique:pages,page_title,'.$page_id.',page_id',
'page_content'=>'Required|Min:20'
);
$edit_page_messages = array(
'page_title.unique' => 'Provided Page Title is already in use'
);
return Validator::make(Input::all(), $edit_page_rules, $edit_page_messages);
}
}<file_sep>/app/database/migrations/2014_02_04_175320_add_staff_roles.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddStaffRoles extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('staff_roles')->insert(array(
'staff_role_name'=>'Administrator',
'staff_role_description'=>'This is an administrator.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('staff_roles')->insert(array(
'staff_role_name'=>'Estate Agent',
'staff_role_description'=>'This is an estate agent.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('staff_roles')->insert(array(
'staff_role_name'=>'Content Editor',
'staff_role_description'=>'This is a content editor.',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('staff_roles')->delete();
}
}<file_sep>/app/controllers/PropertyStatusesController.php
<?php
//IMS Property Status Controller Class
class PropertyStatusesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS's property status index page.
*/
public function get_index(){
$allpropertystatuses = DB::table('property_statuses')->orderBy('property_status_name')->paginate(10);
$this->layout->content = View::make('property_statuses.index')
->with('title', 'List of Property Statuses')
->with('property_statuses', $allpropertystatuses);
}
/**
* Show the IMS's property status details page.
*/
public function get_view($property_status_id){
if (Property_Status::find($property_status_id) != null) {
$property_statusId = Property_Status::find($property_status_id);
$this->layout->content = View::make('property_statuses.view')
->with('title', 'Property Status View Page')
->with('property_status', Property_Status::find($property_status_id));
}
else
return Redirect::route('property_statuses')
->with('error-message', 'Requested Property Status was not found');
}
/**
* Show the IMS's property status creation page.
*/
public function get_new(){
$property_status = array('' => 'Select One') +
Property_Status::lists('property_status_name', 'property_status_id');
$this->layout->content = View::make('property_statuses.new')
->with('title', 'Add New Property Status')
->with('property_statusId',$property_status);
}
/**
* Validate and create the property status.
*/
public function post_create(){
$validation = Property_Status::validate_create();
if($validation->fails()) {
return Redirect::route('new_property_status')
->withErrors($validation)
->withInput();
}
else {
Property_Status::create(array(
'property_status_name'=>Input::get('property_status_name'),
'property_status_description'=>Input::get('property_status_description')
));
return Redirect::route('property_statuses')
->with('message', 'The property status was created successfully!');
}
}
/**
* Show the IMS's property status modification page.
*/
public function get_edit($property_status_id){
if(Property_Status::find($property_status_id)!=null){
$this->layout->content = View::make('property_statuses.edit')
->with('title', 'Edit Property Status')
->with('property_status', Property_Status::find($property_status_id));
}
else{
return Redirect::route('property_statuses')
->with('error-message', 'Requested Property Status was not found');
}
}
/**
* Validate and edit the property status.
*/
public function put_update(){
$property_status_id = Input::get('property_status_id');
$validation = Property_Status::validate_edit($property_status_id);
if($validation->fails()) {
return Redirect::route('edit_property_status', $property_status_id)
->withErrors($validation);
}
else {
Property_Status::find($property_status_id)->update(array(
'property_status_name'=>Input::get('property_status_name'),
'property_status_description'=>Input::get('property_status_description')
));
return Redirect::route('property_status', $property_status_id)
->with('message', 'The property status was updated successfully!');
}
}
/**
* Show the IMS's property status deletion page.
*/
public function get_destroy($property_statusId){
$this->layout->content = View::make('property_statuses.confirm-delete')
->with('title', 'Confirm Property Status Deletion')
->with('property_status', Property_Status::find($property_statusId));
}
/**
* Delete the property status.
*/
public function delete_destroy(){
Property_Status::find(Input::get('property_status_id'))->delete();
return Redirect::route('property_statuses')
->with('message', 'The property status was deleted successfully!');
}
}<file_sep>/app/controllers/ImsController.php
<?php
//IMS Controller Class
class ImsController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.imslayout";
/**
* Show the IMS home page.
*/
public function get_home(){
if(Auth::check()){
if(Auth::user()->getRole()=="Content Editor"){
return Redirect::route('cmshome')
->with('error-message', 'Restricted Access!');
}
else
$this->layout->content = View::make('home.imshome');
}
else
return Redirect::route('imslogin')
->with('error-message', 'Please login!');
}
}<file_sep>/app/database/migrations/2014_02_04_182124_add_properties.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddProperties extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('properties')->insert(array(
'property_typeId'=>'1',
'property_statusId'=>'1',
'property_vendorId'=>'1',
'property_name'=>'<NAME>',
'property_description'=>'Located in the most sought after area of Fontana, this ground floor maisonette comprises naturally bright living/dining, separate kitchen, 2 double and one single bedrooms, main bathroom, en-suite and internal yard. A/Cs are installed, optional garage.',
'property_locationId'=>'10',
'property_squareMetres'=>'75.8',
'property_bathrooms'=>'1',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'350000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'2',
'property_statusId'=>'1',
'property_vendorId'=>'2',
'property_name'=>'<NAME>',
'property_description'=>'Highly finished bright three bedroom maisonette forming part of a smart block. Located in a peaceful area, measuring approx 160sqm. Consists of an entrance hall, a combined sitting / dining room, kitchen area,leading to a good sized balcony where one can relax and enjoy tranquility, 3 double bedrooms, 2 bathrooms, one of which is ensuite, box room and laundry room. No parking problem. Worth viewing!',
'property_locationId'=>'7',
'property_squareMetres'=>'160',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'0',
'property_price'=>'920000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'3',
'property_statusId'=>'1',
'property_vendorId'=>'5',
'property_name'=>'Treetops',
'property_description'=>'Large 2 bedroomed villa situated infront of a valley in the heart of Ghajnsielem. Comprises of a large terrace enjoying side sea views leading onto the kitchen/living/dining, 2 bedrooms, 2 bathrooms and an extra room.',
'property_locationId'=>'12',
'property_squareMetres'=>'100.2',
'property_bathrooms'=>'2',
'property_bedrooms'=>'2',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'209000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'4',
'property_statusId'=>'1',
'property_vendorId'=>'1',
'property_name'=>'Hillcrest',
'property_description'=>'Country views, 3 bedroomed penthouse, combined kitchen / dining, bathroom and a good size back terrace. Worth Viewing.',
'property_locationId'=>'20',
'property_squareMetres'=>'95.08',
'property_bathrooms'=>'1',
'property_bedrooms'=>'3',
'property_hasGarage'=>'0',
'property_hasGarden'=>'1',
'property_price'=>'520000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'5',
'property_statusId'=>'1',
'property_vendorId'=>'2',
'property_name'=>'Sunnyside',
'property_description'=>'Located in one of the most desirable areas of Birgu, this is a 3 bedroom luxury finished house of character in a small block . Accommodation comprises an entrance hall, spacious open plan kitchen/living/dining leading to a good size terrace, 2 bathrooms (1 en-suite shower) laundry room, box room/storage and back yard. Optional interconnecting underlying garages available.',
'property_locationId'=>'4',
'property_squareMetres'=>'85.5',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'634000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'6',
'property_statusId'=>'1',
'property_vendorId'=>'5',
'property_name'=>'Woodside',
'property_description'=>'Very nicely converted town house with old features such as xorok, kileb and wooden beams.It comprises three bedrooms, 2 bathrooms, living, study, laundry room, internal and central courtyard, kitchen/dinning, and a cellar.',
'property_locationId'=>'20',
'property_squareMetres'=>'112.3',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'340000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'7',
'property_statusId'=>'1',
'property_vendorId'=>'1',
'property_name'=>'Primrose',
'property_description'=>'Second floor brand new bungalow measuring 98 square mtrs being sold semi-finished comprising kitchen/living/dining, 3 bedrooms, 2 bathrooms, utility room and a 2 balconies. Optional car garage.',
'property_locationId'=>'1',
'property_squareMetres'=>'98',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'840000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'1',
'property_statusId'=>'1',
'property_vendorId'=>'2',
'property_name'=>'Blossoms',
'property_description'=>'3 bedroomed maisonette, comprising kitchen/living/dining, 2 bathrooms, washroom, 2 terraces with the views.',
'property_locationId'=>'10',
'property_squareMetres'=>'95.5',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'0',
'property_hasGarden'=>'0',
'property_price'=>'910000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'2',
'property_statusId'=>'1',
'property_vendorId'=>'5',
'property_name'=>'Springfield',
'property_description'=>'First floor semi finished flat, consisting of open plan kitchen living dining,three bedroom, bathroom, shower, front and back balconies,served with lift. Worth viewing!',
'property_locationId'=>'10',
'property_squareMetres'=>'75.1',
'property_bathrooms'=>'1',
'property_bedrooms'=>'3',
'property_hasGarage'=>'0',
'property_hasGarden'=>'1',
'property_price'=>'110000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'3',
'property_statusId'=>'1',
'property_vendorId'=>'1',
'property_name'=>'The Orchard',
'property_description'=>'A beautiful villa comprising of an open plan area for a kitchen, living and dining, ground floor bedroom (or could be converted into a garage), pool and deck area, 2 common bathrooms, 3 bedrooms, laundry room, 2 balconies and a large roof terrace. There is also 1 car space included.',
'property_locationId'=>'6',
'property_squareMetres'=>'109.4',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'0',
'property_price'=>'1200000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'5',
'property_statusId'=>'1',
'property_vendorId'=>'2',
'property_name'=>'The Haven',
'property_description'=>'This huge unconverted House of Character excellently located in a prime area with wonderful country views boasts itself with traditional character. Property needs minimal expenses to convert into a premium residence with 4 bedrooms, 2 bathrooms, large kitchen, living and dining overlooking a spacious outside area, large pool and gardens. A big first floor terrace enjoys breathtaking views of Maltese landscape and distant seaviews. A rare opportunity.',
'property_locationId'=>'17',
'property_squareMetres'=>'165.9',
'property_bathrooms'=>'2',
'property_bedrooms'=>'4',
'property_hasGarage'=>'0',
'property_hasGarden'=>'1',
'property_price'=>'630000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'1',
'property_statusId'=>'1',
'property_vendorId'=>'5',
'property_name'=>'Evergreen',
'property_description'=>'A spacious corner elevated ground floor maisonette. Property comprises of an open plan kitchen /dining area leading onto an internal yard with a garden , large living room, 3 bedrooms and 2 bathrooms. This property also includes an interconnecting one car lock-up garage with a storage room.',
'property_locationId'=>'11',
'property_squareMetres'=>'85.3',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'0',
'property_hasGarden'=>'1',
'property_price'=>'340000',
'property_isActive'=>'1',
'property_isDeleted'=>'1',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'6',
'property_statusId'=>'1',
'property_vendorId'=>'1',
'property_name'=>'Wayside',
'property_description'=>'A luxuriously finished, 175 sq. metre town house forming part of a sophisticated residential complex. This property comprises of a large open plan kitchen / living area, 3 double bedrooms and 2 bathrooms.',
'property_locationId'=>'11',
'property_squareMetres'=>'175',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'720000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'7',
'property_statusId'=>'1',
'property_vendorId'=>'2',
'property_name'=>'<NAME>',
'property_description'=>'This semi converted bungalow consists of a living and study area, guest toilet facilities, courtyard, dining area, and kitchen. The second floor consists of 2 bedrooms, bathroom and washroom. Full roof and a good sized basement. Worth viewing.',
'property_locationId'=>'10',
'property_squareMetres'=>'75.9',
'property_bathrooms'=>'1',
'property_bedrooms'=>'2',
'property_hasGarage'=>'0',
'property_hasGarden'=>'1',
'property_price'=>'520000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'1',
'property_statusId'=>'1',
'property_vendorId'=>'5',
'property_name'=>'Fairview',
'property_description'=>'Luxury finished first floor maisonette with a block of only two in a very quiet area. This property comprises of a seperate kitchen dining, large sitting room, three bedrooms, bathroom, back terrace, washroom and half roof. Must be seen.',
'property_locationId'=>'16',
'property_squareMetres'=>'85.2',
'property_bathrooms'=>'1',
'property_bedrooms'=>'3',
'property_hasGarage'=>'0',
'property_hasGarden'=>'1',
'property_price'=>'1100000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'2',
'property_statusId'=>'1',
'property_vendorId'=>'1',
'property_name'=>'Oaklands',
'property_description'=>'Luxury finished elevated ground floor flat in a quiet area. This property comprises of a large kitchen dining open plan, three bedrooms, two bathrooms, and two yards. Sold furnished and has a two car optional garage.',
'property_locationId'=>'7',
'property_squareMetres'=>'99.8',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'1405000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'1',
'property_statusId'=>'1',
'property_vendorId'=>'2',
'property_name'=>'Greenacres',
'property_description'=>'This is a ground floor maisonette location in a prime area comprising of three bedrooms, bathroom, kitchen dining, boxroom internral yard and backyard. Must be seen.',
'property_locationId'=>'10',
'property_squareMetres'=>'75.6',
'property_bathrooms'=>'1',
'property_bedrooms'=>'3',
'property_hasGarage'=>'0',
'property_hasGarden'=>'1',
'property_price'=>'450000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'4',
'property_statusId'=>'1',
'property_vendorId'=>'5',
'property_name'=>'Downtown',
'property_description'=>'This penthouse consists of 2 bedrooms, main bathroom and an open space for a kitchen living and dining with a front balcony. Garage also included.',
'property_locationId'=>'16',
'property_squareMetres'=>'71.8',
'property_bathrooms'=>'1',
'property_bedrooms'=>'2',
'property_hasGarage'=>'1',
'property_hasGarden'=>'0',
'property_price'=>'750000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'5',
'property_statusId'=>'1',
'property_vendorId'=>'1',
'property_name'=>'Sands of Time',
'property_description'=>'This highly finished, 3 bedroom first floor house of character enjoys all the tranquility and countryside views that only Gzira can offer. Property further consists of a large and spacious kitchen, living and dining, main bathroom, en suite bathroom, utility room, and a large wide balcony overlooking the countryside. Garages available.',
'property_locationId'=>'18',
'property_squareMetres'=>'80.8',
'property_bathrooms'=>'2',
'property_bedrooms'=>'3',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'820000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('properties')->insert(array(
'property_typeId'=>'6',
'property_statusId'=>'1',
'property_vendorId'=>'2',
'property_name'=>'Woodlands',
'property_description'=>'Highly furnished town house and 10 minutes away from the seafront. Comprises of open plan kitchen/living/dining, main bedroom, bathroom, boxroom and front balcony overlooking green area. Ready to move in. Good investment!',
'property_locationId'=>'10',
'property_squareMetres'=>'87.8',
'property_bathrooms'=>'1',
'property_bedrooms'=>'1',
'property_hasGarage'=>'1',
'property_hasGarden'=>'1',
'property_price'=>'210000',
'property_isActive'=>'1',
'property_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('properties')->delete();
}
}<file_sep>/public/js/contactus-form-validator.js
//Staff Validation Script
$(document).ready(function(){
$('#contactus-details').validate({
rules: {
customer_title: {
required: true
},
customer_firstName: {
minlength: 2,
required: true
},
customer_lastName: {
minlength: 2,
required: true
},
customer_emailAddress: {
minlength: 6,
required: true,
email: true
},
contactus_query: {
minlength: 20,
required: true
},
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('#contactus-details').on('submit', function () {
if ($('#contactus-details').valid()) {
$("#query").fadeTo("fast", .5).removeAttr("href");
$("#query").addClass("disabled_anchor");
}
});
$('#contactus-details').keypress(function(e){
if(e.which == 13){
return false;
}
});
}); // end document.ready<file_sep>/app/models/Country.php
<?php
/* Country Model Class */
class Country extends Eloquent {
//Database table
protected $table = 'countries';
//Primary key of the countries table
protected $primaryKey = 'country_id';
}<file_sep>/app/database/migrations/2014_02_04_174727_create_staff_table.php
<?php
use Illuminate\Database\Migrations\Migration;
class CreateStaffTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('staff', function($table){
$table->increments('staff_id');
$table->string('staff_title');
$table->string('staff_firstName');
$table->string('staff_lastName');
$table->string('staff_emailAddress');
$table->string('staff_username');
$table->string('staff_password');
$table->unsignedInteger('staff_roleId');
$table->foreign('staff_roleId')
->references('staff_role_id')->on('staff_roles')
->onDelete('cascade')
->onUpdate('cascade');
$table->dateTime('staff_employmentDate');
$table->string('staff_idCardNumber');
$table->dateTime('staff_dateOfBirth');
$table->string('staff_addressLine1');
$table->string('staff_addressLine2')->nullable();
$table->unsignedInteger('staff_countryId');
$table->foreign('staff_countryId')
->references('country_id')->on('countries')
->onDelete('cascade')
->onUpdate('cascade');
$table->string('staff_phoneNumber')->nullable();
$table->string('staff_mobileNumber');
$table->tinyInteger('staff_isActive');
$table->tinyInteger('staff_isDeleted');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('staff');
}
}<file_sep>/app/controllers/ImagesController.php
<?php
//CMS Property Image Controller Class
class ImagesController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.cmslayout";
/**
* Show the CMS's property image index page.
*/
public function get_mainindex(){
$property_name = array('' => 'Select One') +
Property::where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->orderBy('property_id')->get()->lists('full_name', 'property_id');
$this->layout->content = View::make('images.index')
->with('title', 'List of Property Images')
->with('isMain', '1')
->with('images', Image::orderBy('created_at', 'desc')
->paginate('42'))
->with('propertyName', $property_name);
}
/**
* Show the CMS's property image index page filtered by property.
*/
public function get_propertyindex($propertyId){
$property_name = array('' => 'Select One') +
Property::where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->orderBy('property_id')->get()->lists('full_name', 'property_id');
$this->layout->content = View::make('images.index')
->with('title', 'Property Images')
->with('isMain', '0')
->with('propertyName', $property_name)
->with('images', Image::orderBy('created_at', 'desc')
->where('image_propertyId', $propertyId)
->paginate('42'));
}
/**
* Show the CMS's property image upload page.
*/
public function get_upload(){
$property_name = array('' => 'Select One') +
Property::where('property_isDeleted', '!=', '1')
->where('property_isActive', '1')
->orderBy('property_id')->get()->lists('full_name', 'property_id');
$this->layout->content = View::make('images.upload')
->with('title', 'Add New Images')
->with('propertyName', $property_name);
}
/**
* Validate and upload the property image(s).
*/
public function post_upload()
{
$propertyId = Input::get('property_name');
$validation = Property::validate_upload();
if($validation->fails()) {
return Redirect::route('new_images')
->withErrors($validation);
}
else {
$files = Input::file('file');
$serializedFile = array();
foreach ($files as $file) {
// Validate files from input file
$validation = Image::validateImage(array('file'=> $file));
if (!$validation->fails() && $file->isValid()) {
$fileName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$folderName = $propertyId;
$destinationPath = 'uploads/' . $folderName;
// Move file to generated folder
$file->move($destinationPath, $fileName);
Image::create(array(
'image_propertyId' => $propertyId,
'image_name' => $fileName,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
));
} else {
return Redirect::route('new_images')
->with('status', 'alert-danger')
->with('image-message', 'There was a problem uploading your image(s)!');
}
$serializedFile[] = $folderName;
}
return Redirect::route('new_images')
->with('status', 'alert-success')
->with('files', $serializedFile)
->with('image-message', 'Your image(s) were successfully uploaded');
}
}
/**
* Get the property relating to a particular image.
*/
private function get_property($imageId)
{
$image = Image::findOrFail($imageId);
if (! ($image->property_id == 0 || empty($image->properties->property_name))) {
return $image->properties->property_name;
} else {
return 'Property name not found';
}
}
/**
* Delete a property image.
*/
public function delete_destroy($imageId)
{
Image::find($imageId)->delete();
return Redirect::back()
->with('status', 'alert-success')
->with('message', 'Image removed successfully');
}
/**
* Set one of the property images as the primary image.
*/
public function put_setPrimary($property_id, $image_id){
$propertyimages = DB::table('images')->where('image_propertyId', '=', $property_id)->get();
if($propertyimages!=null){
foreach ($propertyimages as $propertyimage) {
if($propertyimage->image_isPrimary == '1')
Image::find($propertyimage->image_id)->update(array(
'image_isPrimary'=>'0'
));
}
Image::find($image_id)->update(array(
'image_isPrimary'=>'1'
));
return Redirect::back()
->with('message', 'The primary image was successfully set!');
}
else {
return Redirect::back()
->with('error-message', 'Could not set primary image!');
}
}
}<file_sep>/app/models/Staff_Role.php
<?php
/* Staff Role Model Class */
class Staff_Role extends Eloquent {
//Database table
protected $table = 'staff_roles';
//Primary key of the staff_roles table
protected $primaryKey = 'staff_role_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('staff_role_id','staff_role_name','staff_role_description');
/**
* Validate staff role creation method.
*
* @return object Validator
*/
public static function validate_create()
{
$create_staff_role_rules = array(
'staff_role_name'=>'Required|Min:2|Unique:staff_roles,staff_role_name',
'staff_role_description'=>'Required|Min:20'
);
$create_staff_role_messages = array(
'staff_role_name.unique' => 'Provided Role Name is already in use'
);
return Validator::make(Input::all(), $create_staff_role_rules, $create_staff_role_messages);
}
/**
* Validate staff role modification method.
*
* @return object Validator
*/
public static function validate_edit($staff_role_id)
{
$edit_staff_role_rules = array(
'staff_role_name'=>'Required|Min:2|Unique:staff_roles,staff_role_name,'.$staff_role_id.',staff_role_id',
'staff_role_description'=>'Required|Min:20'
);
$edit_staff_role_messages = array(
'staff_role_name.unique' => 'Provided Role Name is already in use'
);
return Validator::make(Input::all(), $edit_staff_role_rules, $edit_staff_role_messages);
}
}<file_sep>/app/controllers/CmsStaffController.php
<?php
use Illuminate\Auth\AdminGuard;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Hashing\BcryptHasher;
//CMS Staff Controller Class
class CmsStaffController extends BaseController {
//Enable restful feature
public $restful = true;
//Define the controller layout
protected $layout = "layouts.cmslayout";
/**
* Show the CMS's staff login page.
*/
public function get_login(){
if (!Auth::guest())
return Redirect::route('cmshome')->with('message', 'You are already logged in!');
else
$this->layout->content = View::make('staff.logincms');
}
/**
* Validate and login the staff member.
*/
public function post_signedin(){
$staffdata = array(
'staff_emailAddress' => Input::get('staff_emailAddress'),
'password' => Input::get('staff_<PASSWORD>')
);
$validation = Staff::validate_login();
if($validation->fails()) {
return Redirect::route('cmslogin')
->withErrors($validation)
->withInput();
}
else {
if (Auth::attempt($staffdata)) {
$session_staff_id = Auth::user()->staff_id;
return Redirect::route('cmshome')->with('message', 'You are now logged in!');
} else {
return Redirect::route('cmslogin')
->with('error-message', 'Your email address/password combination was incorrect. Please try again.')
->withInput();
}
}
}
/**
* Logout the staff member and show the CMS staff logout page.
*/
public function get_logout()
{
Auth::logout();
return Redirect::route('cmslogin')->with('message', 'You are now logged out!');
}
}<file_sep>/app/models/Banner_Image.php
<?php
/* Banner Image Model Class */
class Banner_Image extends Eloquent {
//Database table
protected $table = 'banner_images';
//Primary key of the banner_images table
protected $primaryKey = 'banner_image_id';
//The fillable property specifies which attributes should be mass-assignable
protected $fillable = array('banner_image_id','banner_image_name');
/**
* Get the id of the banner image.
*
* @return int
*/
public function getBannerImageId()
{
return $this->banner_image_id;
}
/**
* Upload image validation rules.
* File must be of type image and has a maximum size of 2048KB
*
* @var array
*/
public static $rules = array(
'file' => 'image|max:2048'
);
/**
* Validate banner image method.
*
* @param file $data
* @return object Validator
*/
public static function validateBannerImage($data)
{
return Validator::make($data, static::$rules);
}
}<file_sep>/app/database/migrations/2014_02_03_182307_add_customers.php
<?php
use Illuminate\Database\Migrations\Migration;
class AddCustomers extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::table('customers')->insert(array(
'customer_title'=>'Mr.',
'customer_firstName'=>'Matthew',
'customer_lastName'=>'Sacco',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'mattsacc1990',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Vendor',
'customer_idCardNumber'=>'132187M',
'customer_dateOfBirth'=>'1987-02-04 00:00:00',
'customer_addressLine1'=>'40, Blossoms, Agnese Schembri Street',
'customer_addressLine2'=>'Ta Paris, Birkirkara, BKR4070',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21447351',
'customer_mobileNumber'=>'99297389',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Ms.',
'customer_firstName'=>'Maria',
'customer_lastName'=>'Vella',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'marvella',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Vendor',
'customer_idCardNumber'=>'234583M',
'customer_dateOfBirth'=>'1983-10-14 00:00:00',
'customer_addressLine1'=>'12, Charity, Main Road',
'customer_addressLine2'=>'Fgura FGR1289',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21678776',
'customer_mobileNumber'=>'79120976',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Ms.',
'customer_firstName'=>'Daniela',
'customer_lastName'=>'Sacco',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'danisac18',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'132190M',
'customer_dateOfBirth'=>'1990-01-01 00:00:00',
'customer_addressLine1'=>'34, Home Sweet Home, Independence Avenue',
'customer_addressLine2'=>'Mosta, MST1242',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21882763',
'customer_mobileNumber'=>'99876711',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Ms.',
'customer_firstName'=>'Lilian',
'customer_lastName'=>'Sacco',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'lilsacco',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'876786M',
'customer_dateOfBirth'=>'1986-12-08 00:00:00',
'customer_addressLine1'=>'11, Hope, Valley Road',
'customer_addressLine2'=>'Birkirkara, BKR3000',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21434498',
'customer_mobileNumber'=>'79864360',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Mr.',
'customer_firstName'=>'Mario',
'customer_lastName'=>'Cauchi',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'marcauchi',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Vendor',
'customer_idCardNumber'=>'234367M',
'customer_dateOfBirth'=>'1967-06-16 00:00:00',
'customer_addressLine1'=>'26, Ocean View, Side Street',
'customer_addressLine2'=>'Mellieha, MLH1223',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21873367',
'customer_mobileNumber'=>'79267399',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Dr.',
'customer_firstName'=>'Richard',
'customer_lastName'=>'Attard',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'richattard',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'665887M',
'customer_dateOfBirth'=>'1987-09-09 00:00:00',
'customer_addressLine1'=>'9, Peace, Naxxar Road',
'customer_addressLine2'=>'Msida, MSD2309',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'27665872',
'customer_mobileNumber'=>'79662087',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Mr.',
'customer_firstName'=>'Horace',
'customer_lastName'=>'Azzopardi',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'h.azzopardi',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'833990M',
'customer_dateOfBirth'=>'1990-07-10 00:00:00',
'customer_addressLine1'=>'4, Ivy Cottage, Main Street',
'customer_addressLine2'=>'Paola, PLA6627',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'27213499',
'customer_mobileNumber'=>'99318933',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Mrs.',
'customer_firstName'=>'Helga',
'customer_lastName'=>'Aquilina',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'haquilina',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'327786M',
'customer_dateOfBirth'=>'1986-10-08 00:00:00',
'customer_addressLine1'=>'39, Esperanto, Labour Avenue',
'customer_addressLine2'=>'Naxxar, NXR2000',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21442201',
'customer_mobileNumber'=>'79322134',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Mr.',
'customer_firstName'=>'Benjamin',
'customer_lastName'=>'Darmanin',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'bdarmanin',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'322458M',
'customer_dateOfBirth'=>'1958-06-03 00:00:00',
'customer_addressLine1'=>'55, Greenfields, Great Siege Road',
'customer_addressLine2'=>'Valletta, VLT3012',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21230199',
'customer_mobileNumber'=>'79364447',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Mrs.',
'customer_firstName'=>'Grace',
'customer_lastName'=>'Cachia',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'gracecachia',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'422182M',
'customer_dateOfBirth'=>'1982-12-12 00:00:00',
'customer_addressLine1'=>'3, Southfields, Mill Street',
'customer_addressLine2'=>'Qormi, QRM2311',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'21983822',
'customer_mobileNumber'=>'99223113',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
DB::table('customers')->insert(array(
'customer_title'=>'Mr.',
'customer_firstName'=>'Kenneth',
'customer_lastName'=>'Galea',
'customer_emailAddress'=>'<EMAIL>',
'customer_username'=>'kenneth.galea',
'customer_password'=>'<PASSWORD>',
'customer_type'=>'Buyer',
'customer_idCardNumber'=>'831890M',
'customer_dateOfBirth'=>'1990-05-10 00:00:00',
'customer_addressLine1'=>'1, Welcome, Balzan Valley',
'customer_addressLine2'=>'Balzan, BLZ2100',
'customer_countryId'=>'151',
'customer_phoneNumber'=>'27312758',
'customer_mobileNumber'=>'79231003',
'customer_isActive'=>'1',
'customer_isDeleted'=>'0',
'created_at'=>date('Y-m-d H:m:s'),
'updated_at'=>date('Y-m-d H:m:s'),
));
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::table('customers')->delete();
}
} | 6eacf64a55e32e3c43c0658ff50aef1d37354a87 | [
"JavaScript",
"PHP"
] | 55 | PHP | matt90github/BestPropertyMalta | 96f37ba5d8bebfa592a620d0510857d470462ebf | 6a0d54b6198097c6047781f4bfce84add91b65cd |
refs/heads/master | <repo_name>CytronTechnologies/DIY-PR15-PIC16F876A<file_sep>/MPLABX/PR15.X/nbproject/Makefile-variables.mk
#
# Generated - do not edit!
#
# NOCDDL
#
CND_BASEDIR=`pwd`
# default configuration
CND_ARTIFACT_DIR_default=dist/default/production
CND_ARTIFACT_NAME_default=PR15.X.production.hex
CND_ARTIFACT_PATH_default=dist/default/production/PR15.X.production.hex
CND_PACKAGE_DIR_default=${CND_DISTDIR}/default/package
CND_PACKAGE_NAME_default=pr15.x.tar
CND_PACKAGE_PATH_default=${CND_DISTDIR}/default/package/pr15.x.tar
<file_sep>/Source File/PR15.c
//=========================================================================
// Author : Cytron Technologies
// Project description : Read Gas Sensor and Humidity Sensor using PIC
// Microcontroller ADC and display the reading on LCD display
// : PIC16F876A is used in this project.Compatible with
// MPLAB IDE with HITECH C and XC8 compiler and by
// using MPLABX with HITECH C compiler v 9.82/v9.83 and XC8 compiler.
//==========================================================================
// include
//==========================================================================
#if defined(__XC8)
#include <xc.h>
#pragma config CONFIG = 0x3F32
#else
#include <htc.h> //include the PIC microchip header file
//===========================================================================
// configuration
//============================================================================
__CONFIG (0x3F32);
//FOSC = HS // Oscillator Selection bits (HS oscillator)
//WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
//PWRTE = ON // Power-up Timer Enable bit (PWRT enabled)
//BOREN = OFF // Brown-out Reset Enable bit (BOR disabled)
//LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)
//CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
//WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control)
//CP = OFF // Flash Program Memory Code Protection bit (Code protection off)
#endif
// define
//==========================================================================
#define RS RB3 //RS pin of LCD display
#define RW RB2 //R/W pin of the LCD display
#define E RB1 //E pin of the LCD display
#define B_LIGHT RB0 //Backlight of LCD display (high to on)
#define BUTTON1 RB5 //button 1 (active low)
#define BUTTON2 RB4 //button 2 (active low)
#define LCD_DATA PORTC //LCD display data PORT (8-bit)
#define LED1 RA2 //led 1 (active high)
#define LED2 RA5 //led 2 (active high)
// function prototype (every function must have a fucntion prototype)
//==========================================================================
void delay(unsigned long data);
void send_config(unsigned char data);
void send_char(unsigned char data);
void lcd_goto(unsigned char data);
void lcd_clr(void);
void send_string(const char *s);
void send_num(unsigned short data);
unsigned char usart_rec(void);
void beep_short(void);
void beep_short2(void);
void beep_long(void);
unsigned char read_ad(unsigned char channel);
// global variable
//==========================================================================
// main function
//==========================================================================
void main(void)
{
//assign variable
unsigned char temp; //declare a temporary variable for reading ADC
unsigned char mode; //declare a variable to represent current mode
//set I/O input output
TRISB = 0b11110000; //configure PORT B I/O direction
TRISA = 0b11011011; //configure PORT A I/O direction
TRISC = 0b00000000; //configure PORT C I/O direction
//configure lcd
send_config(0b00000001); //clear display at lcd
send_config(0b00000010); //Lcd Return to home
send_config(0b00000110); //entry mode-cursor increase 1
send_config(0b00001100); //diplay on, cursor off and cursor blink off
send_config(0b00111000); //function set
//configure ADC
ADCON0=0b10000001; //enable ADC converter module
ADCON1=0b01000100; //configure ADC and ANx pin
//initial condition
B_LIGHT=1; //on backlight
lcd_clr(); //clear lcd
lcd_goto(0); //set the lcd cursor to location 0
mode=1; //set startup mode to mode 1
LED1=1; //on led 1
LED2=0; //off led 2
while(1) //infinity loop
{
if(BUTTON1==0) //if button 1 pressed
{
mode=1; //set to mode 1
LED2=0; //off led 2
LED1=1; //on led 1
}
else if(BUTTON2==0) //else if button 2 pressed
{
mode=2; //set to mode 2
LED1=0; //off led 1
LED2=1; //on led 1
}
if(mode==1) //if mode = 1
{
lcd_goto(0); //set lcd cursor to location 0
send_string("Gas Sensor "); //display "Gas Sensor"
temp=read_ad(0); //read AN0 (Gas Sensor)
lcd_goto(20); //set lcd cursor to location 20
send_num(temp); //display the analog value of the gas sensor
}
else if(mode==2) //if mode = 2
{
lcd_goto(0); //set lcd cursor to location 0
send_string("Humidity Sensor "); //display "Humidity Sensor"
temp=read_ad(1); //read AN1 (Humidity Sensor)
lcd_goto(20); //set lcd cursor to location 20
send_num(temp); //display the analog value of the gas sensor
}
}
}
// functions
//==========================================================================
void delay(unsigned long data) //delay function, the delay time
{ //depend on the given value
for( ;data>0;data-=1);
}
void send_config(unsigned char data) //send lcd configuration
{
RW=0; //set lcd to write mode
RS=0; //set lcd to configuration mode
LCD_DATA=data; //lcd data port = data
E=1; //pulse e to confirm the data
delay(50);
E=0;
delay(50);
}
void send_char(unsigned char data) //send lcd character
{
RW=0; //set lcd to write mode
RS=1; //set lcd to display mode
LCD_DATA=data; //lcd data port = data
E=1; //pulse e to confirm the data
delay(10);
E=0;
delay(10);
}
void lcd_goto(unsigned char data) //set the location of the lcd cursor
{ //if the given value is (0-15) the
if(data<16) //cursor will be at the upper line
{ //if the given value is (20-35) the
send_config(0x80+data); //cursor will be at the lower line
} //location of the lcd cursor(2X16):
else // -----------------------------------------------------
{ // | |00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15| |
data=data-20; // | |20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35| |
send_config(0xc0+data); // -----------------------------------------------------
}
}
void lcd_clr(void) //clear the lcd
{
send_config(0x01);
delay(600);
}
void send_string(const char *s) //send a string to display in the lcd
{
unsigned char i=0;
while (s && *s)send_char (*s++);
}
void send_num(unsigned short data) //function to display a value on lcd display
{
unsigned char tenthou,thou,hund,tenth;
tenthou=data/10000; //get tenthousand value
data=data%10000;
thou=data/1000; //get thousand value
data=data%1000;
hund=data/100; //get hundred value
data=data%100;
tenth=data/10; //get tenth value
data=data%10; //get unit value
send_char(0x30+tenthou); //display the tenthousand value
send_char(0x30+thou); //display the thousand value
send_char(0x30+hund); //display the hundred value
send_char(0x30+tenth); //display the tenth value
send_char(0x30+data); //display the unit value
}
unsigned char read_ad(unsigned char channel) //fucntion read analog input according to the given channel
{
unsigned char result; //declare a variable call result
switch(channel)
{
case 0: //if channel = 0
CHS2=0; //CHS2=0
CHS1=0; //CHS1=0
CHS0=0; //CHS0=0
break;
case 1: //if channel = 1
CHS2=0; //CHS=0
CHS1=0; //CHS=0
CHS0=1; //CHS=1
break;
}
GO=1; //start ADC convertion
while(GO); //wait for ADC convertion to complete
result=ADRESH; //read the result
return result; //return the result
}
<file_sep>/README.md
# Reading Gas Humidity
Sample source code for DIY PR15. Project description : This PIC microcontroller based project uses PIC16F876A to interface with Humidity and Gas sensor, further display the reading on 16x2 LCD. It explains the method to interface humidity and gas sensor with microcontroller.Compatible with MPLAB IDE with HITECH C compiler, MPLABX with HITECH C compiler v9.83/v9.82 and XC8 compiler.
There is 3 folder which are Source code(.c), Sample code using MPLABX and sample code using MPLAB(Using MPLAB 8.6 And HiTech 9.80) Welcome to our tecnical forum for any inquiry. http://forum.cytron.com.my/
| d8858be9ff8951694d363181bdbece5f9b74eba8 | [
"Markdown",
"C",
"Makefile"
] | 3 | Makefile | CytronTechnologies/DIY-PR15-PIC16F876A | 7477353372430688cb5593eb7817030acc561b8b | 5ab78ea01302f14bee13acb2510cb5c870ac7585 |
refs/heads/master | <repo_name>abhishekSolanki01/algo-ds<file_sep>/binarysearch/upperboubd.cpp
#include <iostream>
using namespace std;
long long int solve(long long n,long long int x)
{
if(x==9)
{
return n/9;
}
else
{
if(x<=n%9)
{
return n/9+1;
}
else
return n/9;
}
}
int main() {
int t;
long long n,m,x;
cin>>t;
while(t--)
{
cin>>n>>m>>x;
//cout<<solve(m,x)<<'\n';
cout<<solve(m,x)-solve(n-1,x)<<'\n';
}
// your code goes here
return 0;
}
| 53747c2364798e99a779f92ced652b953a98ed87 | [
"C++"
] | 1 | C++ | abhishekSolanki01/algo-ds | c9f79012040bdee20972370c7735daf6007a08ab | 1f68fecb1e053c3618e4b5a9f0a44921f9d25d1a |
refs/heads/master | <repo_name>modgeosys/downloads<file_sep>/app/models/document.rb
class Document < ActiveRecord::Base
has_many :downloads
belongs_to :license
def file_path
"#{RAILS_ROOT}/documents/#{filename}"
end
def file_url
"http://downloads.asapisystems.com/#{filename}"
end
def last_modification_time_of_file
File::mtime(file_path).gmtime
end
end
<file_sep>/app/views/documents/index.xml.builder
xml.instruct!
xml.rss(:version => "2.0") do
xml.channel do
xml.title('ASAP iSystems Downloads')
xml.link(document_index_url)
xml.description('An index of downloadable documents from ASAP iSystems')
xml.pubDate(rss_time_format(Time.now.gmtime))
@documents.each do |document|
xml.item do
xml.title(document.title)
xml.link(document_download_url(document.filename))
xml.description(document.description)
xml.pubDate(rss_time_format(document.last_modification_time_of_file))
end
end
end
end<file_sep>/app/models/license.rb
class License < ActiveRecord::Base
has_many :documents
end
<file_sep>/app/models/download.rb
class Download < ActiveRecord::Base
belongs_to :document
validates_acceptance_of :license_agreement, :accept => true
validates_presence_of :email
validates_presence_of :first_name
validates_presence_of :last_name
validates_format_of :email, :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/, :message => "is invalid"
end
<file_sep>/db/migrate/20110809040506_create_downloads.rb
class CreateDownloads < ActiveRecord::Migration
def self.up
create_table :downloads do |t|
t.column :email, :string
t.column :accepted, :boolean, :default => false
t.column :ip_address, :string
t.timestamps
end
end
def self.down
drop_table :downloads
end
end
<file_sep>/db/migrate/20111010234400_fix_qa_data_type.rb
class FixQaDataType < ActiveRecord::Migration
def self.up
change_column :downloads, :quality_assurance, :boolean
end
def self.down
change_column :downloads, :quality_assurance, :string
end
end<file_sep>/db/migrate/20110810005410_rename_acceptance_field.rb
class RenameAcceptanceField < ActiveRecord::Migration
def self.up
rename_column :downloads, :accepted, :license_agreement
end
def self.down
rename_column :downloads, :license_agreement, :accepted
end
end<file_sep>/app/controllers/downloads_controller.rb
require 'uri'
class DownloadsController < ApplicationController
def new
document = lookup_document
@download = Download.new(params[:download])
@download.document = document
end
def create
fields = params[:download] || {}
@download = Download.new(fields.merge(:ip_address => request.ip))
if @download.save
send_file(@download.document.file_path)
else
render :action => "new"
end
end
private
def lookup_document
if params[:document_id]
Document.find(params[:document_id])
else
Document.find_by_filename(URI.unescape(request.path.sub('/', '')))
end
end
end
<file_sep>/app/mailers/content_notifier.rb
class ContentNotifier < ActionMailer::Base
default :from => '<EMAIL>',
:bcc => '<EMAIL>'
def notify(document_id, summary)
@document = Document.find(document_id)
@summary = summary
recipients = Download.find_all_by_email_notification(true).collect(&:email).uniq
recipients.each do |recipient|
change_notification(recipient).deliver
sleep 1
end
end
def change_notification(recipient)
prototype_download = Download.find(:first, :conditions => ['email = ?', recipient], :order => 'created_at desc')
if prototype_download
@download = Download.new(:email => prototype_download.email,
:license_agreement => true,
:email_notification => true,
:quality_assurance => prototype_download.quality_assurance,
:first_name => prototype_download.first_name,
:last_name => prototype_download.last_name,
:document_id => prototype_download.document_id)
mail(:subject => "Download Change Notification for '#{@document.title}'", :to => recipient)
end
end
end
<file_sep>/app/helpers/documents_helper.rb
module DocumentsHelper
def downloads_root_url
"#{request.protocol}#{request.host}#{request.port == 80 ? '' : ':' + request.port.to_s}"
end
def document_index_url
"#{downloads_root_url}/documents"
end
def document_download_url(filename)
"#{downloads_root_url}/#{filename}"
end
def rss_time_format(time)
time.strftime('%a, %d %b %Y %H:%M:%S %Z+00.00').sub('UTC', 'GMT')
end
end
| 3e3942254441a9756d3daf883555ff9842e3a1db | [
"Ruby"
] | 10 | Ruby | modgeosys/downloads | 0d547831e6486d88c525eb677f02b16d5f3863d8 | ef9ab494fc0547598a8011ee900988085939bb9f |
refs/heads/master | <file_sep>var groupMethods = function(hook, methods) {
for (var method in methods) {
if (methods.hasOwnProperty(method)) {
(function (oldMethod) {
oldMethod = function() {
var params = Array.prototype.slice.call(arguments),
res = hook.call(this);
if (res) {
params.push(res);
oldMethod.apply(this, params);
}
};
})(methods[method]);
}
}
Meteor.methods(methods);
};
var checkAuthUser = function() {
return this.userId;
};
var authMethods = function(methods) {
groupMethods(checkAuthUser, methods);
};
module.exports = {
groupMethods: groupMethods,
authMethods: authMethods
};<file_sep># meteor-hook-server
You can combine some meteor methods in a group/groups to execute some hook before action each of them.
For example, we can combine methods which are executing when user is logged.
# Installation
```
$ meteor npm install --save meteor-hook-server
```
# Usage
```
import { groupMethods as yourOwnName } from 'meteor-hook-server';
const hook = function() {
return this.userId;
};
youOwnName(hook, {
testMethod() {
// call this method on client by Meteor.call('testMethod')
// do here what you need
}
});
```
testMethods method was executed when your hook returns a result equally "true" (if (your result) { // method is executed }).
In another way your method will be prevented.
In our example when user is logged - 'this.userId' returns a user id (it's true) and when the user isn't logged - it's
null - false.
# Data from a hook to a method.
If you need to pass some data from a hook to "method", you can get it from the last param in your method.
```
import { groupMethods as yourOwnName } from 'meteor-hook-server';
const hook = function() {
return this.userId;
};
youOwnName(hook, {
testMethods(some, other, params, id) {
console.log(id); // this.userId
}
});
```
Be attentive: if you want to keep the context (like in a server meteor method) in "hook" you need to use function() {}
instead of an arrow function ( () => {} ).
# Default group:
- authMethods: all methods are executed only when user is logged.
```
import { authMethods } from 'meteor-hook-server';
authMethods({
testMethods() {
// do here what you need
}
});
```
# Next:
- supporting publications | bfbfea78e1bee10ca1ad737e4a89d067a1062fe7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | zhe1ka/meteor-hook-server | f3df2f42a9177c62100017e7ad46aa7f80b11057 | 823a8db9d1b9886226b5a143749ae1f64e5deb7b |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
namespace DynamicProgramming.Domain
{
public class EightQueens
{
int GRID_SIZE = 8;
public void PlaceQueen(int row, int[] columns, List<int[]> results)
{
if(row == GRID_SIZE) {
results.Add(columns);
} else {
for(int col = 0; col < GRID_SIZE; col++)
{
if(CheckValid(columns, row, col))
{
columns[row] = col;
PlaceQueen(row + 1, columns, results);
}
}
}
}
public bool CheckValid(int[] columns, int row1, int column1)
{
for (int row2 = 0; row2 < row1; row2++)
{
int column2 = columns[row2];
if(column1 == column2){
return false;
}
int columnDistance = Math.Abs(column2 - column1);
int rowDistance = row1 - row2;
if(columnDistance == rowDistance)
{
return false;
}
}
return true;
}
}
}<file_sep>using System;
namespace LinkedList.Domain
{
public class Intersection
{
public SinglyLinkedListNode GetIntersection(SinglyLinkedListNode node1, SinglyLinkedListNode node2)
{
if(node1 == null || node2 == null){
return null;
}
Result result1 = GetTailAndSize(node1);
Result result2 = GetTailAndSize(node2);
if(result1.tail != result2.tail){
return null;
}
SinglyLinkedListNode shorter = result1.size < result2.size ? node1 : node2;
SinglyLinkedListNode longer = result1.size < result2.size ? node2 : node1;
longer = GetKthNode(longer, Math.Abs(result1.size - result2.size));
while(shorter != longer){
shorter = shorter.next;
longer = longer.next;
}
return longer;
}
private Result GetTailAndSize(SinglyLinkedListNode node)
{
if(node == null){
return null;
}
int size = 1;
SinglyLinkedListNode current = node;
while(current != null){
size++;
current = current.next;
}
return new Result(current,size);
}
public SinglyLinkedListNode GetKthNode(SinglyLinkedListNode node, int k)
{
SinglyLinkedListNode current = node;
while(k > 0 && current != null)
{
current = current.next;
k--;
}
return current;
}
}
public class Result
{
public SinglyLinkedListNode tail;
public int size;
public Result(SinglyLinkedListNode tail, int size)
{
this.size = size;
this.tail = tail;
}
}
}<file_sep>using System;
namespace TreeAndGraph.Domain
{
public class PathWithSum
{
public int CountTotalPathWithSum(TreeNode<int> root, int targetSum)
{
if(root == null) return 0;
int pathFromRoot = CountPathsWithSumFromNode(root, targetSum, 0);
int pathOnLeft = CountTotalPathWithSum(root.left, targetSum);
int pathOnRight = CountTotalPathWithSum(root.right, targetSum);
return pathFromRoot + pathOnLeft + pathOnRight;
}
public int CountPathsWithSumFromNode(TreeNode<int> node, int targetSum, int currentSum)
{
if(node == null) return 0;
currentSum += node.value;
int totalPaths = 0;
if(currentSum == targetSum){
totalPaths++;
}
totalPaths += CountPathsWithSumFromNode(node.left, targetSum, currentSum);
totalPaths += CountPathsWithSumFromNode(node.right, targetSum, currentSum);
return totalPaths;
}
}
}<file_sep>using System;
namespace StackAndQueue.Domain
{
public class MyQueue<T>
{
private class QueueNode
{
public T data;
public QueueNode next;
public QueueNode(T item)
{
this.data = item;
}
}
private QueueNode first;
private QueueNode last;
public void Add(T item)
{
QueueNode t = new QueueNode(item);
if(last != null)
{
last.next = t;
}
last = t;
if(first == null)
{
first = last;
}
}
public T Remove()
{
if(first == null) throw new InvalidOperationException();
T data = first.data;
first = first.next;
if(first == null)
{
last = null;
}
return data;
}
public T Peek()
{
if(first == null) throw new InvalidOperationException();
return first.data;
}
public bool IsEmpty()
{
return first == null;
}
}
}<file_sep>using Xunit;
using LinkedList.Domain;
namespace LinkedList.Test
{
public class DeleteMiddleNodeTest
{
DeleteMiddleNode classDMN = new DeleteMiddleNode();
[Fact]
public void TestDeleteMiddleNode()
{
//Given
SinglyLinkedListNode node = new SinglyLinkedListNode(1);
node.AppendToTail(1);
node.AppendToTail(2);
node.AppendToTail(3);
node.AppendToTail(4);
node.AppendToTail(4);
node.AppendToTail(4);
//When
classDMN.TryDeletingMiddleNode(node.GetFirstNode(node,3));
//Then
Assert.True(AreSame(null,node.GetFirstNode(node,3)));
//When
//Then
}
private static bool AreSame(SinglyLinkedListNode node1, SinglyLinkedListNode node2)
{
return node1 == node2;
}
}
}<file_sep>using System;
namespace TreeAndGraph.Domain
{
public class TreeNodeWithRandomNode<T> : TreeNode<T>
{
public override TreeNode<T> GetRandomNode()
{
int leftSize = left == null ? 0 : left.size;
Random random = new Random();
int index = random.Next(size);
if(index < leftSize){
return left.GetRandomNode();
}else if (index == leftSize){
return this;
}else {
return right.GetRandomNode();
}
}
public override void InsertInOrder(int d)
{
if( d < value){
if (left == null)
{
left = new TreeNode<T>(d);
} else {
left.InsertInOrder(d);
}
} else{
if(right == null)
{
right = new TreeNode<T>(d);
}else {
right.InsertInOrder(d);
}
}
size++;
}
public override TreeNode<T> Find(int d)
{
if(d == value){
return this;
}else if (d <= value)
{
return left != null ? left.Find(d) : null;
}else if (d > value)
{
return right != null ? right.Find(d) : null;
}
return null;
}
}
}<file_sep>using System;
namespace DynamicProgramming.Domain
{
public class MagicIndex
{
public int MagicFast(int[] array)
{
return MagicFast(array, 0, array.Length - 1);
}
private int MagicFast(int[] array, int start, int end)
{
if(end < start) return -1;
int midIndex = (start + end) / 2;
int midValue = array[midIndex];
if(midIndex == midValue){
return midIndex;
}
int leftIndex = Math.Min(midIndex - 1, midValue);
int left = MagicFast(array, start, leftIndex);
if(left >= 0) return left;
int rightIndex = Math.Min(midIndex + 1, midValue);
int right = MagicFast(array, rightIndex, end);
return right;
}
}
}<file_sep>using System;
namespace StackAndQueue.Domain
{
public class QueueViaStack<T>
{
MyStack<T> stackNew, stackOld;
public QueueViaStack()
{
stackNew = new MyStack<T>();
stackOld = new MyStack<T>();
}
public int Size()
{
return stackNew.size + stackOld.size;
}
public void Add(T value)
{
stackNew.Push(value);
}
private void ShiftStacks()
{
if(stackOld.IsEmpty()){
while (!stackNew.IsEmpty())
{
stackOld.Push(stackNew.Pop());
}
}
}
public T Remove()
{
ShiftStacks();
return stackOld.Pop();
}
public T Peek()
{
ShiftStacks();
return stackOld.Peek();
}
}
}<file_sep>namespace ArrayStudy.Domain
{
public class RotateMatrix
{
public int[][] rotate(int[][] matrix)
{
if (matrix.Length == 0 || matrix.Length != matrix[0].Length) return matrix;
int n = matrix.Length;
for (int layer = 0; layer < n / 2; layer++)
{
int first = layer;
int last = n - 1 - layer;
for (int i = first; i < last; i++)
{
int offset = i - first;
int top= matrix[first][i];
matrix[first][i] = matrix[last-offset][first];
matrix[last-offset][first] = matrix[last][last - offset];
matrix[last][last - offset] = matrix[i][last];
matrix[i][last] = top;
}
}
return matrix;
}
}
}<file_sep>using Xunit;
using BitManipulation.Domain;
namespace BitManipulation.Test
{
public class PairwiseSwapTest
{
[Theory]
[InlineData(9,6)]
[InlineData(32,16)]
public void TestSwapBits(uint n, uint expected)
{
//Given
PairwiseSwap test = new PairwiseSwap();
//When
uint result = test.SwapBits(n);
//Then
Assert.Equal(expected,result);
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace DynamicProgramming.Domain
{
public class PermutationWithDups
{
public List<string> PrintPerms(string s)
{
List<string> result = new List<string>();
Dictionary<char, int> map = BuildMap(s);
PrintPerms(map, "", s.Length, result);
return result;
}
public Dictionary<char, int> BuildMap(string s)
{
Dictionary<char, int> map = new Dictionary<char, int>();
foreach(char c in s)
{
if(map.ContainsKey(c)){
map[c]++;
}else{
map.Add(c, 1);
}
}
return map;
}
public void PrintPerms(Dictionary<char,int> map, string prefix, int remaining, List<string> result)
{
if(remaining == 0){
result.Add(prefix);
return;
}
foreach (char c in map.Keys)
{
int count = map[c];
if(count> 0){
map[c]--;
PrintPerms(map, prefix + c, remaining - 1, result);
map[c] = count;
}
}
}
}
}<file_sep>using Xunit;
using BitManipulation.Domain;
namespace BitManipulation.Test
{
public class InsertionTest
{
[Theory]
[InlineData(1024,19,2,6,1100)]
public void TestInsertion(int n, int m, int i, int j, int expected)
{
//Given
Insertion insertion = new Insertion();
//When
int result = insertion.InsertBits(n,m,i,j);
//Then
Assert.Equal(expected,result);
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class StringCompressionTest
{
StringCompression classSC = new StringCompression();
[Fact]
public void WhenEmptyStringReturnEmpty()
{
//Given
string str = classSC.CompressString("");
//When
//Then
Assert.Equal("",str);
}
[Theory]
[InlineData("abc","abc")]
[InlineData("aabbcc","aabbcc")]
[InlineData("aabcccd","aabcccd")]
public void WhenCompressedLongerReturnOriginal(string originalStr, string expected)
{
string str = classSC.CompressString(originalStr);
//When
//Then
Assert.Equal(expected,str);
}
[Theory]
[InlineData("aabbccc","a2b2c3")]
[InlineData("aaabbbcccddd","a3b3c3d3")]
[InlineData("aaabbbbccd","a3b4c2d1")]
public void WhenCompressedShorterReturnCompressed(string originalStr, string expected)
{
string str = classSC.CompressString(originalStr);
//When
//Then
Assert.Equal(expected,str);
}
}
}<file_sep>using System;
namespace BitManipulation.Domain
{
public class Insertion
{
public int InsertBits(int n, int m, int i, int j)
{
int allOnes = ~0;
int left = allOnes << (j + 1);
int right = (1 << i) - 1;
int mask = left | right;
int n_cleared = n & mask;
int m_shifted = m << i;
return n_cleared | m_shifted;
}
}
}<file_sep>namespace ArrayStudy.Domain
{
public class StringRotation
{
public bool isRotation(string sl, string s2)
{
int len = sl.Length;
/* Check that sl and s2 are equal length and not empty*/
if (len == s2.Length && len > 0)
{
/* Concatenate sl and sl within new buffer */
string slsl = sl + sl;
return isSubstring(slsl, s2);
}
return false;
}
private bool isSubstring(string str1, string str2)
{
return true;
}
}
}<file_sep>using Xunit;
using LinkedList.Domain;
namespace LinkedList.Test
{
public class KthToLastTest
{
KthToLast classKTL = new KthToLast();
SinglyLinkedListNode node = new SinglyLinkedListNode(1);
void InitList()
{
node.AppendToTail(2);
node.AppendToTail(3);
node.AppendToTail(4);
node.AppendToTail(5);
node.AppendToTail(6);
node.AppendToTail(7);
}
[Fact]
public void KthTest()
{
//Given
InitList();
int k = 0;
//When
SinglyLinkedListNode n = classKTL.GetKthNode(node,k);
//Then
Assert.Equal(1,n.data);
}
}
}<file_sep>namespace LinkedList.Domain
{
public class DeleteMiddleNode
{
public bool TryDeletingMiddleNode(SinglyLinkedListNode node)
{
if(node == null || node.next == null)
{
return false;
}
SinglyLinkedListNode next = node.next;
node.next = next.next;
node.data = next.data;
return true;
}
}
}<file_sep>using System.Collections.Generic;
namespace TreeAndGraph.Domain
{
public class BSTSequence
{
public List<SinglyLinkedListNode<int>> GetBSTSequence(TreeNode<int> root)
{
List<SinglyLinkedListNode<int>> result = new List<SinglyLinkedListNode<int>>();
if(root == null)
{
result.Add(new SinglyLinkedListNode<int>());
return result;
}
SinglyLinkedListNode<int> prefix = new SinglyLinkedListNode<int>();
prefix.AppendToTail(root.value);
List<SinglyLinkedListNode<int>> leftSeq = GetBSTSequence(root.left);
List<SinglyLinkedListNode<int>> rightSeq = GetBSTSequence(root.right);
foreach (SinglyLinkedListNode<int> left in leftSeq)
{
foreach (SinglyLinkedListNode<int> right in rightSeq)
{
List<SinglyLinkedListNode<int>> weaved = new List<SinglyLinkedListNode<int>>();
WeaveLists(left, right, weaved, prefix);
result.AddRange(weaved);
}
}
return result;
}
public void WeaveLists(SinglyLinkedListNode<int> first, SinglyLinkedListNode<int> second, List<SinglyLinkedListNode<int>> weaved, SinglyLinkedListNode<int> prefix)
{
if(first == null || second == null)
{
SinglyLinkedListNode<int> result = prefix;
while(first != null){
result.AppendToTail(first.data);
first = first.next;
}
while(second != null){
result.AppendToTail(second.data);
second = second.next;
}
weaved.Add(result);
}
int headFirst = first.GetFirstNode(first, first.data).data;
first.DeleteNode(first, first.data);
prefix.AppendToTail(headFirst);
WeaveLists(first, second, weaved, prefix);
prefix.DeleteNode(prefix, headFirst);
first.AppendToTail(headFirst);
int headSecond = second.GetFirstNode(second, second.data).data;
second.DeleteNode(second, second.data);
prefix.AppendToTail(headSecond);
WeaveLists(first, second, weaved, prefix);
prefix.DeleteNode(prefix, headSecond);
second.AppendToTail(headSecond);
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace DynamicProgramming.Domain
{
public class Permutations
{
public List<string> GetPerms(string str)
{
if (str == null) return null;
List<string> permutations = new List<string>();
if (str.Length == 0)
{
permutations.Add("");
return permutations;
}
char first = str[0];
string remainder = str.Substring(1);
List<string> words = GetPerms(remainder);
foreach (string word in words)
{
for(int j = 0; j <= word.Length; j++){
string s = InsertChatAt(word, first, j);
permutations.Add(s);
}
}
return permutations;
}
public string InsertChatAt(string word, char c, int i){
string start = word.Substring(0,i);
string end = word.Substring(i);
return start + end;
}
}
}<file_sep>using System;
namespace BitManipulation.Domain
{
public class Class1
{
}
}
<file_sep>using System;
using System.Text;
namespace BitManipulation.Domain
{
public class PairwiseSwap
{
public uint SwapBits(uint n)
{
return ( (( n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1));
}
}
}<file_sep># Algorithm
This is a place where you find love and peace... and fun...
<file_sep>using Xunit;
using BitManipulation.Domain;
namespace BitManipulation.Test
{
public class NextNumberTest
{
[Theory]
[InlineData(3,5)]
public void TestGetNext(int num, int expected)
{
//Given
NextNumber test = new NextNumber();
//When
int result = test.GetNext(num);
//Then
Assert.Equal(expected,result);
}
[Theory]
[InlineData(5,3)]
public void TestGetPrev(int num, int expected)
{
//Given
NextNumber test = new NextNumber();
//When
int result = test.getPrev(num);
//Then
Assert.Equal(expected,result);
}
}
}<file_sep>using Xunit;
using LinkedList.Domain;
namespace LinkedList.Test
{
public class SumListTest
{
SumList classSL = new SumList();
[Fact]
public void TestSumList()
{
//Given
SinglyLinkedListNode node1 = new SinglyLinkedListNode(1);
node1.AppendToTail(5);
node1.AppendToTail(3);
SinglyLinkedListNode node2 = new SinglyLinkedListNode(5);
node2.AppendToTail(7);
node2.AppendToTail(9);
SinglyLinkedListNode expected = new SinglyLinkedListNode(6);
expected.AppendToTail(2);
expected.AppendToTail(3);
expected.AppendToTail(1);
//When
SinglyLinkedListNode result = classSL.GetSum(node1,node2);
//Then
while (result != null)
{
Assert.Equal(expected.data, result.data);
result = result.next;
expected = expected.next;
}
}
}
}<file_sep>using Xunit;
using LinkedList.Domain;
namespace LinkedList.Test
{
public class PartitionTest
{
Partition classP = new Partition();
[Fact]
public void TestPartition()
{
//Given
SinglyLinkedListNode node = new SinglyLinkedListNode(1);
node.AppendToTail(5);
node.AppendToTail(2);
node.AppendToTail(3);
// node.AppendToTail(2);
node.AppendToTail(4);
//When
SinglyLinkedListNode n = classP.TryPartition(node,3);
//Then
int[] seq = { 2, 1, 5, 3, 4};
int index = 0;
while (n != null)
{
Assert.Equal(seq[index], n.data);
index++;
n = n.next;
}
}
}
}<file_sep>using Xunit;
using BitManipulation.Domain;
namespace BitManipulation.Test
{
public class BinaryToStringTest
{
[Theory]
[InlineData(0.5,".1")]
public void TestIt(double num, string expected)
{
//Given
BinaryToString insertion = new BinaryToString();
//When
string result = insertion.ConverToString(num);
//Then
Assert.Equal(expected,result);
}
}
}<file_sep>using System;
namespace DynamicProgramming.Domain
{
public class PaintFill
{
public enum Color
{
Black, White, Red, Yellow, Green
}
public bool FillPaint(Color[][] screen, int r, int c, Color nColor)
{
if(screen[r][c] == nColor) return false;
return FillPaint(screen, r, c, screen[r][c], nColor);
}
public bool FillPaint(Color[][] screen, int r, int c, Color oColor, Color nColor)
{
if (r < 0 || r >= screen.Length || c < 0 || c >= screen[0].Length){
return false;
}
if(screen[r][c] == oColor)
{
screen[r][c] = nColor;
FillPaint(screen, r - 1, c, oColor, nColor);
FillPaint(screen, r + 1, c, oColor, nColor);
FillPaint(screen, r, c - 1, oColor, nColor);
FillPaint(screen, r, c + 1, oColor, nColor);
}
return true;
}
}
}<file_sep>using Xunit;
using LinkedList.Domain;
namespace LinkedList.Test
{
public class PalindromeTest
{
Palindrome classP = new Palindrome();
[Fact]
public void WhenPalindromeReturnTrue()
{
//Given
SinglyLinkedListNode node = new SinglyLinkedListNode(1);
node.AppendToTail(2);
node.AppendToTail(3);
node.AppendToTail(4);
node.AppendToTail(3);
node.AppendToTail(2);
node.AppendToTail(1);
//When
bool result = classP.IsPalindrome(node);
//Then
Assert.True(result);
}
[Fact]
public void WhenNotPalindromeReturnFalse()
{
//Given
SinglyLinkedListNode node = new SinglyLinkedListNode(1);
node.AppendToTail(2);
node.AppendToTail(3);
node.AppendToTail(4);
node.AppendToTail(4);
node.AppendToTail(2);
node.AppendToTail(1);
//When
bool result = classP.IsPalindrome(node);
//Then
Assert.False(result);
}
}
}<file_sep>using System;
namespace StackAndQueue.Domain
{
public class Class1
{
}
}
<file_sep>using Xunit;
using BitManipulation.Domain;
namespace BitManipulation.Test
{
public class ConversionTest
{
[Theory]
[InlineData(12,3,4)]
public void TestGetNext(int n, int m, int expected)
{
//Given
Conversion test = new Conversion();
//When
int result = test.GetBits(n, m);
//Then
Assert.Equal(expected,result);
}
}
}<file_sep>using System;
namespace DynamicProgramming.Domain
{
public class RecursiveMultiply
{
public int minProduct(int a, int b)
{
int bigger = a < b ? b : a;
int smaller = a > b ? b : a;
return minProductHelper(smaller, bigger);
}
private int minProductHelper(int smaller, int bigger)
{
if(smaller == 0) return 0;
if(smaller == 1) return 1;
int s = smaller >> 1;
int side1 = minProduct(s, bigger);
int side2 = side1;
if(smaller % 2 == 1){
side2 = minProductHelper(smaller - s, bigger);
}
return side1 + side2;
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class IsUniqueTest
{
IsUnique classIsUnique = new IsUnique();
[Fact]
public void WhenEmptyReturnTrue()
{
bool isUnique = classIsUnique.IsUniqueStr("");
{
}
Assert.True(isUnique);
}
[Theory]
[InlineData("11")]
[InlineData("1231#")]
[InlineData("#123#")]
public void WhenNotUniqueReturnFalse(string str)
{
//Given
//When
bool isUnique = classIsUnique.IsUniqueStr(str);
//Then
Assert.False(isUnique);
}
[Theory]
[InlineData("1")]
[InlineData("123#")]
[InlineData("#123")]
public void WhenUniqueReturnTrue(string str)
{
//Given
//When
bool isUnique = classIsUnique.IsUniqueStr(str);
//Then
Assert.True(isUnique);
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Collections.Generic;
namespace DynamicProgramming.Domain
{
public class GetPath
{
public List<Point> CalculatePath(bool[][] maze)
{
if(maze == null || maze.Length == 0) return null;
List<Point> path = new List<Point>();
if(CalculatePath(maze, maze.Length - 1, maze[0].Length - 1, path))
{
return path;
}
return null;
}
private bool CalculatePath(bool[][] maze, int row, int col, List<Point> path)
{
if(row < 0 || col < 0 || !maze[row][col]) return false;
bool isAtOrigin = (row == 0) && (col == 0);
if(isAtOrigin || CalculatePath(maze, row - 1, col, path) || CalculatePath(maze, row, col - 1, path)){
Point p = new Point(row, col);
path.Add(p);
return true;
}
return false;
}
}
}<file_sep>using System;
namespace StackAndQueue.Domain
{
public class ThreeInOne
{
private int numOfStack;
private int stackCapacity;
public int[] sizes;
private int[] values;
public ThreeInOne(int numOfStack, int stackCapacity)
{
this.numOfStack = numOfStack;
sizes = new int[numOfStack];
this.stackCapacity = stackCapacity;
values = new int[numOfStack * stackCapacity];
}
public void Push(int stackNum, int data)
{
if(IsFull(stackNum)){
throw new InvalidOperationException();
}
sizes[stackNum]++;
values[IndexOfTop(stackNum)] = data;
}
public int Pop(int stackNum)
{
if(IsEmpty(stackNum))
{
throw new InvalidOperationException();
}
int value = values[IndexOfTop(stackNum)];
sizes[stackNum]--;
values[IndexOfTop(stackNum)] = 0;
return value;
}
public int Peek(int stackNum)
{
if(IsEmpty(stackNum))
{
throw new InvalidOperationException();
}
int value = values[IndexOfTop(stackNum)];
return value;
}
private bool IsEmpty(int stackNum)
{
return sizes[stackNum] == 0;
}
private bool IsFull(int stackNum)
{
return sizes[stackNum] == stackCapacity;
}
private int IndexOfTop(int stackNum)
{
int offset = stackNum * stackCapacity;
int size = sizes[stackNum];
return offset + size - 1;
}
}
}<file_sep>using System;
namespace DynamicProgramming.Domain
{
public class MakeChange
{
public int CountWays(int amount, int[] denoms, int index)
{
if( index >= denoms.Length - 1) return 1;
int denomAmount = denoms[index];
int ways = 0;
for(int i=0;i * denomAmount <= amount; i++)
{
int amountRemaining = amount - i * denomAmount;
ways += CountWays(amountRemaining, denoms, index + 1);
}
return ways;
}
public int CountWays(int n){
int[] denoms = {25, 10, 5, 1};
return CountWays(n, denoms, 0);
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class SinglyLinkedListNode<T>
{
public SinglyLinkedListNode<T> next = null;
public int data;
public SinglyLinkedListNode(int data)
{
this.data = data;
}
public SinglyLinkedListNode()
{
}
public void AppendToTail(int data)
{
SinglyLinkedListNode<T> node = new SinglyLinkedListNode<T>(data);
SinglyLinkedListNode<T> n = this;
while(n.next != null)
{
n = n.next;
}
n.next = node;
}
public SinglyLinkedListNode<T> DeleteNode(SinglyLinkedListNode<T> head, int data)
{
SinglyLinkedListNode<T> n = head;
if(n.data == data){
return head.next;
}
while(n.next != null)
{
if(n.next.data == data)
{
n.next = n.next.next;
return head;
}
n = n.next;
}
return head;
}
public SinglyLinkedListNode<T> GetFirstNode(SinglyLinkedListNode<T> head, int data)
{
SinglyLinkedListNode<T> n = head;
while(n != null)
{
if(n.data == data)
{
return n;
}
n = n.next;
}
return null;
}
}
}<file_sep>using System.Collections.Generic;
namespace LinkedList.Domain
{
public class RemoveDups
{
public void RemoveDuplicates(SinglyLinkedListNode node)
{
SinglyLinkedListNode previous = null;
HashSet<int> set = new HashSet<int>();
while(node != null)
{
if(set.Contains(node.data))
{
previous.next = node.next;
}else{
previous = node;
set.Add(node.data);
}
node = node.next;
}
}
public void RemoveDuplicatesWithoutBuffer(SinglyLinkedListNode head)
{
SinglyLinkedListNode current = head;
while(current != null)
{
SinglyLinkedListNode runner = current;
while(runner.next != null)
{
if(runner.next.data == current.data)
{
current.next = runner.next.next;
}else{
runner = runner.next;
}
}
current = current.next;
}
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class RotateMatrixTest
{
RotateMatrix classRM = new RotateMatrix();
[Fact]
public void WhenNotValidReturnOriginal()
{
//Given
int[][] matrix = new int[4][];
matrix[0] = new int[3];
matrix[1] = new int[3];
matrix[2] = new int[3];
matrix[3] = new int[3];
matrix[0][0] = 0;
matrix[0][1] = 1;
matrix[0][2] = 2;
// matrix[0][3] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
// matrix[1][3] = 7;
matrix[2][0] = 8;
matrix[2][1] = 9;
matrix[2][2] = 10;
// matrix[2][3] = 11;
matrix[3][0] = 12;
matrix[3][1] = 13;
matrix[3][2] = 14;
// matrix[3][3] = 15;
//When
int[][] rotatedMatrix = classRM.rotate(matrix);
//Then
Assert.Equal(matrix,rotatedMatrix);
}
[Fact]
public void WhenValidReturnRotated()
{
//Given
int[][] matrix = new int[4][];
matrix[0] = new int[4];
matrix[1] = new int[4];
matrix[2] = new int[4];
matrix[3] = new int[4];
matrix[0][0] = 0;
matrix[0][1] = 1;
matrix[0][2] = 2;
matrix[0][3] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[1][3] = 7;
matrix[2][0] = 8;
matrix[2][1] = 9;
matrix[2][2] = 10;
matrix[2][3] = 11;
matrix[3][0] = 12;
matrix[3][1] = 13;
matrix[3][2] = 14;
matrix[3][3] = 15;
int[][] expectedMatrix = new int[4][];
expectedMatrix[0] = new int[4];
expectedMatrix[1] = new int[4];
expectedMatrix[2] = new int[4];
expectedMatrix[3] = new int[4];
expectedMatrix[0][0] = 12;
expectedMatrix[0][1] = 8;
expectedMatrix[0][2] = 4;
expectedMatrix[0][3] = 0;
expectedMatrix[1][0] = 13;
expectedMatrix[1][1] = 9;
expectedMatrix[1][2] = 5;
expectedMatrix[1][3] = 1;
expectedMatrix[2][0] = 14;
expectedMatrix[2][1] = 10;
expectedMatrix[2][2] = 6;
expectedMatrix[2][3] = 2;
expectedMatrix[3][0] = 15;
expectedMatrix[3][1] = 11;
expectedMatrix[3][2] = 7;
expectedMatrix[3][3] = 3;
//When
int[][] rotatedMatrix = classRM.rotate(matrix);
//Then
Assert.Equal(expectedMatrix,rotatedMatrix);
}
}
}<file_sep>using System;
namespace OOD.Core
{
public class BlackJack : Poker
{
private int _value;
private string _category;
public override int Value
{
get
{
if(_value == 1){
return 1;
}else{
return _value;
}
}
set
{
if(value >= 10 && value <= 13){
_value = 10;
}else if(value >= 1 && value < 10){
_value = value;
}else {
_value = -1;
}
}
}
}
}
<file_sep>using System;
namespace ArrayStudy.Domain
{
public class Permutation
{
public bool IsPermutation(string str1, string str2)
{
if(str1.Length != str2.Length)
return false;
if(str1.Length > 0)
{
str1 = SortArray(str1);
str2 = SortArray(str2);
if(str1 == str2)
{
return true;
}else{
return false;
}
}
return true;
}
private string SortArray(string str)
{
char[] content = str.ToCharArray();
Array.Sort(content);
return String.Concat(content);
}
}
}<file_sep>namespace ArrayStudy.Domain
{
public class OneAway
{
public bool IsOneEditAway(string str1, string str2)
{
if(str1.Length == 0 && str2.Length == 0)
return true;
if(str1.Length == str2.Length){
return IsOneReplacement(str1,str2);
}else if(str1.Length - str2.Length == 1){
return IsOneInsertion(str2, str1);
}else if(str1.Length - str2.Length == -1){
return IsOneInsertion(str1, str2);
}
return false;
}
private bool IsOneReplacement(string str1, string str2)
{
bool differenceFound = false;
for(int i=0; i<str1.Length;i++)
{
if(str1[i] != str2[i])
{
if(differenceFound){
return false;
}
differenceFound = true;
}
}
return differenceFound;
}
private bool IsOneInsertion(string str1, string str2)
{
int index1 = 0, index2 = 0;
while(index1 < str1.Length && index2 < str2.Length)
{
if(str1[index1] != str2[index2]){
if(index1 != index2){
return false;
}
index2++;
}else{
index1++;
index2++;
}
}
return true;
}
}
}<file_sep>using System;
namespace StackAndQueue.Domain
{
public class StackMin : MyStack<int>
{
MyStack<int> s2;
public StackMin(){
s2 = new MyStack<int>();
}
public new void Push(int value)
{
if (value <= Min())
{
s2.Push(value);
}
base.Push(value);
}
public new int Pop()
{
int value = base.Pop();
if(value == Min())
{
s2.Pop();
}
return value;
}
public int Min()
{
if(s2.IsEmpty())
{
return int.MaxValue;
} else {
return s2.Peek();
}
}
}
}<file_sep>namespace LinkedList.Domain
{
public class SumList
{
public SinglyLinkedListNode GetSum(SinglyLinkedListNode node1, SinglyLinkedListNode node2)
{
return AddList(node1,node2,0);
}
private SinglyLinkedListNode AddList(SinglyLinkedListNode node1, SinglyLinkedListNode node2, int carry)
{
SinglyLinkedListNode result = new SinglyLinkedListNode();
if(node1 == null && node2 == null && carry == 0)
{
return null;
}
int value = carry;
if(node1 != null){
value += node1.data;
}
if(node2 != null){
value += node2.data;
}
result.data = value % 10;
if(node1 != null || node2 != null){
SinglyLinkedListNode more = AddList(node1 == null ? null : node1.next,
node2 == null ? null : node2.next,
value >= 10 ? 1 : 0);
if(more != null)
{
result.AppendToTail(more.data);
}
}
return result;
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class MinimalTree
{
public TreeNode<int> CreateMinimalTreeBST(int[] array)
{
return CreateMinimalTreeBST(array, 0, array.Length - 1);
}
public TreeNode<int> CreateMinimalTreeBST(int[] array, int start, int end)
{
if(end < start)
{
return null;
}
int mid = (start + end) / 2;
TreeNode<int> n = new TreeNode<int>(array[mid]);
n.left = CreateMinimalTreeBST(array, start, mid - 1);
n.right = CreateMinimalTreeBST(array, mid + 1, end);
return n;
}
}
}<file_sep>using System;
namespace OOD.Core
{
public class Poker
{
private int _value;
private string _category;
public virtual int Value
{
get
{
return _value;
}
set
{
_value = value <= 13 && value >= 1 ? value : -1;
}
}
public virtual string Category
{
get{ return _category;}
set{ _category = value;}
}
}
}
<file_sep>using System;
using System.Text;
namespace BitManipulation.Domain
{
public class BinaryToString
{
public string ConverToString(double num)
{
if(num >= 1 || num <= 0)
{
return "ERROR";
}
StringBuilder str = new StringBuilder();
str.Append(".");
while(num > 0)
{
if(str.Length >= 32){
return "ERROR";
}
double r = num * 2;
if(r >= 1){
str.Append("1");
num = r - 1.0;
}else{
str.Append("0");
num = r;
}
}
return str.ToString();
}
}
}<file_sep>using System;
namespace ArrayStudy.Domain
{
public class ZeroMatrix
{
public bool CheckZero(int[,] matrix)
{
bool[] row = new bool[matrix.GetLength(0)];
bool[] column = new bool[matrix.GetLength(1)];
for(int i=0;i<matrix.GetLength(0);i++)
{
for(int j=0;j<matrix.GetLength(1);j++)
{
if(matrix[i,j] == 0){
row[i] = true;
column[j] = true;
}
}
}
for(int j=0;j<row.Length;j++)
{
if(row[j]) ZerofyRow(matrix, j);
}
for(int j=0;j<column.Length;j++)
{
if(column[j]) ZerofyColumn(matrix, j);
}
return true;
}
private void ZerofyRow(int[,] matrix, int row)
{
for(int j=0;j<matrix.GetLength(1);j++)
{
matrix[row,j] = 0;
}
}
private void ZerofyColumn(int[,] matrix, int column)
{
for(int j=0;j<matrix.GetLength(0);j++)
{
matrix[j,column] = 0;
}
}
}
}<file_sep>namespace LinkedList.Domain
{
public class KthToLast
{
public SinglyLinkedListNode GetKthNode(SinglyLinkedListNode head, int k)
{
return CheckQualifyNode(head,k,0);
}
public SinglyLinkedListNode CheckQualifyNode(SinglyLinkedListNode node, int k, int index)
{
if(node == null)
{
return null;
}
if(index == k)
{
return node;
}
else
{
return CheckQualifyNode(node.next,k,index+1);
}
}
}
}<file_sep>using System;
using System.Text;
namespace BitManipulation.Domain
{
public class NextNumber
{
public int GetNext(int n)
{
int c0 = 0, c1= 0, c = n;
while((c & 1) == 0 && c != 0){
c0++;
c >>= 1;
}
while((c & 1) == 1){
c1++;
c >>= 1;
}
if(c0 + c1 == 31 || c0 + c1 == 0){
return -1;
}
int p = c1 + c0;
n |= (1 << p);
n &= ~((1 << p) - 1);
n |= (1 << (c1 - 1)) - 1;
return n;
}
public int getPrev(int n) {
int temp = n;
int c0 = 0, c1 = 0;
while((temp & 1) == 1){
c1++;
temp >>= 1;
}
if(temp == 0) return -1;
while ((temp & 1) == 0 && temp != 0)
{
c0++;
temp >>= 1;
}
int p = c0 + c1; // position of rightmost non-trailing one
n &= ((~0) << (p + 1)); // clears from bit p onwards
int mask= (1 << (c1 + 1)) - 1; // Sequence of (cl+l) ones
n |= mask << (c0 - 1);
return n;
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class PermutationTest
{
Permutation classIsPermutation = new Permutation();
[Fact]
public void WhenEmptyReturnTrue()
{
bool isPermutation = classIsPermutation.IsPermutation("","");
{
}
Assert.True(isPermutation);
}
[Theory]
[InlineData("1","12")]
public void WhenNotEqualLengthReturnFalse(string str1, string str2)
{
bool isPermutation = classIsPermutation.IsPermutation(str1,str2);
//Then
Assert.False(isPermutation);
}
[Theory]
[InlineData("11","12")]
[InlineData("1231#","#2341")]
[InlineData("#123#!*&)(","*&^%$#2348")]
public void WhenNotPermutationReturnFalse(string str1,string str2)
{
//Given
//When
bool isPermutation = classIsPermutation.IsPermutation(str1,str2);
//Then
Assert.False(isPermutation);
}
[Theory]
[InlineData("123","123")]
[InlineData("123#","#321")]
[InlineData("#123$%^&*()",")(*&^%$#312")]
public void WhenUPermutationReturnTrue(string str1, string str2)
{
//Given
//When
bool isPermutation = classIsPermutation.IsPermutation(str1,str2);
//Then
Assert.True(isPermutation);
}
}
}
<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class UrlifyTest
{
Urlify classUrlify = new Urlify();
[Fact]
public void WhenEmptyReturnEmpty()
{
string result = classUrlify.UrlifyString("");
Assert.Equal("",result);
}
[Theory]
[InlineData("123","123")]
[InlineData("https://www.dmt.ca","https://www.dmt.ca")]
public void WhenNoSpaceReturnOriginal(string str, string expected)
{
string result = classUrlify.UrlifyString(str);
Assert.Equal(expected,result);
}
[Theory]
[InlineData("1 2 3","1%202%20%203")]
[InlineData("https://www.dmt.ca?value=123 456","https://www.dmt.ca?value=123%20456")]
public void WhenSpaceReturnReplaceSpace(string str,string expected)
{
string result = classUrlify.UrlifyString(str);
Assert.Equal(expected,result);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace StackAndQueue.Domain
{
public class StackPlate
{
List<MyStack<int>> stacks;
int capacity;
int size;
public StackPlate(int capacity)
{
stacks = new List<MyStack<int>>();
this.capacity = capacity;
}
public void Push(int data)
{
MyStack<int> last = GetLastStack();
if(last != null && !IsFull())
{
last.Push(data);
size++;
} else {
size = 0;
MyStack<int> stack = new MyStack<int>();
stack.Push(data);
stacks.Add(stack);
}
}
public int Pop()
{
MyStack<int> last = GetLastStack();
if(last == null)
{
throw new InvalidOperationException();
}
int v = last.Pop();
size--;
if(size == 0)
{
stacks.Remove(last);
}
return v;
}
public MyStack<int> GetLastStack()
{
if(!IsListEmpty()){
return stacks[stacks.Count - 1];
} else{
throw new InvalidOperationException();
}
}
public bool IsListEmpty()
{
return stacks.Count == 0;
}
public bool IsFull()
{
return size < capacity;
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class CheckSubTree
{
public bool IsSubTree(TreeNode<int> t1, TreeNode<int> t2)
{
if(t2 == null) return false;
return CheckIt(t1, t2);
}
public bool CheckIt(TreeNode<int> t1, TreeNode<int> t2)
{
if(t1 == null){
return false;
}else if(t1.value == t2.value && MatchTree(t1, t2)){
return true;
}
return CheckIt(t1.left, t2) || CheckIt(t1.right, t2);
}
public bool MatchTree(TreeNode<int> t1, TreeNode<int> t2)
{
if(t1 == null && t2 == null){
return true;
} else if(t1 == null || t2 == null){
return false;
} else if(t1.value != t2.value){
return false;
} else{
return MatchTree(t1.left, t2.left) && MatchTree(t1.right, t2.right);
}
}
}
}<file_sep>namespace LinkedList.Domain
{
public class SinglyLinkedListNode
{
public SinglyLinkedListNode next = null;
public int data;
public SinglyLinkedListNode(int data)
{
this.data = data;
}
public SinglyLinkedListNode()
{
}
public void AppendToTail(int data)
{
SinglyLinkedListNode node = new SinglyLinkedListNode(data);
SinglyLinkedListNode n = this;
while(n.next != null)
{
n = n.next;
}
n.next = node;
}
public SinglyLinkedListNode DeleteNode(SinglyLinkedListNode head, int data)
{
SinglyLinkedListNode n = head;
if(n.data == data){
return head.next;
}
while(n.next != null)
{
if(n.next.data == data)
{
n.next = n.next.next;
return head;
}
n = n.next;
}
return head;
}
public SinglyLinkedListNode GetFirstNode(SinglyLinkedListNode head, int data)
{
SinglyLinkedListNode n = head;
while(n != null)
{
if(n.data == data)
{
return n;
}
n = n.next;
}
return null;
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class StringRotationTest
{
StringRotation classSR = new StringRotation();
[Fact]
public void WhenEqualLengthReturnTrue()
{
//Given
bool result = classSR.isRotation("abbaa","aaabb");
//When
//Then
Assert.True(result);
}
[Fact]
public void WhenNotEqualLengthReturnFalse()
{
//Given
bool result = classSR.isRotation("abbaaa","aaabb");
//When
//Then
Assert.False(result);
//When
//Then
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class Successor
{
public TreeNode<int> FindSuccessor(TreeNode<int> root)
{
if(root == null) return null;
if(root.right != null)
{
TreeNode<int> n = root;
while(root.left != null)
{
n = n.left;
}
return n;
}else
{
TreeNode<int> q = root;
TreeNode<int> x = q.parent;
while(x != null && x.left != q)
{
q = x;
x = x.parent;
}
return x;
}
}
}
}<file_sep>namespace ArrayStudy.Domain
{
public class IsUnique
{
public bool IsUniqueStr(string str)
{
bool[] char_set = new bool[128];
for(int i = 0; i < str.Length; i++)
{
int index = str[i];
if(char_set[index])
{
return false;
}
char_set[index] = true;
}
return true;
}
}
}<file_sep>using System;
namespace StackAndQueue.Domain
{
public enum PetType
{
dog = 1,
cat = 2
}
public class Animal
{
public string name;
public int order;
public bool IsOlderThan(Animal animal)
{
return this.order < animal.order;
}
}
public class AnimalShelter
{
MyQueue<Animal> dogs;
MyQueue<Animal> cats;
int order;
public AnimalShelter()
{
dogs = new MyQueue<Animal>();
cats = new MyQueue<Animal>();
}
public void Enqueue(Animal animal, PetType type)
{
animal.order = order;
if(type == PetType.dog)
{
dogs.Add(animal);
}else{
cats.Add(animal);
}
order++;
}
public Animal DequeueAny()
{
if(dogs.IsEmpty()){
return cats.Remove();
}
else if(cats.IsEmpty()){
return dogs.Remove();
}
Animal dog = dogs.Peek();
Animal cat = cats.Peek();
return dog.IsOlderThan(cat) ? dog : cat;
}
public Animal DequeueDog()
{
return dogs.Remove();
}
public Animal DequeueCat()
{
return cats.Remove();
}
}
}<file_sep>using Xunit;
using BitManipulation.Domain;
namespace BitManipulation.Test
{
public class FlipBitToWinTest
{
[Theory]
[InlineData(11,3)]
public void TestIt(int num, int expected)
{
//Given
FlipBitToWin test = new FlipBitToWin();
//When
int result = test.FindLongestSequence(num);
//Then
Assert.Equal(expected,result);
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class RouteBetweenNodes
{
enum State
{
Unvisited = 0,
Visited = 1,
Visting = 2
}
public bool Search(Graph<int> g, Node<int> start, Node<int> end)
{
if (start == end) return true;
MyQueue<Node<int>> q = new MyQueue<Node<int>>();
foreach (Node<int> child in g.nodes)
{
child.state = (int)State.Unvisited;
}
start.state = (int)State.Visting;
q.Add(start);
Node<int> u;
while(!q.IsEmpty())
{
u = q.Remove();
if(u != null)
{
foreach (Node<int> child in u.children)
{
if (child.state == (int)State.Unvisited)
{
if(child == end)
{
return true;
}else{
child.state = (int)State.Visting;
q.Add(child);
}
}
}
u.state = (int)State.Visited;
}
}
return false;
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class Graph<T>
{
public Node<T>[] nodes;
public Node<T> GetNode()
{
return new Node<T>();
}
public Node<T> DFSGetNode(Node<T> root, Node<T> target)
{
if(root == null) return null;
if(root == target) return root;
root.visited = true;
foreach (Node<T> child in root.children)
{
if(!child.visited)
{
return DFSGetNode(child,target);
}
}
return null;
}
public Node<T> BFSGetNode(Node<T> root, Node<T> target)
{
MyQueue<Node<T>> queue = new MyQueue<Node<T>>();
root.visited = true;
queue.Add(root);
while(!queue.IsEmpty())
{
Node<T> r = queue.Remove();
if(r == target) return r;
foreach (Node<T> child in r.children)
{
if(!child.visited)
{
child.visited = true;
queue.Add(child);
}
}
}
return null;
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class ValidateBST
{
int index = 0;
public void CopyBST(TreeNode<int> root, int[] array)
{
if(root == null) return;
CopyBST(root.left, array);
array[index] = root.value;
index++;
CopyBST(root.right, array);
}
public bool CheckBST(TreeNode<int> root, Graph<int> graph)
{
int[] array = new int[graph.nodes.Length];
CopyBST(root, array);
for(int i = 1; i < array.Length; i ++)
{
if(array[i] < array[i - 1]) return false;
}
return true;
}
}
}<file_sep>using Xunit;
using LinkedList.Domain;
namespace LinkedList.Test
{
public class RemoveDupsTest
{
RemoveDups classRD = new RemoveDups();
[Fact]
public void RemoveDuplicateTest()
{
//Given
SinglyLinkedListNode node = new SinglyLinkedListNode(1);
node.AppendToTail(1);
node.AppendToTail(2);
node.AppendToTail(3);
node.AppendToTail(4);
node.AppendToTail(4);
//When
classRD.RemoveDuplicates(node);
//Then
int[] seq = {1,2,3,4};
int index = 0;
while(node != null)
{
Assert.Equal(seq[index],node.data);
index++;
node = node.next;
}
}
[Fact]
public void RemoveDuplicateWithOutBufferTest()
{
//Given
SinglyLinkedListNode node = new SinglyLinkedListNode(1);
node.AppendToTail(1);
node.AppendToTail(2);
node.AppendToTail(3);
node.AppendToTail(4);
node.AppendToTail(4);
node.AppendToTail(4);
//When
classRD.RemoveDuplicatesWithoutBuffer(node);
//Then
int[] seq = {1,2,3,4};
int index = 0;
while(node != null)
{
Assert.Equal(seq[index],node.data);
index++;
node = node.next;
}
}
}
}<file_sep>using Xunit;
using LinkedList.Domain;
namespace LinkedList.Test
{
public class IntersectionTest
{
Intersection classI = new Intersection();
[Fact]
public void WhenEmtptyReturnNull()
{
//Given
SinglyLinkedListNode node1 = null;
SinglyLinkedListNode node2 = new SinglyLinkedListNode();
//When
SinglyLinkedListNode result = classI.GetIntersection(node1, node2);
//Then
Assert.True(AreSame(null,result));
}
[Fact]
public void WhenIntersectReturnNode()
{
//Given
SinglyLinkedListNode node1 = new SinglyLinkedListNode(7);
SinglyLinkedListNode node2 = new SinglyLinkedListNode(12);
node1.AppendToTail(6);
node1.AppendToTail(5);
node1.AppendToTail(4);
node1.AppendToTail(3);
node1.AppendToTail(2);
node1.AppendToTail(1);
SinglyLinkedListNode intersection = node1.GetFirstNode(node1,4);
node2.AppendToTail(11);
SinglyLinkedListNode nodeTail = node2.GetFirstNode(node2, 11);
nodeTail.next = intersection;
//When
SinglyLinkedListNode result = classI.GetIntersection(node1, node2);
//Then
Assert.True(AreSame(intersection,result));
}
[Fact]
public void WhenNotIntersectReturnNull()
{
//Given
SinglyLinkedListNode node1 = new SinglyLinkedListNode(7);
SinglyLinkedListNode node2 = new SinglyLinkedListNode(12);
node1.AppendToTail(6);
node1.AppendToTail(5);
node1.AppendToTail(4);
node2.AppendToTail(6);
node2.AppendToTail(5);
node2.AppendToTail(4);
//When
SinglyLinkedListNode result = classI.GetIntersection(node1, node2);
//Then
Assert.True(AreSame(null,result));
}
private static bool AreSame(SinglyLinkedListNode node1, SinglyLinkedListNode node2)
{
return node1 == node2;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace DynamicProgramming.Domain
{
public class BoxStack
{
public int CreateStack(List<Box> boxes)
{
boxes.Sort(new BoxComparator());
int maxHeight = 0;
int[] stackMap = new int[boxes.Count];
for(int i=0;i < boxes.Count; i++)
{
int height = CreateStack(boxes, i, stackMap);
maxHeight = Math.Max(maxHeight, height);
}
return maxHeight;
}
public int CreateStack(List<Box> boxes, int bottomIndex, int[] stackMap)
{
if(bottomIndex < boxes.Count && stackMap[bottomIndex] > 0){
return stackMap[bottomIndex];
}
Box bottom = boxes[bottomIndex];
int maxHeight = 0;
for(int i = bottomIndex + 1; i < boxes.Count; i++)
{
if(boxes[i].CanBeAbove(bottom)){
int height = CreateStack(boxes, i, stackMap);
maxHeight = Math.Max(height, maxHeight);
}
}
maxHeight += bottom.Height;
stackMap[bottomIndex] = maxHeight;
return maxHeight;
}
}
public class Box
{
public int Height;
public int Width;
public int Depth;
public bool CanBeAbove(Box box){
return this.Height > box.Height && this.Width > box.Width && this.Depth > box.Depth;
}
}
public class BoxComparator : IComparer<Box>
{
public int Compare(Box x, Box y)
{
return y.Height - x.Height;
}
}
}<file_sep>using System;
using System.Text;
namespace BitManipulation.Domain
{
public class FlipBitToWin
{
public int FindLongestSequence(int num)
{
if(~num == 0) return 4 * 8;
int currentLength = 0;
int previousLength = 0;
int maxLength = 1;
while(num != 0)
{
if((num & 1) == 1){
currentLength++;
}else if((num & 1) == 0){
currentLength = 0;
previousLength = (num & 2) == 0 ? 0 : currentLength;
}
maxLength = Math.Max(previousLength + currentLength + 1, maxLength);
num >>= 1;
}
return maxLength;
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class OneAwayTest
{
OneAway classOneAway = new OneAway();
[Fact]
public void WhenEmptyReturnTrue()
{
//Given
bool result = classOneAway.IsOneEditAway("","");
//When
//Then
Assert.True(result);
}
[Theory]
[InlineData("str1","str234")]
[InlineData("str123","str123145")]
public void WhenMultipleDifferenceReturnFalse(string str1, string str2)
{
//Given
bool result = classOneAway.IsOneEditAway(str1,str2);
//When
//Then
Assert.False(result);
}
[Theory]
[InlineData("str1","str2",true)]
[InlineData("str123,","str2345",false)]
public void WhenSameLengthReturnResult(string str1, string str2, bool expected)
{
bool result = classOneAway.IsOneEditAway(str1, str2);
//When
//Then
Assert.Equal(expected,result);
}
[Theory]
[InlineData("str1","str13",true)]
[InlineData("str123,","str23,",true)]
[InlineData("!str1","str1",true)]
[InlineData("!str1","str2",false)]
public void WhenOneLengthDifferenceReturnResult(string str1, string str2, bool expected)
{
bool result = classOneAway.IsOneEditAway(str1, str2);
//When
//Then
Assert.Equal(expected,result);
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class PalindromePermutationTest
{
PalindromePermutation classPalindrome = new PalindromePermutation();
[Fact]
public void WhenEmptyReturnTrue()
{
bool result = classPalindrome.IsPalindrome("");
Assert.True(result);
}
[Theory]
[InlineData("abcbac")]
[InlineData("ccddeeffgg")]
public void WhenNoOddReturnTrue(string str)
{
bool result = classPalindrome.IsPalindrome(str);
Assert.True(result);
}
[Theory]
[InlineData("abcbacd")]
[InlineData("ccddeeffggh")]
public void WhenOneOddReturnTrue(string str)
{
bool result = classPalindrome.IsPalindrome(str);
Assert.True(result);
}
[Theory]
[InlineData("abcbacde")]
[InlineData("ccddeeffgghhiok")]
public void WhenMultipleOddReturnFalse(string str)
{
bool result = classPalindrome.IsPalindrome(str);
Assert.False(result);
}
}
}
<file_sep>using System;
using System.Text;
namespace BitManipulation.Domain
{
public class Conversion
{
public int GetBits(int n, int m)
{
int bits = 0;
for(int c = n ^ m; c != 0; c >>= 1)
{
bits += c & 1;
}
return bits;
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace DynamicProgramming.Domain
{
public class Paren
{
public List<string> GenerateParens(int remaining)
{
List<string> set = new List<string>();
if(remaining == 0){
set.Add("");
}else{
List<string> prev = GenerateParens(remaining - 1);
foreach (string str in prev)
{
for(int i=0; i < str.Length; i++)
{
if(str[i] == '('){
string s = InsertInside(str, i);
if(!set.Contains(s)){
set.Add(s);
}
}
}
set.Add("()" + str);
}
}
return set;
}
public string InsertInside(string str, int index)
{
string left = str.Substring(0, index + 1);
string right = str.Substring(index + 1);
return left + "()" + right;
}
}
}<file_sep>namespace LinkedList.Domain
{
public class Partition
{
public SinglyLinkedListNode TryPartition(SinglyLinkedListNode node, int x)
{
SinglyLinkedListNode head = node;
SinglyLinkedListNode tail = node;
while (node != null)
{
SinglyLinkedListNode next = node.next;
if (node.data < x)
{
/* Ins ert node at head. */
node.next = head;
head = node;
}
else
{
tail.next = node;
tail = node;
}
node = next;
}
tail.next = null;
return head;
}
}
}<file_sep>using System;
namespace StackAndQueue.Domain
{
public class SortStack
{
MyStack<int> stack;
MyStack<int> tempStack;
int temp;
int size;
public SortStack(MyStack<int> stack)
{
this.stack = stack;
}
public bool Sort()
{
if (stack.IsEmpty()) return false;
while (!stack.IsEmpty())
{
int top = stack.Pop();
while (!tempStack.IsEmpty() && tempStack.Peek() > top)
{
stack.Push(tempStack.Pop());
}
tempStack.Push(top);
}
while(!tempStack.IsEmpty())
{
stack.Push(tempStack.Pop());
}
return true;
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class Node<T>
{
public string name;
public bool visited;
public int state;
public Node<T>[] children;
}
}<file_sep>using System;
namespace TreeAndGraph.Domain
{
public class CheckBalanced
{
public bool IsABalancedTree(TreeNode<int> root)
{
if(root == null) return true;
int heightDiff = GetHeight(root.left) - GetHeight(root.right);
if(Math.Abs(heightDiff) > 1)
{
return false;
}else{
return IsABalancedTree(root.left) && IsABalancedTree(root.right);
}
}
public int GetHeight(TreeNode<int> root)
{
if(root == null) return - 1;
return Math.Max(GetHeight(root.left), GetHeight(root.right)) + 1;
}
}
}<file_sep>using System.Collections.Generic;
namespace TreeAndGraph.Domain
{
public class ListOfDepth
{
public List<SinglyLinkedListNode<TreeNode<int>>> CreateLevelLinkedList(TreeNode<int> root)
{
List<SinglyLinkedListNode<TreeNode<int>>> lists = new List<SinglyLinkedListNode<TreeNode<int>>>();
CreateLevelLinkedList(root, lists, 0);
return lists;
}
public void CreateLevelLinkedList(TreeNode<int> root, List<SinglyLinkedListNode<TreeNode<int>>> lists, int level)
{
if (root == null) return;
SinglyLinkedListNode<TreeNode<int>> list = null;
if(lists.Count == level)
{
list = new SinglyLinkedListNode<TreeNode<int>>();
lists.Add(list);
}else{
list = lists[level];
}
list.AppendToTail(root.value);
CreateLevelLinkedList(root.left, lists, level + 1);
CreateLevelLinkedList(root.right, lists, level + 1);
}
}
}<file_sep>namespace TreeAndGraph.Domain
{
public class TreeNode<T>
{
public int value;
public TreeNode<T> left;
public TreeNode<T> right;
public TreeNode<T> parent;
public int size;
public TreeNode()
{
}
public TreeNode(int value)
{
this.value = value;
size = 1;
}
public virtual TreeNode<T> GetRandomNode()
{
return null;
}
public virtual void InsertInOrder(int d)
{
}
public virtual TreeNode<T> Find(int d)
{
return null;
}
}
}<file_sep>using System;
namespace TreeAndGraph.Domain
{
public class CommonAncestor
{
public TreeNode<int> GetCommonAncestor(TreeNode<int> p, TreeNode<int> q)
{
int pDepth = Depth(p);
int qDepth = Depth(q);
int delta = pDepth - qDepth;
TreeNode<int> first = delta > 0 ? q : p;
TreeNode<int> second = delta > 0 ? p : q;
second = GoUpBy(second, Math.Abs(delta));
while(first != second && first != null && second != null)
{
first = first.parent;
second = second.parent;
}
return first == null || second == null ? null : first;
}
public TreeNode<int> GoUpBy(TreeNode<int> node, int delta)
{
while(delta > 0 && node != null)
{
node = node.parent;
delta--;
}
return node;
}
public int Depth(TreeNode<int> node)
{
int depth = 0;
while(node != null)
{
node = node.parent;
depth++;
}
return depth;
}
public TreeNode<int> GetCommonAncestor(TreeNode<int> root, TreeNode<int> p, TreeNode<int> q)
{
if(!Covers(root, q) || !Covers(root, p))
{
return null;
}
return AncestorHelper(root, p, q);
}
public TreeNode<int> AncestorHelper(TreeNode<int> root, TreeNode<int> p, TreeNode<int> q)
{
if(root == null || p == null || q == null)
{
return null;
}
bool pIsOnLeft = Covers(root.left, p);
bool qIsOnRight = Covers(root.right, q);
if(pIsOnLeft != qIsOnRight){
return root;
}
TreeNode<int> childSide = pIsOnLeft ? root.left : root.right;
return AncestorHelper(childSide, p, q);
}
public bool Covers(TreeNode<int> root, TreeNode<int> node)
{
if(root == null) return false;
if(root == node) return true;
return Covers(root.left, node) || Covers(root.right, node);
}
}
}<file_sep>using System;
using Xunit;
using ArrayStudy.Domain;
namespace ArrayStudy.Test
{
public class ZeroMatrixTest
{
ZeroMatrix classZM = new ZeroMatrix();
[Fact]
public void TestZeroMatrix()
{
int[,] matrix = new int[4,4];
bool result = classZM.CheckZero(matrix);
Assert.True(result);
}
}
}<file_sep>using System.Linq;
namespace ArrayStudy.Domain
{
public class Urlify
{
public string UrlifyString(string str)
{
if (str != "")
{
char[] originalStr = str.ToCharArray();
int spaceCount = originalStr.Where(x=>string.Equals(x,' ')).Count();
char[] content = new char[str.Length + spaceCount * 2];
int index = 0;
for (int i = 0; i < str.Length; i++)
{
if(string.Equals(str[i], ' ')){
content[index] = '%';
content[index+1] = '2';
content[index+2] = '0';
index += 3;
}else{
content[index] = str[i];
index++;
}
}
return string.Concat(content);
}
return "";
}
}
}
<file_sep>namespace ArrayStudy.Domain
{
public class StringCompression
{
public string CompressString(string originalString)
{
string compressedStr = "";
int count = 0;
for(int i=0;i<originalString.Length;i++)
{
count++;
if(i + 1 >= originalString.Length || originalString[i] != originalString[i+1])
{
compressedStr += "" + originalString[i] + count;
count = 0;
}
}
return compressedStr.Length >= originalString.Length ? originalString : compressedStr;
}
}
}<file_sep>namespace DynamicProgramming.Domain
{
public class TripleStep
{
public int CountWays(int n)
{
int[] memo = new int[n + 1];
for(int i=0;i<memo.Length;i++){
memo[i] = -1;
}
return CountWays(n, memo);
}
private int CountWays(int n, int[] memo)
{
if(n < 0){
return 0;
}else if(n == 0){
return 1;
}else if(memo[n] > -1){
return memo[n];
}else{
memo[n] = CountWays(memo[n - 1], memo) + CountWays(memo[n - 2], memo) + CountWays(memo[n - 3], memo);
return memo[n];
}
}
}
}<file_sep>using System.Collections.Generic;
namespace LinkedList.Domain
{
public class Palindrome
{
public bool IsPalindrome(SinglyLinkedListNode node)
{
SinglyLinkedListNode slow = node, fast = node;
Stack<int> stack = new Stack<int>();
while(fast != null && fast.next != null)
{
stack.Push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
if(fast != null){
slow = slow.next;
}
while(slow != null)
{
int stored = stack.Pop();
if(stored != slow.data){
return false;
}
slow = slow.next;
}
return true;
}
}
}<file_sep>using System;
using System.Text;
namespace BitManipulation.Domain
{
public class DrawLine
{
public void FillBits(byte[] screen, int width, int x1, int x2, int y)
{
int start_offset = x1 % 8;
int start_full_byte = x1 / 8;
// if(start_offset != 0){
// start_full_byte++;
// }
int end_offset = x2 % 8;
int end_full_byte = x2 / 8;
// if(end_offset != 7){
// end_full_byte--;
// }
for(int b = start_full_byte; b < end_full_byte; b++)
{
screen[(width/8) * y + b] = (byte)0xff;
}
int start_mask = (byte) (0xff >> start_offset);
int end_mask = (byte) ~(0xff >> (end_offset + 1));
screen[(width/8) * y + start_full_byte] |= (byte)start_mask;
screen[(width/8) * y + end_full_byte] |= (byte)end_mask;
}
}
}<file_sep>namespace ArrayStudy.Domain
{
public class PalindromePermutation
{
public bool IsPalindrome(string str)
{
if(str.Length > 0 )
{
bool IsEvenDigital = str.Length % 2 == 0 ? true : false;
int[] table = BuildDictionary(str);
return CheckOneMaxOdd(table);
}
return true;
}
private int GetCharNumber(char c)
{
int a = (int)'a';
int z = (int)'z';
int val = (int)c;
if( a <= val && val <= z){
return val - a;
}
return -1;
}
private int[] BuildDictionary(string str)
{
int[] table = new int[(int)'z' - (int)'a' + 1];
char[] originalStr = str.ToCharArray();
for (int i = 0; i < originalStr.Length; i ++)
{
int x = GetCharNumber(originalStr[i]);
if(x > -1){
table[x]++;
}
}
return table;
}
private bool CheckOneMaxOdd(int[] table)
{
int count = 0;
for (int i = 0; i < table.Length; i ++)
{
if(table[i] % 2 == 1)
{
if(count >= 1){
return false;
}
count += 1;
}
}
return true;
}
}
} | 083c4026879060f5765321d4478113d344d0b145 | [
"Markdown",
"C#"
] | 84 | C# | dtfirewind/Algorithm | 493276205456ba689eb21663b5413377770b746f | a9b64a4b7aca60ebf94dd38f4855e416005804ac |
refs/heads/master | <repo_name>React-Moon/todoList<file_sep>/frontend/src/template/menu.jsx
import React from 'react'
import { Navbar, Nav } from 'react-bootstrap'
export default props => (
<div>
<Navbar bg="purple" variant="dark">
{/* Logo menu */}
<Navbar.Brand href="todos">
<i className="fa fa-calendar-check-o" ></i>
TodoApp
</Navbar.Brand>
{/* menu body */}
<Nav className="mr-auto">
<Nav.Link href="todos" >Todo</Nav.Link>
<Nav.Link href="About">About</Nav.Link>
</Nav>
</Navbar>
</div>
)
<file_sep>/frontend/src/template/buttonCustom.jsx
import React from 'react'
import If from './if'
import { Button } from 'react-bootstrap'
export default props => {
return(
<If noHide={!props.done} >
<Button variant={props.variant} className={`fa fa-${props.icon} ${props.classes}`}
size={props.size} onClick={props.onClick}></Button>
</If>
)
}
<file_sep>/frontend/src/template/pageHeader.jsx
import React from 'react'
import { Card } from 'react-bootstrap'
export default props => (
<Card.Header>
<Card.Title>{props.name} <span className="mb-2 text-muted">{props.small}</span></Card.Title>
</Card.Header >
)<file_sep>/frontend/src/todo/todoForm.jsx
import React from 'react'
import { Container, Row, Col, Button, FormControl, InputGroup } from 'react-bootstrap'
export default props => {
const keyHandler = (e) => {
if (e.key === 'Enter') {
e.shiftKey ? props.handleSearch() : props.handleAdd()
}else if (e.key === 'Escape') {
props.handleClear()
}
}
return (
<div role='form' className='todoForm'>
<Container>
<Row>
<Col md='7' >
<InputGroup>
<FormControl type="text" className="form-control"
onChange={props.handleChange}
onKeyUp={keyHandler}
placeholder="Adicione uma tarefa" value={props.description} />
</InputGroup>
</Col>
<Col md='5'>
<Button variant='primary' className='fa fa-plus btnCustom'
onClick={props.handleAdd}>
</Button>
<Button variant='info' className='fa fa-search btnCustom'
onClick={props.handleSearch} >
</Button>
<Button variant='dark' className='fa fa-close btnCustom'
onClick={props.handleClear} >
</Button>
</Col>
</Row>
</Container>
</div>
)}<file_sep>/README.md
<h1 align="center">
<img alt="Jonathan's" src="https://i.pinimg.com/originals/52/1a/fa/521afaada5d1c270249703e2420fbbb3.png" />
<br>
Todo List - ReactJs
</h1>
<p align="center">
<img alt="GitHub top language" src="https://img.shields.io/github/languages/top/React-Moon/todoList.svg">
<img alt="GitHub language count" src="https://img.shields.io/github/languages/count/React-Moon/todoList.svg">
<img alt="Repository size" src="https://img.shields.io/github/repo-size/React-Moon/todoList.svg">
<a href="https://github.com/React-Moon/todoList/commits/master">
<img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/React-Moon/todoList.svg">
</a>
<a href="https://github.com/React-Moon/todoList/issues">
<img alt="Repository issues" src="https://img.shields.io/github/issues/React-Moon/todoList.svg">
</a>
<p align="center">
<a href="#Moon-technologies">Technologies</a> |
<a href="#information_source-how-to-use">How To Use</a> |
<a href="#memo-license">License</a>
</p>
<p align="center">
<img src="https://github.com/JonathansMoon/files/blob/master/images/todoList.jpg">
</p>
## :computer: Technologies
This project was developed at the [Jonathan's Moon](#) with the following technologies:
- [reactjs](https://pt-br.reactjs.org/)
- [nodejs](https://nodejs.org/en/download/)
- [mogodb](https://www.mongodb.com/)
- [mongoosejs](https://mongoosejs.com/)
- [Bootstrap](https://getbootstrap.com/)
- [docker](https://www.docker.com/)
- [css](https://developer.mozilla.org/pt-BR/docs/Web/CSS)
- [axios](https://github.com/axios/axios)
- [VS Code][vc]
## :information_source: How To Use
To clone and run this application, you'll only need [Docker](https://www.docker.com/) installed on your computer. From your command line:
```bash
# Clone this repository
$ git clone https://github.com/React-Moon/todoList.git
# Go into the repository
$ cd todoList/backend
# Run the command to mongodb image on the docker
$ docker-compose up
# Run the command to install modules
$ yarn install
# Run the command to run nodejs
$ yarn dev
# Go into the repository
$ cd todoList/frontend
# Run the command to install modules
$ yarn install
# Run the command to run reactjs
$ yarn start
```
## :memo: License
This project is under the MIT license.
Made with ♥ by <NAME> :wave: [Get in touch!](https://www.linkedin.com/in/jonathan-silva-gomes-53271a168/)
[vc]: https://code.visualstudio.com/
<file_sep>/frontend/src/about/about.jsx
import React from 'react'
import PageHeader from '../template/pageHeader'
import { Jumbotron, Container } from 'react-bootstrap'
export default props => (
<div>
<Jumbotron className="text-center bg-white shadow">
<h4 className="font-weight-bold">About us</h4>
<Container>
<p className="lead font-italic">Something short and leading about the collection below—its contents, the creator, etc. Make it short and sweet, but not too short so folks don't simply skip over it entirely.</p>
</Container>
</Jumbotron>
</div>
) | fe44c41961ba15dff8c080bef065a72b0ec6a8cd | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | React-Moon/todoList | 168bdecda2fc19dbce1e2b1d5b2b197e94841d2a | 1a4b85046d56a0f4010d1457179f428ae4011618 |
refs/heads/master | <repo_name>BenSlabbert/java-sonic<file_sep>/src/test/java/com/github/twohou/sonic/IntegrationTest.java
/*
* This Java source file was generated by the Gradle "init" task.
*/
package com.github.twohou.sonic;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.testcontainers.containers.BindMode;
import org.testcontainers.containers.GenericContainer;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class IntegrationTest {
private static final org.slf4j.Logger log =
org.slf4j.LoggerFactory.getLogger(IntegrationTest.class);
@Rule
public GenericContainer sonic =
new GenericContainer<>("valeriansaliou/sonic:v1.2.3")
.withClasspathResourceMapping("sonic.cfg", "/etc/sonic.cfg", BindMode.READ_ONLY)
.withExposedPorts(1491);
private final String collection = "messages";
private final String bucket = "default";
private IngestChannel ingest;
private SearchChannel search;
private ControlChannel control;
@Before
public void setUp() throws IOException {
// init channels
String address = sonic.getContainerIpAddress();
Integer port = sonic.getMappedPort(1491);
String password = "<PASSWORD>";
Integer connectionTimeout = 5000;
Integer readTimeout = 5000;
ChannelFactory factory =
new ChannelFactory(address, port, password, connectionTimeout, readTimeout);
ingest = factory.newIngestChannel();
search = factory.newSearchChannel();
control = factory.newControlChannel();
// index
ingest.ping();
ingest.push(
collection,
bucket,
"1",
"MPs are starting to debate the process of voting on their preferred Brexit options, as <NAME> prepares to meet Tory backbenchers in an effort to win them over to her agreement.");
ingest.push(
collection,
bucket,
"2",
"A shadowy group committed to ousting North Korea\"s leader Kim Jong-un has claimed it was behind a raid last month at the North Korean embassy in Spain.");
ingest.push(
collection,
bucket,
"3",
"<NAME>, the former Chinese head of Interpol, will be prosecuted in his home country for allegedly taking bribes, China\"s Communist Party says.");
ingest.push(
collection,
bucket,
"4",
"A Chinese student who was violently kidnapped by a stun-gun toting gang of masked men in Canada has been found safe and well, police say.");
// save to disk
control.consolidate();
}
@After
public void cleanUp() throws IOException {
log.info("Cleaning up");
ingest.flushc(collection);
ingest.flushb(collection, bucket);
ingest.flusho(collection, bucket, "1");
Integer resp = ingest.count(collection);
assertEquals(Integer.valueOf(0), resp);
resp = ingest.count(collection, bucket);
assertEquals(Integer.valueOf(0), resp);
resp = ingest.count(collection, bucket, "1");
assertEquals(Integer.valueOf(0), resp);
ingest.quit();
search.quit();
control.quit();
}
@Test
public void testIntegration() throws IOException {
Integer resp = ingest.count(collection);
log.info("Count collection: {}", resp);
assertEquals(1, resp.intValue());
resp = ingest.count(collection, bucket);
assertEquals(53, resp.intValue());
resp = ingest.count(collection, bucket, "1");
assertEquals(16, resp.intValue());
// search
search.ping();
List<String> responses = search.query(collection, bucket, "debate");
assertEquals("1", responses.get(0));
responses = search.query(collection, bucket, "Chinese");
responses.sort(String::compareTo);
assertEquals("3", responses.get(0));
assertEquals("4", responses.get(1));
responses = search.query(collection, bucket, "xxx");
assertTrue(responses.isEmpty());
responses = search.suggest(collection, bucket, "There");
assertEquals("theresa", responses.get(0));
responses = search.suggest(collection, bucket, "Hong");
assertEquals("hongwei", responses.get(0));
}
}
<file_sep>/src/main/java/com/github/twohou/sonic/SonicException.java
package com.github.twohou.sonic;
public class SonicException extends RuntimeException {
public SonicException(String message) {
super(message);
}
public SonicException(String message, Throwable cause) {
super(message, cause);
}
public SonicException(Throwable cause) {
super(cause);
}
public SonicException(
String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
<file_sep>/src/main/java/com/github/twohou/sonic/SearchChannel.java
package com.github.twohou.sonic;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class SearchChannel extends Channel {
public SearchChannel(
@NonNull String address,
@NonNull Integer port,
@NonNull String password,
@NonNull Integer connectionTimeout,
@NonNull Integer readTimeout)
throws IOException {
super(address, port, password, connectionTimeout, readTimeout);
this.start(Mode.search);
}
public List<String> query(
@NonNull String collection,
@NonNull String bucket,
@NonNull String terms,
Integer limit,
Integer offset)
throws IOException {
String q =
String.format(
"%s %s %s \"%s\"%s%s",
SearchType.QUERY.name(),
collection,
bucket,
terms,
limit != null ? String.format(" LIMIT(%d)", limit) : "",
offset != null ? String.format(" OFFSET(%d)", offset) : "");
log.debug("Sonic QUERY: {}", q);
this.send(q);
String queryId = assertPendingSearch();
return assertSearchResults(SearchType.QUERY, queryId);
}
public List<String> query(
@NonNull String collection, @NonNull String bucket, @NonNull String terms)
throws IOException {
return query(collection, bucket, terms, null, null);
}
public List<String> suggest(
@NonNull String collection, @NonNull String bucket, @NonNull String word, Integer limit)
throws IOException {
String s =
String.format(
"%s %s %s \"%s\"%s",
SearchType.SUGGEST.name(),
collection,
bucket,
word,
limit != null ? String.format(" LIMIT(%d)", limit) : "");
log.debug("Sonic SUGGEST: {}", s);
this.send(s);
String searchId = assertPendingSearch();
return assertSearchResults(SearchType.SUGGEST, searchId);
}
public List<String> suggest(
@NonNull String collection, @NonNull String bucket, @NonNull String word) throws IOException {
return suggest(collection, bucket, word, null);
}
/**
* Return pending search ID or throw an exception when the prompt message isn't expected.
*
* @return pending search ID
*/
private String assertPendingSearch() throws IOException {
String line = this.readLine();
log.debug("Sonic PENDING RESPONSE: {}", line);
Matcher matcher = Pattern.compile("^PENDING ([a-zA-Z0-9]+)$").matcher(line);
if (!matcher.find()) {
throw new SonicException("unexpected prompt: " + line);
}
return matcher.group(1);
}
private List<String> assertSearchResults(SearchType searchType, String searchId)
throws IOException {
String line = this.readLine();
log.debug("Sonic EVENT RESPONSE: {}", line);
Matcher matcher =
Pattern.compile("^EVENT " + searchType.name() + " " + searchId + " (.+)?$").matcher(line);
if (!matcher.find()) {
throw new SonicException("Unexpected prompt: " + line);
}
if (matcher.groupCount() != 1 || matcher.group(1) == null) {
return Collections.emptyList();
}
String[] searchResults = matcher.group(1).split(" ");
return Arrays.asList(searchResults);
}
}
<file_sep>/build.gradle
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: "maven"
sourceCompatibility = 11
group = "io.github.benslabbert"
version = "1.1.2-SNAPSHOT"
repositories {
mavenLocal()
jcenter()
maven {
url = uri("https://repo.gradle.org/gradle/libs")
}
}
dependencies {
compile "org.slf4j:slf4j-api:1.7.21"
compile "ch.qos.logback:logback-classic:1.1.7"
compileOnly "org.projectlombok:lombok:1.16.8"
annotationProcessor 'org.projectlombok:lombok:1.18.10'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
testCompile "org.testcontainers:testcontainers:1.12.2"
}
<file_sep>/src/main/java/com/github/twohou/sonic/ControlChannel.java
package com.github.twohou.sonic;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
@Slf4j
public class ControlChannel extends Channel {
public ControlChannel(
@NonNull String address,
@NonNull Integer port,
@NonNull String password,
@NonNull Integer connectionTimeout,
@NonNull Integer readTimeout)
throws IOException {
super(address, port, password, connectionTimeout, readTimeout);
this.start(Mode.control);
}
public void consolidate() throws IOException {
String t = "TRIGGER consolidate";
log.debug("Sonic TRIGGER: {}", t);
this.send(t);
this.assertOK();
}
}
<file_sep>/README.md
# java-sonic
[](https://jitpack.io/#BenSlabbert/java-sonic)
[](https://travis-ci.com/BenSlabbert/java-sonic)
Java client library of [Sonic search](https://github.com/valeriansaliou/sonic/)
## Compatibility
Tested under Ubuntu Trusty with:
- openjdk11
## Install
### Gradle
Step 1. Add it in your root build.gradle at the end of repositories:
```groovy
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```
Step 2. Add the dependency
```groovy
dependencies {
implementation 'com.github.twohou:java-sonic:1.0.1'
}
```
### Maven
Step 1. Add the JitPack repository to your build file
```xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
```
Step 2. Add the dependency
```xml
<dependency>
<groupId>com.github.twohou</groupId>
<artifactId>java-sonic</artifactId>
<version>1.0.1</version>
</dependency>
```
## Usage
See [example](./src/test/java/com/github/twohou/sonic/IntegrationTest.java)
| ad6d6cf31d49a1b5c4294414dc809e25c62032c4 | [
"Markdown",
"Java",
"Gradle"
] | 6 | Java | BenSlabbert/java-sonic | ee42d5c81785807d5ffe1ba0959b3bd4f24d8b4d | 7c41a6421a1baae883f0c8145d7b23baf7bb0b8f |
refs/heads/main | <repo_name>ZYCGary/code-challenge<file_sep>/app/Http/Controllers/Api/CarController.php
<?php
namespace App\Http\Controllers\Api;
use GuzzleHttp\Client;
use Exception;
use Http;
use Illuminate\Http\Request;
class CarController extends Controller
{
public function index()
{
try {
$url = "https://www.imintheright.com.au/devtest/get-vehicle-make-list.php";
$response = Http::get($url);
$cars = json_decode($response->body());
return response()->json($cars);
} catch (Exception $exception) {
return response(500);
}
}
}
<file_sep>/routes/api.php
<?php
use App\Http\Controllers\Api\CarController;
use App\Http\Controllers\Api\CustomerController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::name('api.')
->namespace('Api')
->group(function () {
Route::post('/customers', [CustomerController::class, 'store'])->name('customers.store');
Route::get('/customers', [CustomerController::class, 'index'])->name('customers.index');
Route::get('/cars', [CarController::class, 'index'])->name('cars.index');
});
<file_sep>/app/Http/Controllers/Api/CustomerController.php
<?php
namespace App\Http\Controllers\Api;
use App\Filters\CustomerFilter;
use App\Http\Requests\CustomerRequest;
use App\Models\Customer;
use Exception;
use Illuminate\Http\JsonResponse;
class CustomerController extends Controller
{
public function store(CustomerRequest $request, Customer $customer)
{
try {
$customer->name = $request->input('name');
$customer->mobile = $request->input('mobile');
$customer->email = $request->input('email');
$customer->country_id = $request->input('country');
$customer->active = $request->input('active');
$customer->save();
return response(200);
} catch (Exception $exception) {
return response(500);
}
}
public function index(CustomerFilter $filters): JsonResponse
{
$customers = Customer::with(['Country'])->filter($filters)->get();
foreach ($customers as $customer) {
$customer['country'] = $customer->country;
}
return response()->json($customers);
}
}
<file_sep>/app/Models/Customer.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* App\Models\Customer
*
* @property int $id
* @property string $name
* @property string $mobile
* @property string $email
* @property int $country_id
* @property int $active
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \App\Models\Country $country
* @method static Builder|Customer active()
* @method static Builder|Customer filter($filters)
* @method static Builder|Customer newModelQuery()
* @method static Builder|Customer newQuery()
* @method static Builder|Customer query()
* @method static Builder|Customer whereActive($value)
* @method static Builder|Customer whereCountryId($value)
* @method static Builder|Customer whereCreatedAt($value)
* @method static Builder|Customer whereEmail($value)
* @method static Builder|Customer whereId($value)
* @method static Builder|Customer whereMobile($value)
* @method static Builder|Customer whereName($value)
* @method static Builder|Customer whereUpdatedAt($value)
* @mixin \Eloquent
*/
class Customer extends Model
{
use HasFactory;
protected $guarded= ['id'];
protected $fillable = ['name', 'mobile', 'email', 'country_id', 'active'];
public function country(): BelongsTo
{
return $this->belongsTo(Country::class);
}
public function scopeActive(Builder $query): Builder
{
return $query->whereActive(1);
}
public function scopeFilter($query, $filters)
{
return $filters->apply($query);
}
}
<file_sep>/app/Http/Controllers/PageController.php
<?php
namespace App\Http\Controllers;
use App\Models\Country;
use Illuminate\Http\Request;
class PageController extends Controller
{
public function customer()
{
$countries = Country::all();
return view('customers', [
'countries' => $countries
]);
}
public function car()
{
return view('cars');
}
}
<file_sep>/app/Filters/CustomerFilter.php
<?php
namespace App\Filters;
use Illuminate\Http\Request;
class CustomerFilter
{
protected $request;
protected $queryBuilder;
protected $filters = ['limit'];
public function __construct(Request $request)
{
$this->request = $request;
}
public function apply($builder)
{
$this->queryBuilder = $builder;
// Get filters passed from the request and exist in $this->>filters
$filters = array_filter($this->request->only($this->filters));
foreach ($filters as $filter => $value) {
// $filter illustrates the method name called
if (method_exists($this, $filter)) {
$this->$filter($value);
}
}
return $this->queryBuilder;
}
protected function limit($filter)
{
switch ($filter) {
case 'all':
return $this->queryBuilder;
case 'active':
default:
return $this->queryBuilder->where('active', 1);
case 'not-active':
return $this->queryBuilder->where('active', 0);
}
}
}
<file_sep>/app/Models/Country.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* App\Models\Country
*
* @property int $id
* @property string $country
* @method static \Illuminate\Database\Eloquent\Builder|Country newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Country newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Country query()
* @method static \Illuminate\Database\Eloquent\Builder|Country whereCountry($value)
* @method static \Illuminate\Database\Eloquent\Builder|Country whereId($value)
* @mixin \Eloquent
*/
class Country extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $fillable = ['country'];
public $timestamps = false;
}
<file_sep>/database/seeders/CustomerSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Customer;
use Illuminate\Database\Seeder;
class CustomerSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [];
foreach (range(1, 50) as $index) {
$customer = Customer::factory()->make([
'country_id' => rand(1, 10),
'active' => (rand(0, 1) === 1)
]);
$data[] = [
'name' => $customer->name,
'mobile' => $customer->mobile,
'email' => $customer->email,
'country_id' => $customer->country_id,
'active' => $customer->active,
];
}
Customer::insert($data);
}
}
| 4bd46df0a3d18f365d536a931a045f3128059e17 | [
"PHP"
] | 8 | PHP | ZYCGary/code-challenge | 743af732d4fc90130c971dd7c124f42e107ffd10 | ee94a6474ea8fab15b5f1fffc754c361748babeb |
refs/heads/master | <file_sep>package entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="CHANCELLOR")
public class Chancellor {
private Integer id;
private String name;
private University university;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToOne(mappedBy="chancellor")
public University getUniversity() {
return university;
}
public void setUniversity(University university) {
this.university = university;
}
}
| d51fdb4fa6fe08f744169946d1197dbfb5d5708f | [
"Java"
] | 1 | Java | samuelpucat/aass | bf4e20641ff66aff283cb8009e4befd11f9601ff | 2265c32494dfb12c069a3b7213e76215b98da1f7 |
refs/heads/master | <file_sep>package jp.ac.chiba_fjb.oikawa.appcall;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//以下の呼び出し内容を表示する
// http://join/id=パラメータ
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(intent != null && intent.getDataString() != null){
Pattern p = Pattern.compile("id=(.*)");
Matcher m = p.matcher(intent.getDataString());
if(m.find())
((TextView)findViewById(R.id.textView1)).setText(m.group(1));
}
}
}
| 906ecd149cb852cd2fe33f93fd3392e94524beaa | [
"Java"
] | 1 | Java | SoraKumo001/Android-AppCall | 8a7cdceafba90f976df15129b8f1c4d86f0a05fb | bb39523629e75e2b5a2619d7b01c493f6b62e6e1 |
refs/heads/master | <file_sep>class Hashr
module Delegate
module Conditional
def method_missing(name, *args, &block)
if (args.any? || block) && @data.respond_to?(name)
@data.send(name, *args, &block)
else
super
end
end
end
end
end
<file_sep>class Hashr
module Delegation
module Hash
METHODS = [
:all?,
:any?,
:clear,
:delete,
:delete_if,
:detect,
:drop,
:drop_while,
:each,
:empty?,
:fetch,
:find,
:flat_map,
:grep,
:group_by,
:hash,
:inject,
:invert,
:is_a?,
:keep_if,
:key,
:key?,
:keys,
:length,
:map,
:merge,
:nil?,
:none?,
:one?,
:reduce,
:reject,
:select,
:size,
:value?,
:values,
:values_at
]
METHODS.each do |name|
define_method(name) { |*args, &block| @data.send(name, *args, &block }
end
end
end
end
<file_sep>class Hashr
module Env
class Vars < Struct.new(:defaults, :namespace)
FALSE = [false, nil, 'false', 'nil', '']
def to_h
defaults.deep_merge(read_env(defaults, namespace.dup))
end
private
def read_env(defaults, namespace)
defaults.inject({}) do |result, (key, default)|
keys = namespace + [key]
value = default.is_a?(Hash) ? read_env(default, keys) : var(keys, default)
result.merge(key => value)
end
end
def var(keys, default)
key = keys.map(&:upcase).join('_')
value = ENV.fetch(key, default)
cast(value, default, keys)
end
def cast(value, default, keys)
case default
when Array
value.respond_to?(:split) ? value.split(',') : Array(value)
when true, false
not FALSE.include?(value)
when Integer then Integer(value)
when Float then Float(value)
else
value
end
end
def namespace
Array(super && super.upcase)
end
end
attr_accessor :env_namespace
def defaults
Vars.new(super, env_namespace).to_h
end
end
end
<file_sep>require 'hashr'
<file_sep>describe Hashr::Env do
let(:klass) do
Class.new(Hashr) do
extend Hashr::Env
self.env_namespace = 'hashr'
define string: 'string',
hash: { key: 'value' },
array: ['foo', 'bar'],
bool: false,
int: 4,
float: 11.1
end
end
after do
ENV.keys.each { |key| ENV.delete(key) if key.start_with?('HASHR_') }
end
it 'defaults to an env var' do
ENV['HASHR_STRING'] = 'env string'
expect(klass.new.string).to eq('env string')
end
it 'defaults to a nested env var' do
ENV['HASHR_HASH_KEY'] = 'env value'
expect(klass.new.hash.key).to eq('env value')
end
describe 'type casts based on the default' do
describe 'to boolean' do
it 'true given' do
ENV['HASHR_BOOL'] = 'true'
expect(klass.new.bool).to eq(true)
end
it 'false given' do
ENV['HASHR_BOOL'] = 'false'
expect(klass.new.bool).to eq(false)
end
it 'empty string given' do
ENV['HASHR_BOOL'] = ''
expect(klass.new.bool).to eq(false)
end
end
describe 'to an array' do
it 'splits a comma-separated string' do
ENV['HASHR_ARRAY'] = 'env foo,env bar'
expect(klass.new.array).to eq(['env foo', 'env bar'])
end
it 'returns an empty array for an empty string' do
ENV['HASHR_ARRAY'] = ''
expect(klass.new.array).to eq([])
end
end
describe 'to an int' do
it 'int given' do
ENV['HASHR_INT'] = '1'
expect(klass.new.int).to eq(1)
end
it 'errors for an empty string' do
ENV['HASHR_INT'] = ''
expect { klass.new.int }.to raise_error(ArgumentError)
end
it 'errors for a non-int' do
ENV['HASHR_INT'] = 'a'
expect { klass.new.int }.to raise_error(ArgumentError)
end
end
describe 'to a float' do
it 'float given' do
ENV['HASHR_FLOAT'] = '2.3'
expect(klass.new.float).to eq(2.3)
end
it 'int given' do
ENV['HASHR_FLOAT'] = '4'
expect(klass.new.float).to eq(4.0)
end
it 'errors for an empty string' do
ENV['HASHR_FLOAT'] = ''
expect { klass.new.float }.to raise_error(ArgumentError)
end
it 'errors for a non-float' do
ENV['HASHR_FLOAT'] = 'a'
expect { klass.new.float }.to raise_error(ArgumentError)
end
end
end
it 'data takes precedence over an env var' do
ENV['HASHR_STRING'] = 'env string'
expect(klass.new(string: 'data string').string).to eq('data string')
end
end
<file_sep>describe Hashr do
describe 'initialization' do
it 'takes nil' do
expect { Hashr.new(nil) }.to_not raise_error
end
it 'does not explode on a numerical key' do
expect { Hashr.new(1 => 2) }.to_not raise_error
end
it 'does not explode on a true key' do
expect { Hashr.new(true => 'on') }.to_not raise_error
end
it 'raises an ArgumentError when given a string' do
expect { Hashr.new('foo') }.to raise_error(ArgumentError)
end
it 'passing a block allows to define methods on the singleton class' do
hashr = Hashr.new(count: 5) do
def count
@data.count
end
end
expect(hashr.count).to eq(5)
end
end
describe 'defined?' do
it 'returns true when a key is defined' do
hashr = Hashr.new(foo: 'foo')
expect(hashr.defined?(:foo)).to eq(true)
end
it 'returns false when a key is not defined' do
hashr = Hashr.new(foo: 'foo')
expect(hashr.defined?(:bar)).to eq(false)
end
it 'works with a numerical key' do
hashr = Hashr.new(1 => 'foo')
expect(hashr.defined?(1)).to eq(true)
end
it 'works with a true key' do
hashr = Hashr.new(true => 'foo')
expect(hashr.defined?(true)).to eq(true)
end
it 'is indifferent about symbols/strings (string given, symbol used)' do
hashr = Hashr.new('foo' => 'bar')
expect(hashr.defined?(:foo)).to eq(true)
end
it 'is indifferent about symbols/strings (symbol given, string used)' do
hashr = Hashr.new(foo: :bar)
expect(hashr.defined?('foo')).to eq(true)
end
end
describe 'hash access' do
it 'is indifferent about symbols/strings (string given, symbol used)' do
hashr = Hashr.new('foo' => { 'bar' => 'baz' })
expect(hashr[:foo][:bar]).to eq('baz')
end
it 'is indifferent about symbols/strings (symbol given, string used)' do
hashr = Hashr.new(foo: { bar: 'baz' })
expect(hashr['foo']['bar']).to eq('baz')
end
it 'allows accessing keys with Hash core method names (count)' do
expect(Hashr.new(count: 2).count).to eq(2)
end
it 'allows accessing keys with Hash core method names (key)' do
expect(Hashr.new(key: 'key').key).to eq('key')
end
end
describe 'hash assignment' do
let(:hashr) { Hashr.new }
it 'works with a string key' do
hashr['foo'] = 'foo'
expect(hashr.foo).to eq('foo')
end
it 'works with a symbol key' do
hashr[:foo] = 'foo'
expect(hashr.foo).to eq('foo')
end
end
describe 'method access' do
describe 'on an existing key' do
it 'returns the value' do
expect(Hashr.new(foo: 'foo').foo).to eq('foo')
end
it 'returns a nested hash' do
expect(Hashr.new(foo: { bar: 'bar' }).foo).to eq(bar: 'bar')
end
it 'returns a nested array' do
expect(Hashr.new(foo: ['bar', 'buz']).foo).to eq(['bar', 'buz'])
end
end
describe 'on an existing nested key' do
it 'returns the value' do
expect(Hashr.new(foo: { bar: 'bar' }).foo.bar).to eq('bar')
end
it 'returns a nested array' do
expect(Hashr.new(foo: { bar: ['bar', 'buz'] }).foo.bar).to eq(['bar', 'buz'])
end
end
describe 'on an non-existing key' do
it 'it returns nil' do
expect(Hashr.new(foo: 'foo').bar).to eq(nil)
end
it 'it returns nil (nested key)' do
expect(Hashr.new(foo: { bar: 'bar' }).foo.baz).to eq(nil)
end
end
describe 'predicate methods' do
it 'returns true if the key has a value' do
expect(Hashr.new(foo: { bar: 'bar' }).foo.bar?).to eq(true)
end
it 'returns false if the key does not have a value' do
expect(Hashr.new(foo: { bar: 'bar' }).foo.baz?).to eq(false)
end
end
describe 'respond_to?' do
it 'returns true for existing keys' do
expect(Hashr.new(foo: 'bar').respond_to?(:foo)).to eq(true)
end
it 'returns false for missing keys' do
expect(Hashr.new.respond_to?(:foo)).to eq(true)
end
end
end
describe 'method assignment' do
let(:hashr) { Hashr.new }
it 'assigns a string' do
hashr.foo = 'foo'
expect(hashr.foo).to eq('foo')
end
it 'converts a hash into a Hashr instance' do
hashr.foo = { bar: { baz: 'baz' } }
expect(hashr.foo.bar.baz).to eq('baz')
end
end
describe 'values_at' do
let(:hashr) { Hashr.new(foo: 'foo', bar: 'bar') }
it 'returns values for the given keys' do
expect(hashr.values_at(:foo, :bar)).to eq(['foo', 'bar'])
end
end
describe 'is_a?' do
let(:klass) { Class.new(Class.new(Hashr)) { default foo: 'foo' } }
it 'returns true if the object has the given superclass' do
expect(klass.new.is_a?(Hashr)).to eq(true)
end
it 'returns false if the object does not have the given superclass' do
expect(klass.new.is_a?(Hash)).to eq(false)
end
end
describe 'conversion' do
let(:hash) { Hashr.new(foo: { 'bar' => 'baz' }).to_h }
it 'converts the Hashr instance to a hash' do
expect(hash.class).to eq(Hash)
end
it 'converts nested instances to hashes' do
expect(hash[:foo].class).to eq(Hash)
end
it 'populates the hash with the symbolized keys' do
expect(hash[:foo][:bar]).to eq('baz')
end
end
describe 'defaults' do
describe 'using a symbolized hash' do
let(:klass) { Class.new(Hashr) { default foo: 'foo' } }
it 'defines the default' do
expect(klass.new['foo']).to eq('foo')
end
end
describe 'using a stringified hash' do
let(:klass) { Class.new(Hashr) { default 'foo' => 'foo' } }
it 'defines the default' do
expect(klass.new[:foo]).to eq('foo')
end
end
describe 'with a nested hash' do
let(:klass) { Class.new(Hashr) { default foo: { bar: { baz: 'baz' } } } }
it 'defines the default' do
expect(klass.new['foo'][:bar]['baz']).to eq('baz')
end
end
describe 'with a nested array' do
let(:klass) { Class.new(Hashr) { default foo: ['bar'] } }
it 'defines the default' do
expect(klass.new.foo.first).to eq('bar')
end
end
describe 'keeps existing defaults' do
let(:klass) { Class.new(Hashr) { default foo: 'foo'; default bar: 'bar' } }
it 'defines the existing default' do
expect(klass.new.foo).to eq('foo')
end
it 'defines the new default' do
expect(klass.new.bar).to eq('bar')
end
end
describe 'deep_merges inherited defaults' do
let(:klass) { Class.new(Class.new(Hashr) { default foo: 'foo' }) { default bar: 'bar' } }
it 'defines the inherited default' do
expect(klass.new.foo).to eq('foo')
end
it 'defines the default' do
expect(klass.new.bar).to eq('bar')
end
end
end
describe 'constant lookup' do
let(:klass) { Class.new(Hashr) { def env; ENV; end } }
it 'finds global consts' do
expect(klass.new.env).to eq(ENV)
end
end
describe 'pry methods' do
let(:klass) { Class.new(Hashr) { default foo: { bar: { baz: 'baz' } } } }
example '#inspect' do
expect(klass.new.foo.inspect).to eq("<Hashr {:bar=><Hashr {:baz=>\"baz\"}>}>")
end
example '#to_s' do
expect(klass.new.foo.to_s).to eq("{:bar=>{:baz=>\"baz\"}}")
end
end
end
<file_sep>require 'hashr/core_ext/ruby/hash'
class Hashr < BasicObject
require 'hashr/delegate/conditional'
require 'hashr/env'
class << self
attr_reader :defaults
def inherited(other)
other.default(defaults)
end
def new(*args)
super(self, *args)
end
def default(defaults)
@defaults = (self.defaults || {}).deep_merge(defaults || {})
end
alias :define :default
def const_missing(name)
Kernel.const_get(name)
end
end
attr_reader :class
def initialize(klass, data = nil, defaults = nil, &block)
::Kernel.fail ::ArgumentError.new("Invalid input #{data.inspect}") unless data.nil? || data.is_a?(::Hash)
data = (data || {}).deep_symbolize_keys
defaults = (defaults || klass.defaults || {}).deep_symbolize_keys
@class = klass
@data = defaults.deep_merge(data).inject({}) do |result, (key, value)|
result.merge(key => value.is_a?(::Hash) ? ::Hashr.new(value, {}) : value)
end
end
def defined?(key)
@data.key?(to_key(key))
end
def [](key)
@data[to_key(key)]
end
def []=(key, value)
@data.store(to_key(key), value.is_a?(::Hash) ? ::Hashr.new(value, {}) : value)
end
def values_at(*keys)
keys.map { |key| self[key] }
end
def respond_to?(*args)
true
end
def method_missing(name, *args, &block)
case name.to_s[-1, 1]
when '?'
!!self[name.to_s[0..-2]]
when '='
self[name.to_s[0..-2]] = args.first
else
self[name]
end
end
def try(key)
defined?(key) ? self[key] : nil # TODO needs to look for to_h etc
end
def to_h
@data.inject({}) do |hash, (key, value)|
hash.merge(key => value.is_a?(Hashr) || value.is_a?(Hash) ? value.to_h : value)
end
end
alias to_hash to_h
def ==(other)
to_h == other.to_h if other.respond_to?(:to_h)
end
def instance_of?(const)
self.class == const
end
def is_a?(const)
consts = [self.class]
consts << consts.last.superclass while consts.last.superclass
consts.include?(const)
end
alias kind_of? is_a?
def inspect
"<#{self.class.name} #{@data.inspect}>"
end
def to_s
to_h.to_s
end
private
def to_key(key)
key.respond_to?(:to_sym) ? key.to_sym : key
end
end
<file_sep>describe Hash do
describe 'deep_symbolize_keys' do
it 'symbolizes keys on nested hashes' do
hash = { 'foo' => { 'bar' => 'bar' } }
expected = { :foo => { :bar => 'bar' } }
expect(hash.deep_symbolize_keys).to eq(expected)
end
it 'walks arrays' do
hash = { 'foo' => [{ 'bar' => 'bar', 'baz' => { 'buz' => 'buz' } }] }
expected = { :foo => [{ :bar => 'bar', :baz => { :buz => 'buz' } }] }
expect(hash.deep_symbolize_keys).to eq(expected)
end
end
end
<file_sep>require 'spec_helper'
describe Hashr::Delegate::Conditional do
let(:klass) { Class.new(Hashr) { include Hashr::Delegate::Conditional } }
it 'delegates key?' do
hashr = klass.new(foo: 'foo')
expect(hashr.key?(:foo)).to eq(true)
end
it 'delegates select' do
hashr = klass.new(foo: 'foo', bar: 'bar')
expect(hashr.select { |key, value| key == :bar }.to_h).to eq(bar: 'bar')
end
it 'delegates delete' do
hashr = klass.new(foo: 'foo', bar: 'bar')
hashr.delete(:foo)
expect(hashr.to_h).to eq(bar: 'bar')
end
end
<file_sep># encoding: utf-8
$:.unshift File.expand_path('../lib', __FILE__)
require 'hashr/version'
Gem::Specification.new do |s|
s.name = "hashr"
s.version = Hashr::VERSION
s.authors = ["<NAME>"]
s.email = "<EMAIL>"
s.homepage = "http://github.com/svenfuchs/hashr"
s.summary = "Simple Hash extension to make working with nested hashes (e.g. for configuration) easier and less error-prone"
s.description = "#{s.summary}."
s.files = Dir['{lib/**/*,spec/**/*,MIT-LICENSE,README.md,Gemfile}']
s.platform = Gem::Platform::RUBY
s.require_path = 'lib'
s.rubyforge_project = '[none]'
end
<file_sep>class Hash
def deep_symbolize_keys
symbolizer = lambda do |value|
case value
when Hash
value.deep_symbolize_keys
when Array
value.map { |value| symbolizer.call(value) }
else
value
end
end
inject({}) do |result, (key, value)|
result[(key.to_sym rescue key) || key] = symbolizer.call(value)
result
end
end unless instance_methods.include?(:deep_symbolize_keys)
# deep_merge_hash! by <NAME>, see http://www.ruby-forum.com/topic/142809
def deep_merge(other)
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
merge(other, &merger)
end unless instance_methods.include?(:deep_merge)
end
<file_sep>class Hashr < BasicObject
VERSION = '2.0.1'
end
| e527e7125499b9a08ea77dd11cfd754cd5f1ba01 | [
"Ruby"
] | 12 | Ruby | renee-travisci/hashr | e99327c2e379f9a0a996ce35314b3ed812136acd | 78531ecbf5c7649a821f2aebb326ccf26ee91fb7 |
refs/heads/master | <file_sep># Blesta "ISPAPI" Registrar Module
[](https://github.com/semantic-release/semantic-release)
[](https://github.com/hexonet/blesta-ispapi-registrar/workflows/Release/badge.svg?branch=master)
[](https://opensource.org/licenses/MIT)
[](https://github.com/hexonet/php-sdk/blob/master/CONTRIBUTING.md)
This Repository covers the Blesta Registrar Module of HEXONET. It provides the following features in Blesta:
## Resources
Download the ZIP archive [here](https://github.com/hexonet/blesta-ispapi-registrar/raw/master/blesta-ispapi-registrar-latest.zip) and follow the Documentation.
- [Documentation](https://centralnic-reseller.github.io/centralnic-reseller/docs/hexonet/blesta/)
- [Release Notes](https://github.com/hexonet/blesta-ispapi-registrar/releases)
## Authors
- **<NAME>** - _development_ - [PapaKai](https://github.com/papakai)
Former Authors:
- **<NAME>** - [tulsi91](//github.com/tulsi91)
## License
This project is licensed under the MIT License - see the [LICENSE](https://github.com/hexonet/blesta-ispapi-registrar/blob/master/LICENSE) file for details.
[HEXONET GmbH](https://hexonet.net)
<file_sep>#!/bin/bash
PHP_VERSION="$(php -r 'echo PHP_MAJOR_VERSION . "." . PHP_MINOR_VERSION;')"
phpcs --standard=PHPCompatibility -q -n --colors --runtime-set testVersion "$PHP_VERSION" apis config language ispapi.php || exit 1;<file_sep><?php
/**
* Ispapi Module
*
* @package blesta
* @subpackage blesta.components.modules.ispapi
* @copyright Copyright (c) 2018-2021, HEXONET.
* @license https://raw.githubusercontent.com/hexonet/blesta-ispapi-registrar/master/LICENSE MIT
* @link https://www.hexonet.net/ HEXONET
*/
class Ispapi extends RegistrarModule
{
/**
* @var string Default module view path
*/
private static $defaultModuleView = "components" . DS . "modules" . DS . "ispapi" . DS;
/**
* Initializes the module
*/
public function __construct()
{
// Load the language required by this module
Language::loadLang("ispapi", null, __DIR__ . DS . "language" . DS);
// Load config.json (important to have language loaded first)
$this->loadConfig(__DIR__ . DS . "config.json");
// Load components required by this module
Loader::loadComponents($this, ["Input", "Record"]);
// Load configuration
Configure::load("ispapi", __DIR__ . DS . "config" . DS);
// ---------------------------------------------------------------
// HEXONET's PHP-SDK
// ---------------------------------------------------------------
$path = implode(DS, [__DIR__, "apis", "sdk", "src", ""]);
Loader::load($path . "SocketConfig.php");
Loader::load($path . "APIClient.php");
Loader::load($path . "Column.php");
Loader::load($path . "Logger.php");
Loader::load($path . "Record.php");
Loader::load($path . "ResponseTranslator.php");
Loader::load($path . "Response.php");
Loader::load($path . "ResponseParser.php");
Loader::load($path . "ResponseTemplateManager.php");
$path = implode(DS, [__DIR__, "apis", ""]);
Loader::load($path . "BlestaLogger.php");
// ---------------------------------------------------------------
}
/**
* Cast our UTC API timestamps to UTC timestamp string and unix timestamp
* @param string|int $date API timestamp (YYYY-MM-DD HH:ii:ss) or unix timestamp produced by strtotime
* @return array
*/
private function _castDate(string $date, string $format): array
{
$ts = is_int($date) ?
$date :
strtotime(str_replace(" ", "T", $date) . "Z");//RFC 3339 / ISO 8601
return [
"ts" => $ts,
"short" => gmdate("Y-m-d", $ts),
"long" => gmdate($format, $ts)
];
}
/**
* Make an API request using the provided command and return response in Hash Format
* @param array $command API command to request
* @param array $row Module Row
* @param string $successCase regex to match the response code as success case
* @return array
*/
private function _call(array $command, stdClass $row, string $successCase = "/^200$/")
{
$cl = new \HEXONET\APIClient();
if ($row->meta->sandbox == "true") {
$cl->useOTESystem();
}
$cl->setCredentials($row->meta->user, $row->meta->key)
->setReferer($_SERVER["HTTP_HOST"])
->setUserAgent("Blesta", BLESTA_VERSION, [
"ispapi/" . $this->getVersion()
])
->enableDebugMode() // activate logging
->setCustomLogger(new BlestaLogger(
$this,
$cl->getURL()
));
if (!empty($row->ProxyServer)) {
$cl->setProxy($row->ProxyServer);
}
$r = $cl->request($command)->getHash();
if (!preg_match($successCase, $r["CODE"])) {
$this->Input->setErrors([
"errors" => [ $r["CODE"] . " " . $r["DESCRIPTION"] ]
]);
}
return $r;
}
/**
* Attempts to log the given info to the module log.
* (Make native Log function public allowing us to forward it to our BlestaLogger)
* @param string $url The URL contacted for this request
* @param string $data A string of module data sent along with the request (optional)
* @param string $direction The direction of the log entry (input or output, default input)
* @param bool $success True if the request was successful, false otherwise
*/
public function log($url, $data = null, $direction = "input", $success = false)
{
parent::log($url, $data, $direction, $success);
}
/**
* Yes, we support DNS Management
* @return bool
*/
public function supportsDnsManagement()
{
return false;
}
/**
* Yes, we support Email Forwarding
* @return bool
*/
public function supportsEmailForwarding()
{
return false;
}
/**
* Yes, we support Id Protection / Whois Privacy
* @return bool
*/
public function supportsIdProtection()
{
return false;
}
/**
* Yes, we support EPP / Authorization Codes
* @return bool
*/
public function supportsEppCode()
{
return false;
}
/**
* Attempts to validate service info. This is the top-level error checking method. Sets Input errors on failure.
*
* @param stdClass $package A stdClass object representing the selected package
* @param array $vars An array of user supplied info to satisfy the request
* @return bool True if the service validates, false otherwise. Sets Input errors when false.
*/
public function validateService($package, array $vars = null)
{
// TODO: the right place to validate authcodes for transfer
// and additional domain fields
return true;
}
/**
* Adds the service to the remote server. Sets Input errors on failure,
* preventing the service from being added.
*
* @param stdClass $package A stdClass object representing the selected package
* @param array $vars An array of user supplied info to satisfy the request
* @param stdClass $parent_package A stdClass object representing the parent
* service's selected package (if the current service is an addon service)
* @param stdClass $parent_service A stdClass object representing the parent
* service of the service being added (if the current service is an addon
* service and parent service has already been provisioned)
* @param string $status The status of the service being added. These include:
* - active
* - canceled
* - pending
* - suspended
* @return array A numerically indexed array of meta fields to be stored for this service containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function addService(
$package,
array $vars = null,
$parent_package = null,
$parent_service = null,
$status = "pending"
) {
// 'Service' meaning here registered or tranferred domain name
$whois_sections = Configure::get("Ispapi.whois_sections");
$tld = null;
$input_fields = [];
if (isset($vars["domain"])) {
$tld = $this->getTld($vars["domain"]);
}
$input_fields = array_merge(
Configure::get("Ispapi.domain_fields"),
(array) Configure::get("Ispapi.domain_fields" . $tld),
(array) Configure::get("Ispapi.nameserver_fields"),
(array) Configure::get("Ispapi.transfer_fields"),
[
"NumYears" => true,
"transfer" => isset($vars["transfer"]) ? $vars["transfer"] : 1
]
);
$row = $this->getModuleRow($package->module_row);
if (isset($vars["use_module"]) && $vars["use_module"] == "true") {
if ($package->meta->type === "domain") {
$vars["NumYears"] = 1;
$vars["SLD"] = substr($vars["domain"], 0, -strlen($tld));
$vars["TLD"] = ltrim($tld, ".");
foreach ($package->pricing as $pricing) {
if ($pricing->id === $vars["pricing_id"]) {
$vars["NumYears"] = $pricing->term;
$vars["Period"] = $pricing->period;
break;
}
}
// Fields for contact information
$whois_fields = Configure::get("Ispapi.whois_fields");
// Contact information of a customer
if (!isset($this->Clients)) {
Loader::loadModels($this, ["Clients"]);
}
if (!isset($this->Contacts)) {
Loader::loadModels($this, ["Contacts"]);
}
$client = $this->Clients->get($vars["client_id"]);
if ($client) {
$numbers = $this->Contacts->getNumbers($client->contact_id, "phone");
}
// Customer contact information according to whois_fields = Registrant, Admin, Tech and Billing
foreach ($whois_fields as $key => $value) {
if (strpos($key, "FirstName") !== false) {
$vars[$key] = $client->first_name;
} elseif (strpos($key, "LastName") !== false) {
$vars[$key] = $client->last_name;
} elseif (strpos($key, "Organization") !== false) {
$vars[$key] = $client->company;
} elseif (strpos($key, "Address1") !== false) {
$vars[$key] = $client->address1;
} elseif (strpos($key, "Address2") !== false) {
$vars[$key] = $client->address2;
} elseif (strpos($key, "City") !== false) {
$vars[$key] = $client->city;
} elseif (strpos($key, "StateProvince") !== false) {
$vars[$key] = $client->state;
} elseif (strpos($key, "PostalCode") !== false) {
$vars[$key] = $client->zip;
} elseif (strpos($key, "Country") !== false) {
$vars[$key] = $client->country;
} elseif (strpos($key, "Phone") !== false) {
$vars[$key] = $this->formatPhone(
isset($numbers[0]) ? $numbers[0]->number : null,
$client->country
);
} elseif (strpos($key, "EmailAddress") !== false) {
$vars[$key] = $client->email;
}
}
// Nameservers
$vars["UseDNS"] = "default";
for ($i=1; $i<=5; $i++) {
if (!isset($vars["ns" . $i]) || empty($vars["ns" . $i])) {
unset($vars["ns" . $i]);
} else {
unset($vars["UseDNS"]);
}
}
$fields = array_intersect_key($vars, $input_fields);
// Registrant, Admin, Tech and Billing contact information for AddDomain and TransferDomain commands
foreach ($whois_sections as $key => $contact) {
$contact_data[$contact] = [
"FIRSTNAME" => $vars[$contact."FirstName"],
"LASTNAME" => $vars[$contact."LastName"],
"STREET" => $vars[$contact."Address1"],
"ORGANIZATION" => $vars[$contact."Organization"],
"CITY" => $vars[$contact."City"],
"STATE" => $vars[$contact."StateProvince"],
"ZIP" => $vars[$contact."PostalCode"],
"COUNTRY" => $vars[$contact."Country"],
"PHONE" => $vars[$contact."Phone"],
"EMAIL" => $vars[$contact."EmailAddress"]
];
if (strlen($vars[$contact."Address2"])) {
$contact_data[$contact]["STREET"] .= " , ".$vars[$contact."Address2"];
}
}
if (isset($vars["transfer_key"]) && !empty($vars["transfer_key"])) {
//domain transfer pre-check
$r = $this->_call([
"COMMAND" => "CheckDomainTransfer",
"DOMAIN" => $vars["domain"],
"AUTH" => $vars["transfer_key"]
], $row, "/^(200|218)$/");
// Handling api errors
if ($this->Input->errors()) {
return;
}
$errors = [];
if (isset($r["PROPERTY"]["AUTHISVALID"]) && $r["PROPERTY"]["AUTHISVALID"][0] === "NO") {
// return custom error message
$errors[] = "Invaild Authorization Code";
}
if (isset($r["PROPERTY"]["TRANSFERLOCK"]) && $r["PROPERTY"]["TRANSFERLOCK"][0] === "1") {
// return custom error message
$errors[] = "Transferlock is active. Therefore the Domain cannot be transferred.";
}
if (!empty($errors)) {
$this->Input->setErrors([
"errors" => $errors
]);
return;
}
// Handle transfer
$command = [
"COMMAND" => "TransferDomain",
"DOMAIN" => $vars["domain"],
"PERIOD" => $vars["NumYears"],
"NAMESERVER0" => $vars["ns1"],
"NAMESERVER1" => $vars["ns2"],
"NAMESERVER2" => $vars["ns3"],
"NAMESERVER3" => $vars["ns4"],
"OWNERCONTACT0" => $contact_data["Registrant"],
"ADMINCONTACT0" => $contact_data["Admin"],
"TECHCONTACT0" => $contact_data["Tech"],
"BILLINGCONTACT0" => $contact_data["Billing"],
"AUTH" => $vars["transfer_key"]
];
if (isset($r["PROPERTY"]["USERTRANSFERREQUIRED"])
&& $r["PROPERTY"]["USERTRANSFERREQUIRED"][0] === "1"
) {
//auto-detect user-transfer
$command["ACTION"] = "USERTRANSFER";
}
//don't send owner admin tech billing contact for .NU .DK .CA, .US, .PT, .NO, .SE, .ES domains
//2) do not send contact information for gTLD (Including nTLDs)
if (preg_match("/\.([a-z]{3,}(nu|dk|ca|us|pt|no|se|es)$/i", $vars["domain"])) {
unset($command["OWNERCONTACT0"]);
unset($command["ADMINCONTACT0"]);
unset($command["TECHCONTACT0"]);
unset($command["BILLINGCONTACT0"]);
}
//don't send owner billing contact for .FR domains
if (preg_match("/\.fr$/i", $vars["domain"])) {
unset($command["OWNERCONTACT0"]);
unset($command["BILLINGCONTACT0"]);
}
//auto-detect default transfer period
//for example, es, no, nu tlds require period value as zero (free transfers).
//in Blesta the default value is based on the package settings for those TLDs created by user
$r = $this->_call([
"COMMAND" => "QueryDomainOptions",
"DOMAIN0" => $vars["domain"]
], $row);
//TODO
if ($qr["CODE"] === "200") {
$period_array = explode(",", $qr["PROPERTY"]["ZONETRANSFERPERIODS"][0]);
if (preg_match("/^0(Y|M)?$/i", $period_array[0])) {// set period 0 - specific case.
$command["PERIOD"] = $period_array[0];
}
}
//do not send contact information for gTLD (Including nTLDs)
if (preg_match("/\.[a-z]{3,}$/i", $vars["domain"])) {
unset($command["OWNERCONTACT0"]);
unset($command["ADMINCONTACT0"]);
unset($command["TECHCONTACT0"]);
unset($command["BILLINGCONTACT0"]);
}
$this->_call($command, $row);
// Handling api errors
if ($this->Input->errors()) {
return;
}
return [
[
"key" => "domain",
"value" => $fields["domain"],
"encrypted" => 0
]
];
}
// Handle registration
$command = [
"COMMAND" => "AddDomain",
"DOMAIN" => $vars["domain"],
"PERIOD" => $vars["NumYears"],
"NAMESERVER0" => $vars["ns1"],
"NAMESERVER1" => $vars["ns2"],
"NAMESERVER2" => $vars["ns3"],
"NAMESERVER3" => $vars["ns4"],
"OWNERCONTACT0" => $contact_data["Registrant"],
"ADMINCONTACT0" => $contact_data["Admin"],
"TECHCONTACT0" => $contact_data["Tech"],
"BILLINGCONTACT0" => $contact_data["Billing"]
];
// Not all TLDs additional fields are like X-<tld>-<something>
#$tld_pattern = preg_replace("/\./", " ", strtoupper($tld));
#foreach($vars as $key => $value) {
# if (preg_match("/X-".trim($tld_pattern)."/",$key)){
# $command[$key] = $value;
# }
#}
// Considered only "X-<something>" pattern for all fields
foreach ($vars as $key => $value) {
if (preg_match("/^X-(.*)/", $key)) {
$command[$key] = $value;
}
}
$this->_call($command, $row);
// Handle api errors
if ($this->Input->errors()) {
return;
}
// Return domain details when registered successfully
return [
[
"key" => "domain",
"value" => $vars["domain"],
"encrypted" => 0
]
];
}
}
$meta = [];
$fields = array_intersect_key($vars, $input_fields);
foreach ($fields as $key => $value) {
$meta[] = [
"key" => $key,
"value" => $value,
"encrypted" => 0
];
}
return $meta;
}
/**
* Edits the service on the remote server. Sets Input errors on failure,
* preventing the service from being edited.
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $vars An array of user supplied info to satisfy the request
* @param stdClass $parent_package A stdClass object representing the parent
* service's selected package (if the current service is an addon service)
* @param stdClass $parent_service A stdClass object representing the parent
* service of the service being edited (if the current service is an addon service)
* @return array A numerically indexed array of meta fields to be stored for this service containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function editService($package, $service, array $vars = [], $parent_package = null, $parent_service = null)
{
// Perform manual renewals
$renew = isset($vars["renew"]) ? (int)$vars["renew"] : 0;
if ($renew > 0 && $vars["use_module"] == "true") {
// Call to renewService() to perform manual renewals
$this->renewService($package, $service, $parent_package, $parent_service, $renew);
unset($vars["renew"]);
}
return null; // All this handled by admin/client tabs instead
}
/**
* Cancels the service on the remote server. Sets Input errors on failure,
* preventing the service from being canceled.
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param stdClass $parent_package A stdClass object representing the parent
* service's selected package (if the current service is an addon service)
* @param stdClass $parent_service A stdClass object representing the parent
* service of the service being canceled (if the current service is an addon service)
* @return mixed null to maintain the existing meta fields or a numerically
* indexed array of meta fields to be stored for this service containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function cancelService($package, $service, $parent_package = null, $parent_service = null)
{
// Set renewal mode to AUTOEXPIRE
return $this->suspendService($package, $service, $parent_package = null, $parent_service = null);
}
/**
* Suspends the service on the remote server. Sets Input errors on failure,
* preventing the service from being suspended.
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param stdClass $parent_package A stdClass object representing the parent
* service's selected package (if the current service is an addon service)
* @param stdClass $parent_service A stdClass object representing the parent
* service of the service being suspended (if the current service is an addon service)
* @return mixed null to maintain the existing meta fields or a numerically
* indexed array of meta fields to be stored for this service containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function suspendService($package, $service, $parent_package = null, $parent_service = null)
{
// Set renewal mode to AUTOEXPIRE
if ($package->meta->type === "domain") {
$row = $this->getModuleRow($package->module_row);
$fields = $this->serviceFieldsToObject($service->fields);
$this->_call([
"COMMAND" => "SetDomainRenewalMode",
"DOMAIN" => $fields->domain,
"RENEWALMODE" => "AUTOEXPIRE"
], $row);
if ($this->Input->errors()) {
return;
}
}
return null; // Nothing to do
}
/**
* Allows the module to perform an action when the service is ready to renew.
* Sets Input errors on failure, preventing the service from renewing.
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param stdClass $parent_package A stdClass object representing the parent
* service's selected package (if the current service is an addon service)
* @param stdClass $parent_service A stdClass object representing the parent
* service of the service being renewed (if the current service is an addon service)
* @return mixed null to maintain the existing meta fields or a numerically
* indexed array of meta fields to be stored for this service containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function renewService($package, $service, $parent_package = null, $parent_service = null, $years = null)
{
// Credentials to API
$row = $this->getModuleRow($package->module_row);
// Renew domain
if ($package->meta->type === "domain") {
$fields = $this->serviceFieldsToObject($service->fields);
$tld = trim($this->getTld($fields->domain), ".");
$sld = trim(substr($fields->domain, 0, -strlen($tld)), ".");
$vars["domain"] = $fields->{"domain"};
if ($years) {
$vars["NumYears"] = $years;
}
// Renew the domain
$r = $this->_call([
"COMMAND" => "RenewDomain",
"DOMAIN" => $vars["domain"],
"PERIOD" => $vars["NumYears"]
], $row);
// Some of the TLDs require following command for renewals (eg: .de)
if ($r["CODE"] === "510") {
// clear errors from previous call
$this->Input->setErrors([]);
$this->_call([
"COMMAND" => "PayDomainRenewal",
"DOMAIN" => $vars["domain"],
"PERIOD" => $vars["NumYears"]
], $row);
}
if ($this->Input->errors()) {
return;
}
}
return null;
}
/**
* Validates input data when attempting to add a package, returns the meta
* data to save when adding a package. Performs any action required to add
* the package on the remote server. Sets Input errors on failure,
* preventing the package from being added.
*
* @param array An array of key/value pairs used to add the package
* @return array A numerically indexed array of meta fields to be stored for this package containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function addPackage(array $vars = null)
{
$meta = [];
if (isset($vars["meta"]) && is_array($vars["meta"])) {
// Return all package meta fields
foreach ($vars["meta"] as $key => $value) {
$meta[] = [
"key" => $key,
"value" => $value,
"encrypted" => 0
];
}
}
return $meta;
}
/**
* Validates input data when attempting to edit a package, returns the meta
* data to save when editing a package. Performs any action required to edit
* the package on the remote server. Sets Input errors on failure,
* preventing the package from being edited.
*
* @param stdClass $package A stdClass object representing the selected package
* @param array An array of key/value pairs used to edit the package
* @return array A numerically indexed array of meta fields to be stored for this package containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function editPackage($package, array $vars = null)
{
$meta = [];
if (isset($vars["meta"]) && is_array($vars["meta"])) {
// Return all package meta fields
foreach ($vars["meta"] as $key => $value) {
$meta[] = [
"key" => $key,
"value" => $value,
"encrypted" => 0
];
}
}
return $meta;
}
/**
* Returns the rendered view of the manage module page
*
* @param mixed $module A stdClass object representing the module and its rows
* @param array $vars An array of post data submitted to or on the manage
* module page (used to repopulate fields after an error)
* @return string HTML content containing information to display when viewing the manager module page
*/
public function manageModule($module, array &$vars)
{
// TODO here we can introduce our own logic / action to
// * manage packages
// * add a manual sync
// * audit domains
// * etc.
// Load the view into this object, so helpers can be automatically added to the view
$this->view = new View("manage", "default");
$this->view->base_uri = $this->base_uri;
$this->view->setDefaultView(self::$defaultModuleView);
// Load the helpers required for this view
Loader::loadHelpers($this, ["Form", "Html", "Widget"]);
$this->view->set("module", $module);
return $this->view->fetch();
}
/**
* Returns the rendered view of the add module row page
*
* @param array $vars An array of post data submitted to or on the add
* module row page (used to repopulate fields after an error)
* @return string HTML content containing information to display when viewing the add module row page
*/
public function manageAddRow(array &$vars)
{
// TODO here we can introduce our own logic / action to
// * manage packages
// * add a manual sync
// * audit domains
// * etc.
// Load the view into this object, so helpers can be automatically added to the view
$this->view = new View("add_row", "default");
$this->view->base_uri = $this->base_uri;
$this->view->setDefaultView(self::$defaultModuleView);
// Load the helpers required for this view
Loader::loadHelpers($this, ["Form", "Html", "Widget"]);
// Set unspecified checkboxes
if (!empty($vars)) {
if (empty($vars["sandbox"])) {
$vars["sandbox"] = "false";
}
}
$this->view->set("vars", (object)$vars);
return $this->view->fetch();
}
/**
* Returns the rendered view of the edit module row page
*
* @param stdClass $module_row The stdClass representation of the existing module row
* @param array $vars An array of post data submitted to or on the edit
* module row page (used to repopulate fields after an error)
* @return string HTML content containing information to display when viewing the edit module row page
*/
public function manageEditRow($module_row, array &$vars)
{
// Load the view into this object, so helpers can be automatically added to the view
$this->view = new View("edit_row", "default");
$this->view->base_uri = $this->base_uri;
$this->view->setDefaultView(self::$defaultModuleView);
// Load the helpers required for this view
Loader::loadHelpers($this, ["Form", "Html", "Widget"]);
if (empty($vars)) {
$vars = $module_row->meta;
} elseif (empty($vars["sandbox"])) {
// Set unspecified checkboxes
$vars["sandbox"] = "false";
}
$this->view->set("vars", (object)$vars);
return $this->view->fetch();
}
/**
* Adds the module row on the remote server. Sets Input errors on failure,
* preventing the row from being added.
*
* @param array $vars An array of module info to add
* @return array A numerically indexed array of meta fields for the module row containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
*/
public function addModuleRow(array &$vars)
{
// TODO maybe syncing services
$meta_fields = ["user", "key", "sandbox"];//TODO maybe extending this
$encrypted_fields = ["key"];
// Set unspecified checkboxes
if (empty($vars["sandbox"])) {
$vars["sandbox"] = "false";
}
$this->Input->setRules($this->getRowRules($vars));
// Validate module row
if ($this->Input->validates($vars)) {
// Build the meta data for this row
$meta = [];
foreach ($vars as $key => $value) {
if (in_array($key, $meta_fields)) {
$meta[] = [
"key" => $key,
"value" => $value,
"encrypted" => in_array($key, $encrypted_fields) ? 1 : 0
];
}
}
return $meta;
}
}
/**
* Edits the module row on the remote server. Sets Input errors on failure,
* preventing the row from being updated.
*
* @param stdClass $module_row The stdClass representation of the existing module row
* @param array $vars An array of module info to update
* @return array A numerically indexed array of meta fields for the module row containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
*/
public function editModuleRow($module_row, array &$vars)
{
// Same as adding
return $this->addModuleRow($vars);
}
/**
* Returns the value used to identify a particular service (eg: domain name)
*
* @param stdClass $service A stdClass object representing the service
* @return string A value used to identify this service amongst other similar services
*/
public function getServiceName($service)
{
foreach ($service->fields as $field) {
if ($field->key === "domain") {
return $field->value;
}
}
return null;
}
/**
* Returns the value used to identify a particular package service which has
* not yet been made into a service. This may be used to uniquely identify
* an uncreated services of the same package (i.e. in an order form checkout)
*
* @param stdClass $package A stdClass object representing the selected package
* @param array $vars An array of user supplied info to satisfy the request
* @return string The value used to identify this package service
* @see Module::getServiceName()
*/
public function getPackageServiceName($packages, array $vars = null)
{
return (isset($vars["domain"])) ? $vars["domain"] : null;
}
/**
* Unsuspends the service on the remote server. Sets Input errors on failure,
* preventing the service from being unsuspended.
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param stdClass $parent_package A stdClass object representing the parent
* service's selected package (if the current service is an addon service)
* @param stdClass $parent_service A stdClass object representing the parent
* service of the service being unsuspended (if the current service is an addon service)
* @return mixed null to maintain the existing meta fields or a numerically
* indexed array of meta fields to be stored for this service containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function unsuspendService($package, $service, $parent_package = null, $parent_service = null)
{
return null; // Nothing to do
}
/**
* Updates the package for the service on the remote server. Sets Input
* errors on failure, preventing the service's package from being changed.
*
* @param stdClass $package_from A stdClass object representing the current package
* @param stdClass $package_to A stdClass object representing the new package
* @param stdClass $service A stdClass object representing the current service
* @param stdClass $parent_package A stdClass object representing the parent
* service's selected package (if the current service is an addon service)
* @param stdClass $parent_service A stdClass object representing the parent
* service of the service being changed (if the current service is an addon service)
* @return mixed null to maintain the existing meta fields or a numerically
* indexed array of meta fields to be stored for this service containing:
* - key The key for this meta field
* - value The value for this key
* - encrypted Whether or not this field should be encrypted (default 0, not encrypted)
* @see Module::getModule()
* @see Module::getModuleRow()
*/
public function changeServicePackage(
$package_from,
$package_to,
$service,
$parent_package = null,
$parent_service = null
) {
return null; // Nothing to do
}
/**
* Deletes the module row on the remote server. Sets Input errors on failure,
* preventing the row from being deleted.
*
* @param stdClass $module_row The stdClass representation of the existing module row
*/
public function deleteModuleRow($module_row)
{
//
}
/**
* Returns all fields used when adding/editing a package, including any
* javascript to execute when the page is rendered with these fields.
*
* @param $vars stdClass A stdClass object representing a set of post fields
* @return ModuleFields A ModuleFields object, containg the fields to render
* as well as any additional HTML markup to include
*/
public function getPackageFields($vars = null)
{
Loader::loadHelpers($this, ["Html"]);
// TODO loading packages available for server/server grp
$fields = new ModuleFields();
$types = [
"domain" => Language::_("Ispapi.package_fields.type_domain", true),
];
// Set type of package
$type = $fields->label(Language::_("Ispapi.package_fields.type", true), "ispapi_type");
$type->attach(
$fields->fieldSelect(
"meta[type]",
$types,
$vars->meta["type"] ?? null,
["id" => "ispapi_type"]
)
);
$fields->setField($type);
// Set all TLDs
$tld_options = $fields->label(Language::_("Ispapi.package_fields.tld_options", true));
$tlds = $this->getTlds();
// Set all TLDs Dropdown
// TODO may improve by setting labels
foreach ($tlds as $key => $val) {
$tlds_array[$val]=$val;
}
$tld_options->attach(
$fields->fieldSelect(//TODO fieldCheckbox ?
"meta[tlds][]",
$tlds_array,
$vars->meta["tlds"] ?? null,
[ "id"=>"tlds" ]
)
);
$fields->setField($tld_options);
// Set nameservers
for ($i=1; $i<=5; $i++) {
$type = $fields->label(Language::_("Ispapi.package_fields.ns" . $i, true), "ispapi_ns" . $i);
$type->attach(
$fields->fieldText(
"meta[ns][]",
$vars->meta["ns"][$i-1] ?? null,
["id" => "ispapi_ns" . $i]
)
);
$fields->setField($type);
}
$fields->setHtml("
<script type=\"text/javascript\">
$(document).ready(function() {
toggleTldOptions($('#ispapi_type').val());
// Re-fetch module options to pull cPanel packages and ACLs
$('#ispapi_type').change(function() {
toggleTldOptions($(this).val());
});
function toggleTldOptions(type) {
if (type === 'ssl')
$('.ispapi_tlds').hide();
else
$('.ispapi_tlds').show();
}
});
</script>
");
return $fields;
}
/**
* Returns all fields to display to an admin attempting to add a service with the module
*
* @param stdClass $package A stdClass object representing the selected package
* @param $vars stdClass A stdClass object representing a set of post fields
* @return ModuleFields A ModuleFields object, containg the fields to render as
* well as any additional HTML markup to include
*/
public function getAdminAddFields($package, $vars = null)
{
Loader::loadHelpers($this, [ "Form", "Html" ]);
// TODO separate handling of transfer request
if ($package->meta->type !== "domain") {
return new ModuleFields();
}
// Set default name servers
if (!isset($vars->ns1) && isset($package->meta->ns)) {
$i = 1;
foreach ($package->meta->ns as $ns) {
$vars->{"ns" . $i++} = $ns;
}
}
$fields = [
"domainoptions" => [
"label" => Language::_("Ispapi.domain.DomainAction", true),
"type" => "radio",
"value" => "1",
"options" => [
"1" => "Register",
"2" => "Transfer",
]
],
"domain" => [
"label" => Language::_("Ispapi.domain.domain", true),
"type" => "text"
],
"transfer_key" => [
"label" => Language::_("Ispapi.transfer.EPPCode", true),
"type" => "text"
]
];
//TODO: we might work on NS Fields
// Handle transfer request
if ((isset($vars->transfer) && $vars->transfer === "true")
|| !empty($vars->transfer_key)
) {
return $this->arrayToModuleFields(array_merge(
$fields,
Configure::get("Ispapi.transfer_fields"),
Configure::get("Ispapi.nameserver_fields")
), null, $vars);
}
// Handle domain registration
$module_fields = $this->arrayToModuleFields(array_merge(
$fields,
Configure::get("Ispapi.nameserver_fields")
), null, $vars);
// Additional domain fields
if (isset($vars->domain)) {
$tld = $this->getTld($vars->domain);
if ($tld) {
$extension_fields = array_merge(
(array)Configure::get("Ispapi.domain_fields" . $tld),
(array)Configure::get("Ispapi.contact_fields" . $tld)
);
if ($extension_fields) {
$module_fields = $this->arrayToModuleFields($extension_fields, $module_fields, $vars);
}
}
}
$module_fields->setHtml("
<script type=\"text/javascript\">
$(document).ready(function() {
$('#domainoptions_id').prop('checked', true);
$('#transfer_key_id').closest('li').hide();
// Set whether to show or hide the ACL option
$('#transfer_key_id').closest('li').hide();
$('input[name=\"domainoptions\"]').change(function() {
if ($(this).val() == '2')
$('#transfer_key_id').closest('li').show();
else
$('#transfer_key_id').closest('li').hide();
});
// Refresh the page when typed in domain name in in order to display additional fields
$('input[name=\"domain\"]').change(function(event) {
// do not refresh if domain has not actually changed (some change events are triggered automatically)
if (event.target.value.toLowerCase() === '" . ($vars->domain ?? '') . "'.toLowerCase()) return;
$('input[type=radio]').attr('checked',false);
var form = $(this).closest('form');
$(form).append('<input type=\"hidden\" name=\"refresh_fields\" value=\"true\">');
$(form).submit();
});
});
</script>
");
//TODO Build the domain fields
/*$fields = $this->buildDomainModuleFields($vars);
if ($fields) {
$module_fields = $fields;
}*/
return $module_fields;
}
/**
* Returns all fields to display to a client attempting to add a service with the module
*
* @param stdClass $package A stdClass object representing the selected package
* @param $vars stdClass A stdClass object representing a set of post fields
* @return ModuleFields A ModuleFields object, containg the fields to render
* as well as any additional HTML markup to include
*/
public function getClientAddFields($package, $vars = null)
{
// Handle domain name
if (isset($vars->domain)) {
$vars->domain = $vars->domain;
}
if ($package->meta->type !== "domain") {
return new ModuleFields();
}
// Set default name servers
if (!isset($vars->ns) && isset($package->meta->ns)) {
$i=1;
foreach ($package->meta->ns as $ns) {
$vars->{"ns" . $i++} = $ns;
}
}
// Handle transfer request
if (isset($vars->transfer)
|| isset($vars->transfer_key)
) {
$fields = array_merge(
Configure::get("Ispapi.transfer_fields"),
Configure::get("Ispapi.nameserver_fields")
);
// TODO: check .ca for whois privacy service
// shouldn't be supported
// $fields["private"]
// Already have the domain name don't make editable
$fields["domain"]["type"] = "hidden";
$fields["domain"]["label"] = null;
return $this->arrayToModuleFields($fields, null, $vars);
}
// Handle domain registration
$fields = array_merge(
Configure::get("Ispapi.nameserver_fields"),
Configure::get("Ispapi.domain_fields")
);
// TODO: check .ca for whois privacy service
// shouldn't be supported
// $fields["private"]
// Already have the domain name don't make editable
$fields["domain"]["type"] = "hidden";
$fields["domain"]["label"] = null;
$module_fields = $this->arrayToModuleFields($fields, null, $vars);
if (isset($vars->domain)) {
$tld = $this->getTld($vars->domain);
$extension_fields = Configure::get("Ispapi.domain_fields" . $tld);
if ($extension_fields) {
$module_fields = $this->arrayToModuleFields($extension_fields, $module_fields, $vars);
}
}
return $module_fields;
}
/**
* Returns all fields to display to an admin attempting to edit a service with the module
*
* @param stdClass $package A stdClass object representing the selected package
* @param $vars stdClass A stdClass object representing a set of post fields
* @return ModuleFields A ModuleFields object, containg the fields to render
* as well as any additional HTML markup to include
*/
public function getAdminEditFields($package, $vars = null)
{
Loader::loadHelpers($this, [ "Form", "Html" ]);
$fields = new ModuleFields();
// Create domain label
$domain = $fields->label(Language::_("Ispapi.manage.manual_renewal", true), "renew");
$row = $this->getModuleRow($package->module_row);
// Supported renewal periods of TLD
$r = $this->_call([
"COMMAND" => "QueryDomainOptions",
"DOMAIN0" => $vars->domain,
"PROPERTIES" => "LAUNCHPHASES"
], $row);
// renewal periods
$renewalperiods = explode(",", $r["PROPERTY"]["ZONERENEWALPERIODS"][0]);
array_unshift($renewalperiods, 0);
// Create domain field and attach to domain label
$domain->attach($fields->fieldSelect("renew", $renewalperiods, [ "id"=>"renew" ]));
$fields->setField($domain);
// Display domain information
$domain_information = $fields->label(Language::_("Ispapi.domain.domaininformation", true), "domaininformation");
// Domain status
$domain_status = $fields->label(Language::_("Ispapi.domain.domainstatus", true), "domainstatus");
// Expiry date
$expirydate = $fields->label(Language::_("Ispapi.domain.expirydate", true), "expirydate");
if ($package->meta->type === "domain") {
$r = $this->_call([
"COMMAND" => "StatusDomain",
"DOMAIN" => $vars->domain
], $row);
if ($r["CODE"] === "200") {
// Expiry date at our system [HM-696]
$r = $r["PROPERTY"];
$expirationdate = $r["EXPIRATIONDATE"][0];
$expirationts = strtotime($expirationdate);
$finalizationdate = $r["FINALIZATIONDATE"][0];
$paiduntildate = $r["PAIDUNTILDATE"][0];
$failuredate = $r["FAILUREDATE"][0];
// Status of the domain at our system
if (preg_match("/ACTIVE/i", $r["STATUS"][0])) {
$values["status"] = "Active";
}
if (preg_match("/DELETE/i", $r["STATUS"][0])) {
$values["expirydate"] = preg_replace("/ .*$/", "", $expirationdate);
$values["status"] = "Expired";
}
if ($failuredate > $paiduntildate) {
$values["expirydate"] = preg_replace("/ .*$/", "", $paiduntildate);
} else {
$finalizationts = strtotime($finalizationdate);
$paiduntilts = strtotime($paiduntildate);
$expirationts = $finalizationts + ($paiduntilts - $expirationts);
$values["expirydate"] = date("Y-m-d", $expirationts);
}
}
$domain_status->attach(
$fields->fieldText(
(isset($values["status"]) ? $values["status"] : ""),
[ "id"=>$values["status"] ],
[ "readonly"=>"readonly" ]
)
);
$expirydate->attach(
$fields->fieldText(
(isset($values["expirydate"]) ? $values["expirydate"] : ""),
["id"=>$values["expirydate"]],
["readonly"=>"readonly"]
)
);
}
$fields->setField($domain_information);
$fields->setField($domain_status);
$fields->setField($expirydate);
#return $fields;
return (isset($fields) ? $fields : new ModuleFields());
}
/**
* Fetches the HTML content to display when viewing the service info in the
* admin interface.
*
* @param stdClass $service A stdClass object representing the service
* @param stdClass $package A stdClass object representing the service's package
* @return string HTML content containing information to display when viewing the service info
*/
public function getAdminServiceInfo($service, $package)
{
return "";
}
/**
* Fetches the HTML content to display when viewing the service info in the
* client interface.
*
* @param stdClass $service A stdClass object representing the service
* @param stdClass $package A stdClass object representing the service's package
* @return string HTML content containing information to display when viewing the service info
*/
public function getClientServiceInfo($service, $package)
{
return "";
}
/**
* Returns all tabs to display to an admin when managing a service whose
* package uses this module
*
* @param stdClass $package A stdClass object representing the selected package
* @return array An array of tabs in the format of method => title.
* Example: [ "methodName" => "Title", "methodName2" => "Title2" ]
*/
public function getAdminTabs($package)
{
if ($package->meta->type === "domain") {
return [
"tabWhois" => Language::_("Ispapi.tab_whois.title", true),
"tabNameservers" => Language::_("Ispapi.tab_nameservers.title", true),
"tabSettings" => Language::_("Ispapi.tab_settings.title", true),
// TODO we might work on adding DNSSec, Hosts, DNS RR, Admin Actions
];
}
}
/**
* Returns all tabs to display to a client when managing a service whose
* package uses this module
*
* @param stdClass $package A stdClass object representing the selected package
* @return array An array of tabs in the format of method => title.
* Example: [ "methodName" => "Title", "methodName2" => "Title2" ]
*/
public function getClientTabs($package)
{
if ($package->meta->type === "domain") {
return [
"tabClientWhois" => Language::_("Ispapi.tab_whois.title", true),
"tabClientNameservers" => Language::_("Ispapi.tab_nameservers.title", true),
"tabClientSettings" => Language::_("Ispapi.tab_settings.title", true)
// TODO we might work on adding DNSSec, Hosts, DNS RR, Admin Actions
];
}
}
/**
* Admin Whois tab
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
public function tabWhois($package, $service, array $get = null, array $post = null, array $files = null)
{
return $this->manageWhois("tab_whois", $package, $service, $get, $post, $files);
}
/**
* Client Whois tab
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
public function tabClientWhois($package, $service, array $get = null, array $post = null, array $files = null)
{
return $this->manageWhois("tab_client_whois", $package, $service, $get, $post, $files);
}
/**
* Admin Nameservers tab
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
public function tabNameservers($package, $service, array $get = null, array $post = null, array $files = null)
{
return $this->manageNameservers("tab_nameservers", $package, $service, $get, $post, $files);
}
/**
* Admin Nameservers tab
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
public function tabClientNameservers($package, $service, array $get = null, array $post = null, array $files = null)
{
return $this->manageNameservers("tab_client_nameservers", $package, $service, $get, $post, $files);
}
/**
* Admin Settings tab
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
public function tabSettings($package, $service, array $get = null, array $post = null, array $files = null)
{
return $this->manageSettings("tab_settings", $package, $service, $get, $post, $files);
}
/**
* Client Settings tab
*
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
public function tabClientSettings($package, $service, array $get = null, array $post = null, array $files = null)
{
return $this->manageSettings("tab_client_settings", $package, $service, $get, $post, $files);
}
/**
* Handle updating whois information
*
* @param string $view The view to use
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
private function manageWhois($view, $package, $service, array $get = null, array $post = null, array $files = null)
{
$this->view = new View($view, "default");
// Load the helpers required for this view
Loader::loadHelpers($this, ["Form", "Html"]);
$row = $this->getModuleRow($package->module_row);
$vars = new stdClass();
$whois_fields = Configure::get("Ispapi.whois_fields");
$fields = $this->serviceFieldsToObject($service->fields);
$whois_sections = Configure::get("Ispapi.whois_sections");
$tld = trim($this->getTld($fields->domain), ".");
$sld = trim(substr($fields->domain, 0, -strlen($tld)), ".");
if (!empty($post)) {
// Modify/update contact/whois information
$command = [
"COMMAND" => "ModifyDomain",
"DOMAIN" => $fields->domain
];
$map = [
"OWNERCONTACT0" => "Registrant",
"ADMINCONTACT0" => "Admin",
"TECHCONTACT0" => "Tech",
"BILLINGCONTACT0" => "Billing",
];
foreach ($map as $ctype => $ptype) {
$command[$ctype] = [
"FIRSTNAME" => html_entity_decode($post[$ptype."FirstName"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"LASTNAME" => html_entity_decode($post[$ptype."LastName"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"ORGANIZATION" => html_entity_decode($post[$ptype."Organization"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"STREET" => html_entity_decode($post[$ptype."Address1"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"CITY" => html_entity_decode($post[$ptype."City"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"STATE" => html_entity_decode($post[$ptype."StateProvince"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"ZIP" => html_entity_decode($post[$ptype."PostalCode"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"COUNTRY" => html_entity_decode($post[$ptype."Country"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"PHONE" => html_entity_decode($post[$ptype."Phone"], ENT_QUOTES | ENT_XML1, "UTF-8"),
"EMAIL" => html_entity_decode($post[$ptype."EmailAddress"], ENT_QUOTES | ENT_XML1, "UTF-8"),
];
if (strlen($post[$ptype."Address2"])) {
$command[$ctype]["STREET"] .= " , ".html_entity_decode($post[$ptype."Address2"], ENT_QUOTES | ENT_XML1, "UTF-8");
}
}
$this->_call($command, $row);
$vars = (object)$post;
} else {
// To get the contact details of a domain, first perform a StatusDomain command and then use the data from StatusDomain to perform the StatusContact command.
$r = $this->_call([
"COMMAND" => "StatusDomain",
"DOMAIN" => $fields->domain,
], $row);
if ($r["CODE"] === "200") {
$contacts_array = [
"Registrant" => $r["PROPERTY"]["OWNERCONTACT"][0],
"Admin" => $r["PROPERTY"]["ADMINCONTACT"][0],
"Tech" => $r["PROPERTY"]["TECHCONTACT"][0],
"Billing" => $r["PROPERTY"]["BILLINGCONTACT"][0],
];
foreach ($contacts_array as $key => $contact) {
$r = $this->_call([
"COMMAND" => "StatusContact",
"CONTACT" => $contact,
], $row);
if ($r["CODE"] === "200") {
$data[$key] = $r["PROPERTY"];
}
}
// Display owner, tech and billing contact details
foreach ($whois_sections as $section) {
if (isset($data[$section])) {
foreach ($data[$section] as $name) {
$vars->{$section."FirstName"} = ($data[$section]["FIRSTNAME"] ? $data[$section]["FIRSTNAME"][0] : "");
$vars->{$section."LastName"} = ($data[$section]["LASTNAME"] ? $data[$section]["LASTNAME"][0] : "");
$vars->{$section."Organization"} = ($data[$section]["ORGANIZATION"] ? $data[$section]["ORGANIZATION"][0] : "");
if ((count($data[$section]["STREET"]) < 2) && preg_match("/^(.*) , (.*)/", $data[$section]["STREET"][0], $m)) {
$vars->{$section."Address1"} = $m[1];
$vars->{$section."Address2"} = $m[2];
} else {
$vars->{$section."Address1"} = ($data[$section]["STREET"] ? $data[$section]["STREET"][0] : "");
}
$vars->{$section."City"} = ($data[$section]["CITY"] ? $data[$section]["CITY"][0] : "");
$vars->{$section."StateProvince"} = ($data[$section]["STATE"] ? $data[$section]["STATE"][0] : "");
$vars->{$section."PostalCode"} = ($data[$section]["ZIP"] ? $data[$section]["ZIP"][0] : "");
$vars->{$section."Country"} = ($data[$section]["COUNTRY"] ? $data[$section]["COUNTRY"][0] : "");
$vars->{$section."Phone"} = ($data[$section]["PHONE"] ? $data[$section]["PHONE"][0] : "");
$vars->{$section."EmailAddress"} = ($data[$section]["EMAIL"] ? $data[$section]["EMAIL"][0] : "");
}
}
}
}
}
$this->view->set("vars", $vars);
$this->view->set("fields", $this->arrayToModuleFields($whois_fields, null, $vars)->getFields());
$this->view->set("sections", ["Registrant", "Admin", "Tech", "Billing"]);
$this->view->setDefaultView(self::$defaultModuleView);
return $this->view->fetch();
}
/**
* Handle updating nameserver information
*
* @param string $view The view to use
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
private function manageNameservers(
$view,
$package,
$service,
array $get = null,
array $post = null,
array $files = null
) {
$this->view = new View($view, "default");
// Load the helpers required for this view
Loader::loadHelpers($this, ["Form", "Html"]);
$vars = new stdClass();
$row = $this->getModuleRow($package->module_row);
$fields = $this->serviceFieldsToObject($service->fields);
if (!empty($post)) {
// Modify and save nameservers
$vars = $post;
// Default to using default nameservers
$vars["usedns"] = "Default";
foreach ($vars["ns"] as $i => $ns) {
if (!empty($ns)) {
$vars["ns" . ($i+1)] = $ns;
unset($vars["usedns"]);
}
}
unset($vars["ns"]);
$this->_call([
"COMMAND" => "ModifyDomain",
"DOMAIN" => $fields->domain,
"NAMESERVER" => [
$vars["ns1"],
$vars["ns2"],
$vars["ns3"],
$vars["ns4"],
$vars["ns5"]
],
"INTERNALDNS" => 1
], $row);
$vars = (object)$post;
} else {
// Get nameservers
$r = $this->_call([
"COMMAND" => "StatusDomain",
"DOMAIN" => $fields->domain,
], $row);
if ($r["CODE"] === "200"
&& isset($r["PROPERTY"]["NAMESERVER"])
) {
$vars->ns = $r["PROPERTY"]["NAMESERVER"];
}
}
$this->view->set("vars", $vars);
$this->view->setDefaultView(self::$defaultModuleView);
return $this->view->fetch();
}
/**
* Handle updating settings
*
* @param string $view The view to use
* @param stdClass $package A stdClass object representing the current package
* @param stdClass $service A stdClass object representing the current service
* @param array $get Any GET parameters
* @param array $post Any POST parameters
* @param array $files Any FILES parameters
* @return string The string representing the contents of this tab
*/
private function manageSettings(
$view,
$package,
$service,
array $get = null,
array $post = null,
array $files = null
) {
$this->view = new View($view, "default");
// Load the helpers required for this view
Loader::loadHelpers($this, ["Form", "Html"]);
$vars = new stdClass();
$row = $this->getModuleRow($package->module_row);
$fields = $this->serviceFieldsToObject($service->fields);
$tld = trim($this->getTld($fields->domain), ".");
$sld = trim(substr($fields->domain, 0, -strlen($tld)), ".");
// Whois privacy settings of a TLD
$r = $this->_call([
"COMMAND" => "QueryDomainOptions",
"DOMAIN0" => $fields->domain,
"PROPERTIES" => "LAUNCHPHASES"
], $row);
// Display whois_privacy setting for the domain if it is supported
if (!empty($r["PROPERTY"]["X-PROXY"][0])) {
$vars->{"whois_privacy_supported"} = "yes";
}
// Status domain
$r = $this->_call([
"COMMAND" => "StatusDomain",
"DOMAIN" => $fields->domain
], $row);
if (empty($post)) {
// Get transferlock and whois privacy settings information
if ($r["CODE"] === "200") {
$vars->registrar_lock = ($r["PROPERTY"]["TRANSFERLOCK"][0] === "1") ? "true" : "false";
// Whois privacy
$vars->whois_privacy = ($r["PROPERTY"]["X-ACCEPT-WHOISTRUSTEE-TAC"][0] === "1") ? "true" : "false";
}
$this->view->set("vars", $vars);
$this->view->setDefaultView(self::$defaultModuleView);
return $this->view->fetch();
}
// Post values to var variable
$vars->registrar_lock = $post["registrar_lock"];
$vars->whois_privacy = $post["whois_privacy"];
// To get epp/auth code
if (isset($post["request_epp"]) && !isset($post["save"])) {
// Expiring Authorization Codes
// https://confluence.centralnic.com/display/RSR/Expiring+Authcodes
// pending cases:
// - RSRBE-3774
// - RSRBE-3753
$response = $r;//StatusDomain
if (preg_match("/\.de$/i", $fields->domain)) {
$response = $this->_call([
"COMMAND" => "DENIC_CreateAuthInfo1",
"DOMAIN" => $fields->domain
], $row);
} elseif (preg_match("/\.(eu|be)$/i", $fields->domain)) {
$response = $this->_call([
"COMMAND" => "RequestDomainAuthInfo",
"DOMAIN" => $fields->domain
], $row);
// TODO -> PENDING = 1|0
}
// check response
if ($response["CODE"] === "200") {
if (preg_match("/\.(fi|nz)$/i", $fields->domain)
&& ($response["PROPERTY"]["TRANSFERLOCK"][0] === "1")
) {
$this->Input->setErrors([
"errors" => ["Failed loading the epp code. Please unlock this domain name first. A new epp code will then be generated and provided here."]
]);
} elseif (!isset($response["PROPERTY"]["AUTH"][0])) {
$this->Input->setErrors([
"errors" => ["EPP Code has been send to registrant by email."]
]);
} elseif (!strlen($response["PROPERTY"]["AUTH"][0])) {
$this->Input->setErrors([
"errors" => ["No AuthInfo code assigned to this domain name. Contact Support."]
]);
} else {
$vars->{"auth"} = $response["PROPERTY"]["AUTH"][0];
}
} else {
$this->Input->setErrors([
"errors" => ["Failed loading the epp code (" . $response["DESCRIPTION"] . ")."]
]);
}
}
// Save transferlock settings of a domain
if ((isset($post["registrar_lock"]) || isset($post["whois_privacy"])) && isset($post["save"])) {
$command = [
"COMMAND" => "ModifyDomain",
"DOMAIN" => $fields->domain,
"TRANSFERLOCK" => $post["registrar_lock"] == "true" ? "1" : "0",
];
if ($vars->whois_privacy_supported) {
$command["X-ACCEPT-WHOISTRUSTEE-TAC"] = $post["whois_privacy"] == "true" ? "1" : "0";
}
$this->_call($command, $row);
}
$this->view->set("vars", $vars);
$this->view->setDefaultView(self::$defaultModuleView);
return $this->view->fetch();
}
/**
* Performs a whois lookup on the given domain
*
* @param string $domain The domain to lookup
* @param int $module_row_id The ID of the module row to fetch for the current module
* @return bool True if available, false otherwise
*/
public function checkAvailability($domain, $module_row_id = null)
{
$row = $this->getModuleRow();
$r = $this->_call([
"COMMAND" => "CheckDomains",
"DOMAIN0" => $domain,
"PREMIUMCHANNELS" => "*"
], $row);
if ($r["CODE"] !== "200") {
$this->Input->setErrors([
"errors" => [ $domain . ": " . $r["DESCRIPTION"] ]
]);
return false;
}
if (empty($r["PROPERTY"]["DOMAINCHECK"][0])) {
return false;
}
$fulldc = $r["PROPERTY"]["DOMAINCHECK"][0];
$dc = substr($fulldc, 0, 3);
if ($dc === "210") {//AVAILABLE
return true;
}
$error = false;
if ($dc === "549") {
$error = $domain . ": Unsupported TLD or availability lookup failed";
} elseif ($dc === "211") {
if (preg_match("/block/", $r["PROPERTY"]["REASON"][0])) {// CASE: DOMAIN BLOCK
//$error = $domain . ": Reserved Domain (Domain Block).";
} elseif (preg_match("/^Collision Domain name available \{/i", substr($fulldc, 3))) {// CASE: NXD DOMAIN
//$error = $domain . ": Reserved Domain (Collision Domain).";
} elseif (!empty($r["PROPERTY"]["PREMIUMCHANNEL"][0])) {// CASE: PREMIUM
$this->Input->setErrors([
"errors" => [ $domain . ": Premium Domain. Contact Support." ]
]);
} elseif (!empty($r["PROPERTY"]["CLASS"][0]) // CASE: RESERVED or PREMIUM? BACKORDER
&& stripos($r["PROPERTY"]["REASON"][0], "reserved") //RESERVED
) {
$this->Input->setErrors([
"errors" => [ $domain . ": Reserved Domain. Contact Support." ]
]);
}
}
return false;
}
/**
* Gets the domain expiration date
*
* @param stdClass $service The service belonging to the domain to lookup
* @param string $format The format to return the expiration date in
* @return string The domain expiration date in UTC time in the given format
* @see Services::get()
*/
public function getExpirationDate($service, $format = "Y-m-d H:i:s")
{
Loader::loadHelpers($this, ["Date"]);
$domain = $this->getServiceDomain($service);
$row = $this->getModuleRow($service->module_row_id ?? null);
$r = $this->_call([
"COMMAND" => "StatusDomain",
"DOMAIN" => $domain,
], $row);
if ($r["CODE"] !== "200") {//TODO expired cases
return false;
}
// cast our UTC API timestamp format to useful formats in local timezone
$expirationdate = $this->_castDate($r["PROPERTY"]["EXPIRATIONDATE"][0], $format);
$finalizationdate = $this->_castDate($r["PROPERTY"]["FINALIZATIONDATE"][0], $format);
$paiduntildate = $this->_castDate($r["PROPERTY"]["PAIDUNTILDATE"][0], $format);
$failuredate = $this->_castDate($r["PROPERTY"]["FAILUREDATE"][0], $format);
if ($failuredate["ts"] > $paiduntildate["ts"]) {
$expirydate = $paiduntildate;
} else {
$ts = $finalizationdate["ts"] + ($paiduntildate["ts"] - $expirationdate["ts"]);
$expirydate = gmdate($format, $ts);
}
return $this->Date->format($format, $expirydate);
}
/**
* Gets the domain name from the given service
*
* @param stdClass $service The service from which to extract the domain name
* @return string The domain name associated with the service
*/
public function getServiceDomain($service)
{
if (isset($service->fields)) {
foreach ($service->fields as $service_field) {
if ($service_field->key === "domain") {
return $service_field->value;
}
}
}
return $this->getServiceName($service);
}
/**
* Get a list of the TLDs supported by the registrar module
*
* @param int $module_row_id The ID of the module row to fetch for the current module
* @return array A list of all TLDs supported by the registrar module
*/
public function getTlds($module_row_id = null)
{
$row = $this->getModuleRow($module_row_id);
$row = !empty($row) ? $row : $this->getModuleRows()[0];
if (empty($row)) {
return [];
}
// Fetch the TLDs results from the cache, if they exist
$cache = Cache::fetchCache(
"tlds",
Configure::get("Blesta.company_id") . DS . "modules" . DS . "ispapi" . DS
);
if ($cache) {
return unserialize(base64_decode($cache));
}
// Fetch ispapi TLDs
$r = $this->_call([
"COMMAND" => "StatusUser"
], $row);
// Handling api errors
if ($r["CODE"] !== "200") {
return [];
}
$tldclassmap = Configure::get("Ispapi.tldclassmap");
$tlds = [];
foreach ($r["PROPERTY"]["RELATIONTYPE"] as $idx => $t) {
if (preg_match("/^PRICE_CLASS_(MANAGED)?DOMAIN_([^_]+)_(SETUP|CREATE)$/", $t, $m)) {
// block relation just leads to not getting the relation returned
$tldclass = $m[2];
if (isset($tldclassmap[$tldclass])) {
$tlds[] = $tldclassmap[$tldclass];
} else {
$tlds[] = "." . strtolower($tldclass);
}
}
}
// cleanup and sort list of tlds
$tlds = array_values(array_unique($tlds));
usort($tlds, function ($tld1, $tld2) {
$a = implode(".", array_reverse(explode(".", $tld1)));//com, uk.co
$b = implode(".", array_reverse(explode(".", $tld2)));//ca, de.com
if ($a === $b) {
return 0;
}
return ($a > $b) ? 1 : -1;
});
// Save the TLDs results to the cache
if (count($tlds) > 0) {
if (Configure::get("Caching.on") && is_writable(CACHEDIR)) {
try {
Cache::writeCache(
"tlds",
base64_encode(serialize($tlds)),
strtotime(Configure::get("Blesta.cache_length")) - time(),
Configure::get("Blesta.company_id") . DS . "modules" . DS . "ispapi" . DS
);
} catch (Exception $e) {
// Write to cache failed, so disable caching
Configure::set("Caching.on", false);
}
}
}
return $tlds;
}
/**
* Builds and returns the rules required to add/edit a module row
*
* @param array $vars An array of key/value data pairs
* @return array An array of Input rules suitable for Input::setRules()
*/
private function getRowRules(&$vars)
{
return [
"user" => [
"valid" => [
"rule" => "isEmpty",
"negate" => true,
"message" => Language::_("Ispapi.!error.user.valid", true)
]
],
"key" => [
"valid" => [
"last" => true,
"rule" => "isEmpty",
"negate" => true,
"message" => Language::_("Ispapi.!error.key.valid", true)
],
"valid_connection" => [
"rule" => [
[$this, "validateConnection"],
$vars["user"],
isset($vars["sandbox"]) ? $vars["sandbox"] : "false"
],
"message" => Language::_("Ispapi.!error.key.valid_connection", true)
]
]
];
}
/**
* Validates that the given connection details
*
* @param string $key The API key
* @param string $user The API user
* @param string $sandbox "true" if this is a sandbox account, false otherwise
* @return bool True if the connection details are valid, false otherwise
*/
public function validateConnection($key, $user, $sandbox)
{
$row = json_decode(json_encode([
"meta" => [
"user" => $user,
"key" => $key,
"sandbox" => $sandbox
]
]));
$r = $this->_call([
"COMMAND" => "CheckAuthentication",
"SUBUSER" => $user,
"PASSWORD" => $key
], $row);
if ($r["CODE"] !== "200") {
return null;
}
// Workarround to call that only 1 time.
static $included = false;
if (!$included) {
$included = true;
$values = [
"blesta" => BLESTA_VERSION,
"updated_date" => gmdate("Y-m-d H:i:s"),
"ispapi_version" => $this->getVersion(),
"php_version" => implode(".", [PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION]),
"os" => php_uname("s")
// TODO pf
];
$command = [
"COMMAND" => "SetEnvironment",
];
$i=0;
$envkey = "middleware/blesta/" . $_SERVER["HTTP_HOST"];
foreach ($values as $key => $value) {
$command["ENVIRONMENTKEY$i"] = $envkey;
$command["ENVIRONMENTNAME$i"] = $key;
$command["ENVIRONMENTVALUE$i"] = $value;
$i++;
}
$this->_call($command, $row);
}
return "OK";
}
/**
* Returns the TLD of the given domain
*
* @param string $domain The domain to return the TLD from
* @return string The TLD of the domain
*/
private function getTld($domain)
{
$tlds = $this->getTlds();
$domain = strtolower($domain);
foreach ($tlds as $tld) {
if (substr($domain, -strlen($tld)) === $tld) {
return $tld;
}
}
return strstr($domain, ".");
}
/**
* Formats a phone number into +NNN.NNNNNNNNNN
*
* @param string $number The phone number
* @param string $country The ISO 3166-1 alpha2 country code
* @return string The number in +NNN.NNNNNNNNNN
*/
private function formatPhone($number, $country)
{
if (!isset($this->Contacts)) {
Loader::loadModels($this, ["Contacts"]);
}
return $this->Contacts->intlNumber($number, $country, ".");
}
//TODO install, upgrade, uninstall, cron
//cron to be used to sync expiration date?
/**
* Sends an email to the debug address with the given data
*
* @param mixed $data The data to send
*/
public function debug($data)
{
file_put_contents("/tmp/dump.txt", var_export($data, true));
}
}
<file_sep>#!/bin/bash
sudo cp -R ~/git/blesta-ispapi-registrar/components/modules/ispapi /var/www/blesta/components/modules
sudo chown -R www-data.www-data /var/www/blesta/components/modules/ispapi
<file_sep>## [3.0.5](https://github.com/hexonet/blesta-ispapi-registrar/compare/v3.0.4...v3.0.5) (2022-06-14)
### Bug Fixes
* **ci:** review build tool dependencies and test release process (no need to upgrade!) ([f62a438](https://github.com/hexonet/blesta-ispapi-registrar/commit/f62a438bf8c48a11eee50788dc45bb4d51331042))
## [3.0.4](https://github.com/hexonet/blesta-ispapi-registrar/compare/v3.0.3...v3.0.4) (2021-11-30)
### Bug Fixes
* **renewService:** fix PayDomainRenewal ([611456d](https://github.com/hexonet/blesta-ispapi-registrar/commit/611456deb7161fe558c723c1f6b772ffa2026046))
## [3.0.3](https://github.com/hexonet/blesta-ispapi-registrar/compare/v3.0.2...v3.0.3) (2021-11-09)
### Bug Fixes
* **checkavailability:** minor review (no nxd, domain blocks) ([f9e4198](https://github.com/hexonet/blesta-ispapi-registrar/commit/f9e41980fe9e05387f2923f03129d5d9da49a20e))
## [3.0.2](https://github.com/hexonet/blesta-ispapi-registrar/compare/v3.0.1...v3.0.2) (2021-10-20)
### Bug Fixes
* **getAdminAddFields:** fix endless-loop ([da39265](https://github.com/hexonet/blesta-ispapi-registrar/commit/da39265e7ee15ef648de308189a7f50cc7ba3437))
## [3.0.1](https://github.com/hexonet/blesta-ispapi-registrar/compare/v3.0.0...v3.0.1) (2021-08-12)
### Bug Fixes
* **build:** fixed archive file list globbing to fully including our SDKs source files ([b6600ee](https://github.com/hexonet/blesta-ispapi-registrar/commit/b6600ee39854b70329acf03b142b0201d912e986))
# [3.0.0](https://github.com/hexonet/blesta-ispapi-registrar/compare/v2.0.3...v3.0.0) (2021-08-10)
### Features
* **php-sdk:** migration to our API Connector ([c96918a](https://github.com/hexonet/blesta-ispapi-registrar/commit/c96918ae9d4bb1275ea7a2b828cea3b97d6efbfe))
### BREAKING CHANGES
* **php-sdk:** API Class Instantiation, Communication and Logging has been revamped from scratch.
## [2.0.3](https://github.com/hexonet/blesta-ispapi-registrar/compare/v2.0.2...v2.0.3) (2021-08-06)
### Bug Fixes
* **gettlds:** order the list of TLDs more nicely ([0553d12](https://github.com/hexonet/blesta-ispapi-registrar/commit/0553d12779e66f239084ae790731e9d76d79ac34))
## [2.0.2](https://github.com/hexonet/blesta-ispapi-registrar/compare/v2.0.1...v2.0.2) (2021-08-05)
### Bug Fixes
* **ci:** include updated config.json in version commit ([8bef494](https://github.com/hexonet/blesta-ispapi-registrar/commit/8bef494765fb448ace47fb38c18b46be40fd48e0))
## [2.0.1](https://github.com/hexonet/blesta-ispapi-registrar/compare/v2.0.0...v2.0.1) (2021-08-05)
### Bug Fixes
* **gettlds:** fixed building list of supported TLDs ([b1b286d](https://github.com/hexonet/blesta-ispapi-registrar/commit/b1b286df9b64049e778a23316c5c52bb6b7bc16c))
# [2.0.0](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.3.3...v2.0.0) (2021-08-05)
### Features
* **blesta 5.2:** initial revamp ([e2147b6](https://github.com/hexonet/blesta-ispapi-registrar/commit/e2147b61a7de9eff73a4121c394f95a6cd7b37a6))
### BREAKING CHANGES
* **blesta 5.2:** Reviewed to be compatible with Blesta 5.2.
## [1.3.3](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.3.2...v1.3.3) (2021-02-01)
### Bug Fixes
* **.my / .ae / .qa:** added requested TLDs (.my, .ae, .qa) - more to come ([27b8c03](https://github.com/hexonet/blesta-ispapi-registrar/commit/27b8c034e7a7924cbb5a0411f53cf0524b01329d)), closes [#86](https://github.com/hexonet/blesta-ispapi-registrar/issues/86)
## [1.3.2](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.3.1...v1.3.2) (2021-01-27)
### Bug Fixes
* **ci:** migrated to gh actions and gulp; reviewed folder structure; ([93cc220](https://github.com/hexonet/blesta-ispapi-registrar/commit/93cc220c039d46a36957b54ac2e7c810fb6ae729))
* **github actions:** fixed archives; excluded vendor folder ([d2b4125](https://github.com/hexonet/blesta-ispapi-registrar/commit/d2b41259d62a27398227ee5c7e747a79b6cd2c4f))
## [1.3.1](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.3.0...v1.3.1) (2020-03-23)
### Bug Fixes
* **expiry-date:** expiry date auto-detection ([40599bc](https://github.com/hexonet/blesta-ispapi-registrar/commit/40599bc6cc01d31b5c3d0129e0f220359065704f))
# [1.3.0](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.2.2...v1.3.0) (2020-02-26)
### Features
* **transfer:** auto-detection for 0Y period, Transfer domain checks ([434d1e3](https://github.com/hexonet/blesta-ispapi-registrar/commit/434d1e380685c7fb3f42ae0a43e645ac0edff0f4))
## [1.2.2](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.2.1...v1.2.2) (2019-09-30)
### Bug Fixes
* **DomainTransfers:** send required contact data for domain transfers ([9e52790](https://github.com/hexonet/blesta-ispapi-registrar/commit/9e52790))
## [1.2.1](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.2.0...v1.2.1) (2019-09-19)
### Bug Fixes
* **release proccess:** fix composer binary path ([774aca0](https://github.com/hexonet/blesta-ispapi-registrar/commit/774aca0))
* **release process:** migrate configuration ([9489f31](https://github.com/hexonet/blesta-ispapi-registrar/commit/9489f31))
# [1.2.0](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.1.5...v1.2.0) (2019-09-05)
### Features
* **user-transfer:** support for user transfers ([1ef7171](https://github.com/hexonet/blesta-ispapi-registrar/commit/1ef7171))
## [1.1.5](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.1.4...v1.1.5) (2019-07-19)
### Bug Fixes
* **pkg:** bug fixes in 'Settings' tab, contact data and module log information ([04585f2](https://github.com/hexonet/blesta-ispapi-registrar/commit/04585f2))
## [1.1.4](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.1.3...v1.1.4) (2019-04-26)
### Bug Fixes
* **pkg:** added Blesta version in the user enviroment ([93141cc](https://github.com/hexonet/blesta-ispapi-registrar/commit/93141cc))
## [1.1.3](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.1.2...v1.1.3) (2019-02-01)
### Bug Fixes
* **pkg:** added user environment logging ([861a7ae](https://github.com/hexonet/blesta-ispapi-registrar/commit/861a7ae))
## [1.1.2](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.1.1...v1.1.2) (2018-12-24)
### Bug Fixes
* **pkg:** Makefile update, removed README.pdf, .odt file and pkg folder ([8c8d293](https://github.com/hexonet/blesta-ispapi-registrar/commit/8c8d293))
## [1.1.1](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.1.0...v1.1.1) (2018-12-14)
### Bug Fixes
* **pkg:** modified package.json to include zip files in the release ([ca55c51](https://github.com/hexonet/blesta-ispapi-registrar/commit/ca55c51))
# [1.1.0](https://github.com/hexonet/blesta-ispapi-registrar/compare/v1.0.0...v1.1.0) (2018-12-14)
### Features
* **pkg:** Added Makefile ([2ece17c](https://github.com/hexonet/blesta-ispapi-registrar/commit/2ece17c))
# 1.0.0 (2018-12-12)
### Bug Fixes
* **pkg:** added .gitignore file ([09d86a1](https://github.com/hexonet/blesta-ispapi-registrar/commit/09d86a1))
* **pkg:** added evaluation on registration and renewal periods acc. QueryDomainOptions ([c7722e5](https://github.com/hexonet/blesta-ispapi-registrar/commit/c7722e5))
* **pkg:** fixed a bug in admin settings tab ([cb336b1](https://github.com/hexonet/blesta-ispapi-registrar/commit/cb336b1))
<file_sep><?php
/**
* @copyright Copyright (c) 2018-2021, HEXONET
* @license https://raw.githubusercontent.com/hexonet/blesta-ispapi-registrar/master/LICENSE MIT
*/
// All available TLDs
Configure::set('Ispapi.tldclassmap', [
"ACIM" => ".ac.im",
"ACMU" => ".ac.mu",
"ACNZ" => ".ac.nz",
"AAAPRO" => ".aaa.pro",
"ACAPRO" => ".aca.pro",
"ACCTPRO" => ".acct.pro",
"ADULTHT" => ".adult.ht",
"AEORG" => ".ae.org",
"ARCOM" => ".ar.com",
"ARCPRO" => ".arc.pro",
"ARTHT" => ".art.ht",
"ARTSNF" => ".arts.nf",
"ASSOHT" => ".asso.ht",
"AVOCATPRO" => ".avocat.pro",
"BARPRO" => ".bar.pro",
"BIZKI" => ".biz.ki",
"BIZPL" => ".biz.pl",
"BIZPR" => ".biz.pr",
"BRCOM" => ".br.com",
"CLUBTW" => ".club.tw",
"COAE" => ".co.ae",
"COAG" => ".co.ag",
"COAM" => ".co.am",
"COAT" => ".co.at",
"COBZ" => ".co.bz",
"COCM" => ".co.cm",
"COCOM" => ".co.com",
"COGG" => ".co.gg",
"COGL" => ".co.gl",
"COGY" => ".co.gy",
"COIM" => ".co.im",
"COIN" => ".co.in",
"COJE" => ".co.je",
"COJP" => ".co.jp",
"COKR" => ".co.kr",
"COLC" => ".co.lc",
"COMAF" => ".com.af",
"COMBR" => ".com.br",
"COMAG" => ".com.ag",
"COMAI" => ".com.ai",
"COMAM" => ".com.am",
"COMAR" => ".com.ar",
"COMAU" => ".com.au",
"COMBZ" => ".com.bz",
"COMCM" => ".com.cm",
"COMCN" => ".com.cn",
"COMCO" => ".com.co",
"COMDE" => ".com.de",
"COMEC" => ".com.ec",
"COMES" => ".com.es",
"COMFR" => ".com.fr",
"COMG" => ".co.mg",
"COMU" => ".co.mu",
"COMGL" => ".com.gl",
"COMGR" => ".com.gr",
"COMGY" => ".com.gy",
"COMHK" => ".com.hk",
"COMHN" => ".com.hn",
"COMHT" => ".com.ht",
"COMIM" => ".com.im",
"COMKI" => ".com.ki",
"COMLC" => ".com.lc",
"COMLV" => ".com.lv",
"COMMG" => ".com.mg",
"COMMS" => ".com.ms",
"COMMT" => ".com.mt",
"COMMU" => ".com.mu",
"COMMX" => ".com.mx",
"COMMY" => ".com.my",
"COMNF" => ".com.nf",
"COMPE" => ".com.pe",
"COMPH" => ".com.ph",
"COMPL" => ".com.pl",
"COMPR" => ".com.pr",
"COMPT" => ".com.pt",
"COMRE" => ".com.re",
"COMRO" => ".com.ro",
"COMRU" => ".com.ru",
"COMUA" => ".com.ua",
"COMS" => ".co.ms",
"COMSB" => ".com.sb",
"COMSC" => ".com.sc",
"COMSE" => ".com.se",
"COMSG" => ".com.sg",
"COMSO" => ".com.so",
"COMTC" => ".com.tc",
"COMTW" => ".com.tw",
"COMVC" => ".com.vc",
"COMVE" => ".com.ve",
"CONL" => ".co.nl",
"CONZ" => ".co.nz",
"COUK" => ".co.uk",
"COVE" => ".co.ve",
"COZA" => ".co.za",
"CNCOM" => ".cn.com",
"CPAPRO" => ".cpa.pro",
"DDSPRO" => ".dds.pro",
"DECOM" => ".de.com",
"DENPRO" => ".den.pro",
"DNTPRO" => ".dnt.pro",
"EBIZTW" => ".ebiz.tw",
"EBIZTW" => ".ebiz.tw",
"EDUCO" => ".edu.co",
"ENGPRO" => ".eng.pro",
"EPPUA" => ".epp.ua",
"EUCOM" => ".eu.com",
"FINEC" => ".fin.ec",
"FIRMHT" => ".firm.ht",
"FIRMIN" => ".firm.in",
"FIRMNF" => ".firm.nf",
"GAMETW" => ".game.tw",
"GBCOM" => ".gb.com",
"GBNET" => ".gb.net",
"GEEKNZ" => ".geek.nz",
"GENIN" => ".gen.in",
"GENNZ" => ".gen.nz",
"GOVCO" => ".gov.co",
"GRCOM" => ".gr.com",
"HUCOM" => ".hu.com",
"HUNET" => ".hu.net",
"IDAU" => ".id.au",
"IDVTW" => ".idv.tw",
"INDIN" => ".ind.in",
"INFOEC" => ".info.ec",
"INFOHT" => ".info.ht",
"INFOKI" => ".info.ki",
"INFONF" => ".info.nf",
"INFOPL" => ".info.pl",
"INFOPR" => ".info.pr",
"INFOVE" => ".info.ve",
"INFOVN" => ".info.vn",
"INGPRO" => ".ing.pro",
"INNET" => ".in.net",
"JPNET" => ".jp.net",
"JPNCOM" => ".jpn.com",
"JURPRO" => ".jur.pro",
"KIWINZ" => ".kiwi.nz",
"KRCOM" => ".kr.com",
"LAWPRO" => ".law.pro",
"LTDCOIM" => ".ltd.co.im",
"LTDIM" => ".ltd.im",
"LTDUK" => ".ltd.uk",
"MAORINZ" => ".maori.nz",
"MEDEC" => ".med.ec",
"MEDPRO" => ".med.pro",
"MEUK" => ".me.uk",
"MEXCOM" => ".mex.com",
"MILCO" => ".mil.co",
"MOBIKI" => ".mobi.ki",
"NAMEPR" => ".name.pr",
"NAMESLD" => ".name",
"NETAE" => ".net.ae",
"NETAF" => ".net.af",
"NETAG" => ".net.ag",
"NETAI" => ".net.ai",
"NETAM" => ".net.am",
"NETAU" => ".net.au",
"NETBR" => ".net.br",
"NETBZ" => ".net.bz",
"NETCO" => ".net.co",
"NETCM" => ".net.cm",
"NETCN" => ".net.cn",
"NETEC" => ".net.ec",
"NETGG" => ".net.gg",
"NETGL" => ".net.gl",
"NETGY" => ".net.gy",
"NETHN" => ".net.hn",
"NETHT" => ".net.ht",
"NETIM" => ".net.im",
"NETIN" => ".net.in",
"NETJE" => ".net.je",
"NETKI" => ".net.ki",
"NETLC" => ".net.lc",
"NETLV" => ".net.lv",
"NETMG" => ".net.mg",
"NETMU" => ".net.mu",
"NETMY" => ".net.my",
"NETMX" => ".net.mx",
"NETNF" => ".net.nf",
"NETNZ" => ".net.nz",
"NETPE" => ".net.pe",
"NETPH" => ".net.ph",
"NETPL" => ".net.pl",
"NETPR" => ".net.pr",
"NETRU" => ".net.ru",
"NETSB" => ".net.sb",
"NETSC" => ".net.sc",
"NETSO" => ".net.so",
"NETTC" => ".net.tc",
"NETVC" => ".net.vc",
"NETVE" => ".net.ve",
"NETZA" => ".net.za",
"NOCOM" => ".no.com",
"NOMAG" => ".nom.ag",
"NOMCO" => ".nom.co",
"NOMES" => ".nom.es",
"NOMPE" => ".nom.pe",
"NOMRO" => ".nom.ro",
"OFFAI" => ".off.ai",
"ORAT" => ".or.at",
"ORJP" => ".or.jp",
"ORMU" => ".or.mu",
"ORGAE" => ".org.ae",
"ORGAF" => ".org.af",
"ORGAG" => ".org.ag",
"ORGAI" => ".org.ai",
"ORGAM" => ".org.am",
"ORGAU" => ".org.au",
"ORGBZ" => ".org.bz",
"ORGCN" => ".org.cn",
"ORGCO" => ".org.co",
"ORGES" => ".org.es",
"ORGGG" => ".org.gg",
"ORGGL" => ".org.gl",
"ORGGR" => ".org.gr",
"ORGHT" => ".org.ht",
"ORGHN" => ".org.hn",
"ORGIM" => ".org.im",
"ORGIN" => ".org.in",
"ORGJE" => ".org.je",
"ORGKI" => ".org.ki",
"ORGLC" => ".org.lc",
"ORGLV" => ".org.lv",
"ORGMG" => ".org.mg",
"ORGMS" => ".org.ms",
"ORGMU" => ".org.mu",
"ORGMX" => ".org.mx",
"ORGMY" => ".org.my",
"ORGNZ" => ".org.nz",
"ORGPE" => ".org.pe",
"ORGPH" => ".org.ph",
"ORGPL" => ".org.pl",
"ORGPR" => ".org.pr",
"ORGPT" => ".org.pt",
"ORGRO" => ".org.ro",
"ORGRU" => ".org.ru",
"ORGSB" => ".org.sb",
"ORGSC" => ".org.sc",
"ORGSO" => ".org.so",
"ORGTC" => ".org.tc",
"ORGTW" => ".org.tw",
"ORGUA" => ".org.ua",
"ORGUK" => ".org.uk",
"ORGVC" => ".org.vc",
"ORGVE" => ".org.ve",
"ORGWS" => ".org.ws",
"ORGZA" => ".org.za",
"OTHERNF" => ".other.nf",
"PERNF" => ".per.nf",
"PERSOHT" => ".perso.ht",
"PHONEKI" => ".phone.ki",
"PLCCOIM" => ".plc.co.im",
"PLCUK" => ".plc.uk",
"POLHT" => ".pol.ht",
"PPRU" => ".pp.ru",
"PROEC" => ".pro.ec",
"PROHT" => ".pro.ht",
"PROPR" => ".pro.pr",
"PROTC" => ".pro.tc",
"QCCOM" => ".qc.com",
"RADIOAM" => ".radio.am",
"RADIOFM" => ".radio.fm",
"RECHTPRO" => ".recht.pro",
"RECNF" => ".rec.nf",
"RELHT" => ".rel.ht",
"RUCOM" => ".ru.com",
"SACOM" => ".sa.com",
"SCHOOLNZ" => ".school.nz",
"SECOM" => ".se.com",
"SENET" => ".se.net",
"SHOPHT" => ".shop.ht",
"STBPRO" => ".stb.pro",
"STORENF" => ".store.nf",
"TELKI" => ".tel.ki",
"TMFR" => ".tm.fr",
"TMSE" => ".tm.se",
"UKCOM" => ".uk.com",
"UKNET" => ".uk.net",
"USCOM" => ".us.com",
"USORG" => ".us.org",
"UYCOM" => ".uy.com",
"WAWPL" => ".waw.pl",
"WEBNF" => ".web.nf",
"WEBVE" => ".web.ve",
"WEBZA" => ".web.za",
"ZACOM" => ".za.com"
]);
// Transfer fields
Configure::set('Ispapi.transfer_fields', [
'domain' => [
'label' => Language::_('Ispapi.transfer.domain', true),
'type' => 'text'
],
'transfer_key' => [
'label' => Language::_('Ispapi.transfer.EPPCode', true),
'type' => 'text'
]
]);
// Domain fields
Configure::set('Ispapi.domain_fields', [
'domain' => [
'label' => Language::_('Ispapi.domain.domain', true),
'type' => 'text'
],
]);
// Nameserver fields
Configure::set('Ispapi.nameserver_fields', [
'ns1' => [
'label' => Language::_('Ispapi.nameserver.ns1', true),
'type' => 'text'
],
'ns2' => [
'label' => Language::_('Ispapi.nameserver.ns2', true),
'type' => 'text'
],
'ns3' => [
'label' => Language::_('Ispapi.nameserver.ns3', true),
'type' => 'text'
],
'ns4' => [
'label' => Language::_('Ispapi.nameserver.ns4', true),
'type' => 'text'
],
'ns5' => [
'label' => Language::_('Ispapi.nameserver.ns5', true),
'type' => 'text'
]
]);
// Whois sections
Configure::set('Ispapi.whois_sections', [
'Registrant',
'Tech',
'Admin',
'Billing'
]);
// Whois fields
Configure::set('Ispapi.whois_fields', [
'RegistrantFirstName' => [
'label' => Language::_('Ispapi.whois.RegistrantFirstName', true),
'type' => 'text'
],
'RegistrantLastName' => [
'label' => Language::_('Ispapi.whois.RegistrantLastName', true),
'type' => 'text'
],
'RegistrantOrganization' => [
'label' => Language::_('Ispapi.whois.RegistrantOrganization', true),
'type' => 'text'
],
'RegistrantAddress1' => [
'label' => Language::_('Ispapi.whois.RegistrantAddress1', true),
'type' => 'text'
],
'RegistrantAddress2' => [
'label' => Language::_('Ispapi.whois.RegistrantAddress2', true),
'type' => 'text'
],
'RegistrantCity' => [
'label' => Language::_('Ispapi.whois.RegistrantCity', true),
'type' => 'text'
],
'RegistrantStateProvince' => [
'label' => Language::_('Ispapi.whois.RegistrantStateProvince', true),
'type' => 'text'
],
'RegistrantPostalCode' => [
'label' => Language::_('Ispapi.whois.RegistrantPostalCode', true),
'type' => 'text'
],
'RegistrantCountry' => [
'label' => Language::_('Ispapi.whois.RegistrantCountry', true),
'type' => 'text'
],
'RegistrantPhone' => [
'label' => Language::_('Ispapi.whois.RegistrantPhone', true),
'type' => 'text'
],
'RegistrantEmailAddress' => [
'label' => Language::_('Ispapi.whois.RegistrantEmailAddress', true),
'type' => 'text'
],
'TechFirstName' => [
'label' => Language::_('Ispapi.whois.TechFirstName', true),
'type' => 'text'
],
'TechLastName' => [
'label' => Language::_('Ispapi.whois.TechLastName', true),
'type' => 'text'
],
'TechOrganization' => [
'label' => Language::_('Ispapi.whois.TechOrganization', true),
'type' => 'text'
],
'TechAddress1' => [
'label' => Language::_('Ispapi.whois.TechAddress1', true),
'type' => 'text'
],
'TechAddress2' => [
'label' => Language::_('Ispapi.whois.TechAddress2', true),
'type' => 'text'
],
'TechCity' => [
'label' => Language::_('Ispapi.whois.TechCity', true),
'type' => 'text'
],
'TechStateProvince' => [
'label' => Language::_('Ispapi.whois.TechStateProvince', true),
'type' => 'text'
],
'TechPostalCode' => [
'label' => Language::_('Ispapi.whois.TechPostalCode', true),
'type' => 'text'
],
'TechCountry' => [
'label' => Language::_('Ispapi.whois.TechCountry', true),
'type' => 'text'
],
'TechPhone' => [
'label' => Language::_('Ispapi.whois.TechPhone', true),
'type' => 'text'
],
'TechEmailAddress' => [
'label' => Language::_('Ispapi.whois.TechEmailAddress', true),
'type' => 'text'
],
'AdminFirstName' => [
'label' => Language::_('Ispapi.whois.AdminFirstName', true),
'type' => 'text'
],
'AdminLastName' => [
'label' => Language::_('Ispapi.whois.AdminLastName', true),
'type' => 'text'
],
'AdminOrganization' => [
'label' => Language::_('Ispapi.whois.AdminOrganization', true),
'type' => 'text'
],
'AdminAddress1' => [
'label' => Language::_('Ispapi.whois.AdminAddress1', true),
'type' => 'text'
],
'AdminAddress2' => [
'label' => Language::_('Ispapi.whois.AdminAddress2', true),
'type' => 'text'
],
'AdminCity' => [
'label' => Language::_('Ispapi.whois.AdminCity', true),
'type' => 'text'
],
'AdminStateProvince' => [
'label' => Language::_('Ispapi.whois.AdminStateProvince', true),
'type' => 'text'
],
'AdminPostalCode' => [
'label' => Language::_('Ispapi.whois.AdminPostalCode', true),
'type' => 'text'
],
'AdminCountry' => [
'label' => Language::_('Ispapi.whois.AdminCountry', true),
'type' => 'text'
],
'AdminPhone' => [
'label' => Language::_('Ispapi.whois.AdminPhone', true),
'type' => 'text'
],
'AdminEmailAddress' => [
'label' => Language::_('Ispapi.whois.AdminEmailAddress', true),
'type' => 'text'
],
'BillingFirstName' => [
'label' => Language::_('Ispapi.whois.BillingFirstName', true),
'type' => 'text'
],
'BillingLastName' => [
'label' => Language::_('Ispapi.whois.BillingLastName', true),
'type' => 'text'
],
'BillingOrganization' => [
'label' => Language::_('Ispapi.whois.BillingOrganization', true),
'type' => 'text'
],
'BillingAddress1' => [
'label' => Language::_('Ispapi.whois.BillingAddress1', true),
'type' => 'text'
],
'BillingAddress2' => [
'label' => Language::_('Ispapi.whois.BillingAddress2', true),
'type' => 'text'
],
'BillingCity' => [
'label' => Language::_('Ispapi.whois.BillingCity', true),
'type' => 'text'
],
'BillingStateProvince' => [
'label' => Language::_('Ispapi.whois.BillingStateProvince', true),
'type' => 'text'
],
'BillingPostalCode' => [
'label' => Language::_('Ispapi.whois.BillingPostalCode', true),
'type' => 'text'
],
'BillingCountry' => [
'label' => Language::_('Ispapi.whois.BillingCountry', true),
'type' => 'text'
],
'BillingPhone' => [
'label' => Language::_('Ispapi.whois.BillingPhone', true),
'type' => 'text'
],
'BillingEmailAddress' => [
'label' => Language::_('Ispapi.whois.BillingEmailAddress', true),
'type' => 'text'
]
]);
// .US
Configure::set('Ispapi.domain_fields.us', [
'X-US-NEXUS-CATEGORY' => [
'label' => Language::_('Ispapi.domain.RegistrantNexus', true),
'type' => 'select',
'options' => [
'C11' => Language::_('Ispapi.domain.RegistrantNexus.c11', true),
'C12' => Language::_('Ispapi.domain.RegistrantNexus.c12', true),
'C21' => Language::_('Ispapi.domain.RegistrantNexus.c21', true),
'C31' => Language::_('Ispapi.domain.RegistrantNexus.c31', true),
'C32' => Language::_('Ispapi.domain.RegistrantNexus.c32', true)
]
],
'X-US-NEXUS-APPPURPOSE' => [
'label' => Language::_('Ispapi.domain.RegistrantPurpose', true),
'type' => 'select',
'options' => [
'P1' => Language::_('Ispapi.domain.RegistrantPurpose.p1', true),
'P2' => Language::_('Ispapi.domain.RegistrantPurpose.p2', true),
'P3' => Language::_('Ispapi.domain.RegistrantPurpose.p3', true),
'P4' => Language::_('Ispapi.domain.RegistrantPurpose.p4', true),
'P5' => Language::_('Ispapi.domain.RegistrantPurpose.p5', true)
]
],
'X-US-NEXUS-VALIDATOR' => [
'label' => Language::_('Ispapi.domain.RegistrantCountry', true),
'type' => 'text'
]
]);
// .NU
Configure::set('Ispapi.domain_fields.nu', [
'X-REGISTRANT-IDNUMBER' => [
'label' => Language::_('Ispapi.domain.RegistrantIDnumber', true),
'type' => 'text'
],
'X-VATID' => [
'label' => Language::_('Ispapi.domain.VatID', true),
'type' => 'text'
],
]);
// .VOTE
Configure::set('Ispapi.domain_fields.vote', [
'X-VOTE-ACCEPT-HIGHLY-REGULATED-TAC' => [
'label' => Language::_('Ispapi.domain.Agreement', true),
'type' => 'checkbox',
'options' => [
'I AGREE' => Language::_('Ispapi.domain.VOTEAgreement.yes', true)
]
]
]);
// .VOTO
Configure::set('Ispapi.domain_fields.voto', [
'X-VOTO-ACCEPT-HIGHLY-REGULATED-TAC' => [
'label' => Language::_('Ispapi.domain.Agreement', true),
'type' => 'checkbox',
'options' => [
'I AGREE' => Language::_('Ispapi.domain.VOTOAgreement.yes', true)
]
]
]);
// .RO
Configure::set('Ispapi.domain_fields.ro', [
'X-REGISTRANT-IDNUMBER' => [
'label' => Language::_('Ispapi.domain.RegistrantIDnumber', true),
'type' => 'text'
],
'X-REGISTRANT-VATID' => [
'label' => Language::_('Ispapi.domain.RegistrantVatID', true),
'type' => 'text'
]
]);
// .BERLIN
Configure::set('Ispapi.domain_fields.berlin', [
'X-BERLIN-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.BerlinOptions', true)
]
]
]);
// .RUHR
Configure::set('Ispapi.domain_fields.ruhr', [
'X-RUHR-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.RuhrOptions', true)
]
]
]);
// .HAMBURG
Configure::set('Ispapi.domain_fields.hamburg', [
'X-HAMBURG-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.HamburgOptions', true)
]
]
]);
// .BAYERN
Configure::set('Ispapi.domain_fields.bayern', [
'X-BAYERN-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.BayernOptions', true)
]
]
]);
// .JP
Configure::set('Ispapi.domain_fields.jp', [
'X-JP-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.JpOptions', true)
]
]
]);
// .DE
Configure::set('Ispapi.domain_fields.de', [
'X-DE-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.deOptions', true)
]
]
]);
// .EU
Configure::set('Ispapi.domain_fields.eu', [
'X-EU-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.euOptions', true)
]
]
]);
// .SG
Configure::set('Ispapi.domain_fields.sg', [
'X-SG-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.sgOptions', true)
]
],
'X-SG-RCBID' => [
'label' => Language::_('Ispapi.domain.RCBSingaporeID', true),
'type' => 'text'
],
'X-ADMIN-IDNUMBER' => [
'label' => Language::_('Ispapi.domain.AdminIDnumber', true),
'type' => 'text'
]
]);
// .COM.SG
Configure::set('Ispapi.domain_fields.com.sg', Configure::get('Ispapi.domain_fields.sg', true));
// .EDU.SG
Configure::set('Ispapi.domain_fields.edu.sg', Configure::get('Ispapi.domain_fields.sg', true));
// .NET.SG
Configure::set('Ispapi.domain_fields.net.sg', Configure::get('Ispapi.domain_fields.sg', true));
// .ORG.SG
Configure::set('Ispapi.domain_fields.org.sg', Configure::get('Ispapi.domain_fields.sg', true));
// .PER.SG
Configure::set('Ispapi.domain_fields.per.sg', Configure::get('Ispapi.domain_fields.sg', true));
// .CA
Configure::set('Ispapi.domain_fields.ca', [
'X-CA-LEGALTYPE' => [
'label' => Language::_('Ispapi.domain.CIRALegalType', true),
'type' => 'select',
'options' => [
'CCO' => Language::_('Ispapi.domain.RegistrantPurpose.cco', true),
'CCT' => Language::_('Ispapi.domain.RegistrantPurpose.cct', true),
'RES' => Language::_('Ispapi.domain.RegistrantPurpose.res', true),
'GOV' => Language::_('Ispapi.domain.RegistrantPurpose.gov', true),
'EDU' => Language::_('Ispapi.domain.RegistrantPurpose.edu', true),
'ASS' => Language::_('Ispapi.domain.RegistrantPurpose.ass', true),
'HOP' => Language::_('Ispapi.domain.RegistrantPurpose.hop', true),
'PRT' => Language::_('Ispapi.domain.RegistrantPurpose.prt', true),
'TDM' => Language::_('Ispapi.domain.RegistrantPurpose.tdm', true),
'TRD' => Language::_('Ispapi.domain.RegistrantPurpose.trd', true),
'PLT' => Language::_('Ispapi.domain.RegistrantPurpose.plt', true),
'LAM' => Language::_('Ispapi.domain.RegistrantPurpose.lam', true),
'TRS' => Language::_('Ispapi.domain.RegistrantPurpose.trs', true),
'ABO' => Language::_('Ispapi.domain.RegistrantPurpose.abo', true),
'INB' => Language::_('Ispapi.domain.RegistrantPurpose.inb', true),
'LGR' => Language::_('Ispapi.domain.RegistrantPurpose.lgr', true),
'OMK' => Language::_('Ispapi.domain.RegistrantPurpose.omk', true),
'MAJ' => Language::_('Ispapi.domain.RegistrantPurpose.maj', true)
]
],
'X-CA-LANGUAGE' => [
'label' => Language::_('Ispapi.domain.CIRALanguage', true),
'type' => 'select',
'options' => [
'en' => Language::_('Ispapi.domain.CIRALanguage.en', true),
'fr' => Language::_('Ispapi.domain.CIRALanguage.fr', true),
]
]
]);
// .AERO
Configure::set('Ispapi.domain_fields.aero', [
'X-AERO-ENS-AUTH-ID' => [
'label' => Language::_('Ispapi.domain.AeroID', true),
'type' => 'text',
],
'X-AERO-ENS-AUTH-KEY' => [
'label' => Language::_('Ispapi.domain.AeroPassword', true),
'type' => 'text'
]
]);
// .TRAVEL
Configure::set('Ispapi.domain_fields.travel', [
'X-TRAVEL-INDUSTRY' => [
'label' => Language::_('Ispapi.domain.TravelIndustry', true),
'type' => 'text'
]
]);
// .FR
Configure::set('Ispapi.domain_fields.fr', [
'X-FR-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'select',
'options' => [
' ' => ' ',
'1' => Language::_('Ispapi.domain.frOptions', true)
]
],
'X-FR-REGISTRANT-BIRTH-DATE' => [
'label' => Language::_('Ispapi.domain.DateOfBirth', true),
'type' => 'text'
],
'X-FR-REGISTRANT-BIRTH-PLACE' => [
'label' => Language::_('Ispapi.domain.PlaceOfBirth', true),
'type' => 'text'
],
'X-FR-REGISTRANT-LEGAL-ID' => [
'label' => Language::_('Ispapi.domain.VatIDorSiren', true),
'type' => 'text'
],
'X-FR-REGISTRANT-TRADEMARK-NUMBER' => [
'label' => Language::_('Ispapi.domain.TrademarkNumber', true),
'type' => 'text'
],
'X-FR-REGISTRANT-DUNS-NUMBER' => [
'label' => Language::_('Ispapi.domain.DunsNumber', true),
'type' => 'text'
],
'X-FR-REGISTRANT-LOCAL-ID' => [
'label' => Language::_('Ispapi.domain.LocalID', true),
'type' => 'text'
],
'X-FR-REGISTRANT-JO-DATE-DECLARATION' => [
'label' => Language::_('Ispapi.domain.DateOfDeclaration', true),
'type' => 'text'
],
'X-FR-REGISTRANT-JO-NUMBER' => [
'label' => Language::_('Ispapi.domain.NumberJo', true),
'type' => 'text'
],
'X-FR-REGISTRANT-JO-PAGE' => [
'label' => Language::_('Ispapi.domain.JoPage', true),
'type' => 'text'
],
'X-FR-REGISTRANT-JO-DATE-PUBLICATION' => [
'label' => Language::_('Ispapi.domain.DateOfPublicationJo', true),
'type' => 'text'
]
]);
// .PM
Configure::set('Ispapi.domain_fields.pm', Configure::get('Ispapi.domain_fields.fr', true));
// .RE
Configure::set('Ispapi.domain_fields.re', Configure::get('Ispapi.domain_fields.fr', true));
// .TF
Configure::set('Ispapi.domain_fields.tf', Configure::get('Ispapi.domain_fields.fr', true));
// .WF
Configure::set('Ispapi.domain_fields.wf', Configure::get('Ispapi.domain_fields.fr', true));
// .YT
Configure::set('Ispapi.domain_fields.yt', Configure::get('Ispapi.domain_fields.fr', true));
// .JOBS
Configure::set('Ispapi.domain_fields.jobs', [
'X-JOBS-COMPANYURL' => [
'label' => Language::_('Ispapi.domain.CompanyURL', true),
'type' => 'text'
],
'X-JOBS-INDUSTRYCLASSIFICATION' => [
'label' => Language::_('Ispapi.domain.IndustryClassification', true),
'type' => 'select',
'options' => [
'' => '',
'2' => Language::_('Ispapi.domain.AccountingBankingFinance', true),
'3' => Language::_('Ispapi.domain.AgricultureFarming', true),
'21' => Language::_('Ispapi.domain.Biotechnologycience', true),
'5' => Language::_('Ispapi.domain.ComputerInformationechnology', true),
'4' => Language::_('Ispapi.domain.ConstructionBuildingServices', true),
'12' => Language::_('Ispapi.domain.Consulting', true),
'6' => Language::_('Ispapi.domain.EducationTrainingLibrary', true),
'7' => Language::_('Ispapi.domain.Entertainment', true),
'13' => Language::_('Ispapi.domain.Environmental', true),
'19' => Language::_('Ispapi.domain.Hospitality', true),
'10' => Language::_('Ispapi.domain.GovernmentCivilService', true),
'11' => Language::_('Ispapi.domain.Healthcare', true),
'15' => Language::_('Ispapi.domain.HRRecruiting', true),
'16' => Language::_('Ispapi.domain.Insurance', true),
'17' => Language::_('Ispapi.domain.Legal', true),
'18' => Language::_('Ispapi.domain.Manufacturing', true),
'20' => Language::_('Ispapi.domain.MediaAdvertising', true),
'9' => Language::_('Ispapi.domain.ParksRecreation', true),
'26' => Language::_('Ispapi.domain.Pharmaceutical', true),
'22' => Language::_('Ispapi.domain.RealEstate', true),
'14' => Language::_('Ispapi.domain.RestaurantFoodService', true),
'23' => Language::_('Ispapi.domain.Retail', true),
'8' => Language::_('Ispapi.domain.Telemarketing', true),
'24' => Language::_('Ispapi.domain.Transportation', true),
'25' => Language::_('Ispapi.domain.Other', true)
]
],
]);
// .PRO
Configure::set('Ispapi.domain_fields.pro', [
'X-PRO-PROFESSION' => [
'label' => Language::_('Ispapi.domain.Profession', true),
'type' => 'text'
],
'X-PRO-AUTHORITY' => [
'label' => Language::_('Ispapi.domain.Authority', true),
'type' => 'text'
],
'X-PRO-AUTHORITYWEBSITE' => [
'label' => Language::_('Ispapi.domain.AuthorityWebsite', true),
'type' => 'text'
],
'X-PRO-LICENSENUMBER' => [
'label' => Language::_('Ispapi.domain.LicenseNumber', true),
'type' => 'text'
],
'X-PRO-ACCEPT-TOU' => [
'label' => Language::_('Ispapi.domain.PROTerms', true),
'type' => 'checkbox',
'options' => [
'1' => Language::_('Ispapi.domain.PROTerms.yes', true)
]
],
]);
// .HK
Configure::set('Ispapi.domain_fields.hk', [
'X-HK-REGISTRANT-DOCUMENT-TYPE' => [
'label' => Language::_('Ispapi.domain.RegistrantDocumentType', true),
'type' => 'select',
'options' => [
'HKID' => Language::_('Ispapi.domain.HongKongIdentityNumber', true),
'OTHID' => Language::_('Ispapi.domain. OtherCountryIdentityNumber', true),
'PASSNO' => Language::_('Ispapi.domain.PassportNo', true),
'BIRTHCERT' => Language::_('Ispapi.domain.BirthCertificate', true),
'OTHIDV' => Language::_('Ispapi.domain.OthersIndividualDocument', true),
'BR' => Language::_('Ispapi.domain.BusinessRegistrationCertificate', true),
'CI' => Language::_('Ispapi.domain.CertificateofIncorporation', true),
'CRS' => Language::_('Ispapi.domain.CertificateofRegistrationofaSchool', true),
'HKSARG' => Language::_('Ispapi.domain.HongKongSpecialAdministrativeRegionGovernment', true),
'HKORDINANCE' => Language::_('Ispapi.domain.OrdinanceofHongKong', true),
'OTHORG' => Language::_('Ispapi.domain.OthersOrganizationDocument', true)
]
],
'X-HK-REGISTRANT-DOCUMENT-NUMBER' => [
'label' => Language::_('Ispapi.domain.RegistrantDocumentNumber', true),
'type' => 'text'
],
'X-HK-REGISTRANT-DOCUMENT-ORIGIN-COUNTRY' => [
'label' => Language::_('Ispapi.domain.RegistrantDocumentOriginCountry', true),
'type' => 'text'
],
'X-HK-REGISTRANT-BIRTH-DATE' => [
'label' => Language::_('Ispapi.domain.RegistrantBirthDateforindividuals', true),
'type' => 'text'
],
'X-HK-ACCEPT-INDIVIDUAL-REGISTRATION-TAC' => [
'label' => Language::_('Ispapi.domain.HKTermsforindividuals', true),
'type' => 'checkbox',
'options' => [
'1' => Language::_('Ispapi.domain.HKTermsforindividuals.yes', true)
]
]
]);
// .FI
Configure::set('Ispapi.domain_fields.fi', [
'X-FI-ACCEPT-REGISTRATION-TAC' => [
'label' => Language::_('Ispapi.domain.FICORAAgreement', true),
'type' => 'checkbox',
'options' => [
'1' => Language::_('Ispapi.domain.FIagreement.yes', true)
]
],
'X-FI-IDNUMBER' => [
'label' => Language::_('Ispapi.domain.IDNumber', true),
'type' => 'text'
]
]);
// .SE
Configure::set('Ispapi.domain_fields.se', [
'X-NICSE-IDNUMBER' => [
'label' => Language::_('Ispapi.domain.RegistrantIDNumber', true),
'type' => 'text'
],
'X-NICSE-VATID' => [
'label' => Language::_('Ispapi.domain.RegistrantVatID', true),
'type' => 'text'
]
]);
// .DK
Configure::set('Ispapi.domain_fields.dk', [
'X-REGISTRANT-VATID' => [
'label' => Language::_('Ispapi.domain.RegistrantVatID', true),
'type' => 'text'
],
'X-ADMIN-VATID' => [
'label' => Language::_('Ispapi.domain.AdminVATID', true),
'type' => 'text'
],
'X-DK-REGISTRANT-CONTACT' => [
'label' => Language::_('Ispapi.domain.Registrantcontact', true),
'type' => 'text'
],
'X-DK-ADMIN-CONTACT' => [
'label' => Language::_('Ispapi.domain.Admincontact', true),
'type' => 'text'
]
]);
// .IT
Configure::set('Ispapi.domain_fields.it', [
'X-IT-ACCEPT-TRUSTEE-TAC' => [
'label' => Language::_('Ispapi.domain.LocalPresence', true),
'type' => 'text'
],
'X-IT-PIN' => [
'label' => Language::_('Ispapi.domain.PIN', true),
'type' => 'text'
],
'X-IT-ACCEPT-LIABILITY-TAC' => [
'label' => Language::_('Ispapi.domain.Section3Agreemen', true),
'type' => 'select',
'options' => [
'' => '',
'1' => Language::_('Ispapi.domain.Section3Agreemen.yes', true)
]
],
'X-IT-ACCEPT-REGISTRATION-TAC' => [
'label' => Language::_('Ispapi.domain.Section5Agreemen', true),
'type' => 'select',
'options' => [
'' => '',
'1' => Language::_('Ispapi.domain.Section5Agreemen.yes', true)
]
],
'X-IT-ACCEPT-DIFFUSION-AND-ACCESSIBILITY-TAC' => [
'label' => Language::_('Ispapi.domain.Section6Agreement', true),
'type' => 'select',
'options' => [
'' => '',
'1' => Language::_('Ispapi.domain.Section6Agreemen.yes', true)
]
],
'X-IT-ACCEPT-EXPLICIT-TAC' => [
'label' => Language::_('Ispapi.domain.Section7Agreemen', true),
'type' => 'select',
'options' => [
'' => '',
'1' => Language::_('Ispapi.domain.Section7Agreemen.yes', true)
]
]
]);
// .QUEBEC
Configure::set('Ispapi.domain_fields.quebec', [
'X-CORE-INTENDED-USE' => [
'label' => Language::_('Ispapi.domain.QUEBECIntendeduse', true),
'type' => 'text'
]
]);
// .SCOT
Configure::set('Ispapi.domain_fields.scot', [
'X-CORE-INTENDED-USE' => [
'label' => Language::_('Ispapi.domain.SCOTIntendeduse', true),
'type' => 'text'
]
]);
// .NYC
Configure::set('Ispapi.domain_fields.nyc', [
'X-NYC-REGISTRANT-NEXUS-CATEGORY' => [
'label' => Language::_('Ispapi.domain.NEXUSCategory', true),
'type' => 'select',
'options' => [
'' => '',
'1' => Language::_('Ispapi.domain.NaturalPerson', true),
'2' => Language::_('Ispapi.domain.Entityororganization', true)
]
]
]);
// .ES
Configure::set('Ispapi.domain_fields.es', [
'X-ES-REGISTRANT-TIPO-IDENTIFICACION' => [
'label' => Language::_('Ispapi.domain.RegistrantType', true),
'type' => 'select',
'options' => [
'' => '',
'0' => Language::_('Ispapi.domain.Otra', true),
'1' => Language::_('Ispapi.domain.NIF', true),
'3' => Language::_('Ispapi.domain.Alien', true),
]
],
'X-ES-REGISTRANT-IDENTIFICACION' => [
'label' => Language::_('Ispapi.domain.RegistrantIdentificationNumber', true),
'type' => 'text'
],
'X-ES-ADMIN-TIPO-IDENTIFICACION' => [
'label' => Language::_('Ispapi.domain.AdminContactType', true),
'type' => 'select',
'options' => [
'' => '',
'0' => Language::_('Ispapi.domain.Otra', true),
'1' => Language::_('Ispapi.domain.NIF', true),
'3' => Language::_('Ispapi.domain.Alien', true),
]
],
'X-ES-ADMIN-IDENTIFICACION' => [
'label' => Language::_('Ispapi.domain.AdminContactIdentificationNumber', true),
'type' => 'text'
],
'X-ES-ACCEPT-INDIVIDUAL-REGISTRATION-TAC' => [
'label' => Language::_('Ispapi.domain.Agreement', true),
'type' => 'select',
'options' => [
'0' => '',
'1' => Language::_('Ispapi.domain.ESAgreement', true)
]
]
]);
// .IE
Configure::set('Ispapi.domain_fields.ie', [
'X-IE-REGISTRANT-CLASS' => [
'label' => Language::_('Ispapi.domain.RegistrantClass', true),
'type' => 'select',
'options' => [
'' => '',
'Company,Business Owner,Club' => Language::_('Ispapi.domain.CompanyBusinessOwnerClub', true),
'Band' => Language::_('Ispapi.domain.Band', true),
'Local Group,School' => Language::_('Ispapi.domain.LocalGroupSchool', true),
'College,State Agency,Charity,Blogger' => Language::_('Ispapi.domain.CollegeStateAgencyCharityBlogger', true),
'Other' => Language::_('Ispapi.domain.Other', true)
]
],
'X-IE-REGISTRANT-REMARKS' => [
'label' => Language::_('Ispapi.domain.ProofofconnectiontoIreland', true),
'type' => 'text'
]
]);
// .NO
Configure::set('Ispapi.domain_fields.no', [
'X-NO-REGISTRANT-IDENTITY' => [
'label' => Language::_('Ispapi.domain.RegistrantIDnumber', true),
'type' => 'text'
],
'Fax-Required' => [
'label' => Language::_('Ispapi.domain.Faxrequired', true),
'type' => 'checkbox',
'options' => [
'I AGREE' => Language::_('Ispapi.domain.NOFaxrequired.yes', true)
]
]
]);
// .SWISS
Configure::set('Ispapi.domain_fields.swiss', [
'X-SWISS-REGISTRANT-ENTERPRISE-ID' => [
'label' => Language::_('Ispapi.domain.EnterpriseID', true),
'type' => 'text'
],
'X-CORE-INTENDED-USE' => [
'label' => Language::_('Ispapi.domain.SWISSIntendeduse', true),
'type' => 'text'
]
]);
// .PT
Configure::set('Ispapi.domain_fields.pt', [
'X-PT-REGISTRANT-VATID' => [
'label' => Language::_('Ispapi.domain.RegistrantVatID', true),
'type' => 'text'
],
'X-PT-TECH-VATID' => [
'label' => Language::_('Ispapi.domain.TechvatID', true),
'type' => 'text'
],
]);
// .ECO
Configure::set('Ispapi.domain_fields.eco', [
'X-ECO-ACCEPT-HIGHLY-REGULATED-TAC' => [
'label' => Language::_('Ispapi.domain.HighlyRegulatedTLD', true),
'type' => 'select',
'options' => [
'' => '',
'1' => Language::_('Ispapi.domain.ECOHighlyRegulatedTLD.yes', true)
]
]
]);
// .CN
Configure::set('Ispapi.domain_fields.cn', [
'X-CN-REGISTRANT-ID-TYPE' => [
'label' => Language::_('Ispapi.domain.RegistrantIDType', true),
'type' => 'text'
],
'X-CN-REGISTRANT-ID-NUMBER' => [
'label' => Language::_('Ispapi.domain.RegistrantIDNumber', true),
'type' => 'text'
]
]);
// .COM.CN
Configure::set('Ispapi.domain_fields.com.cn', Configure::get('Ispapi.domain_fields.cn', true));
// .NET.CN
Configure::set('Ispapi.domain_fields.net.cn', Configure::get('Ispapi.domain_fields.cn', true));
// .ORG.CN
Configure::set('Ispapi.domain_fields.org.cn', Configure::get('Ispapi.domain_fields.cn', true));
// .COM.AU
Configure::set('Ispapi.domain_fields.com.au', [
'X-CN-REGISTRANT-ID-TYPE' => [
'label' => Language::_('Ispapi.domain.RegistrantIDType', true),
'type' => 'select',
'options' => [
'ABN' => Language::_('Ispapi.domain.AustralianBusinessNumber', true),
'ACN' => Language::_('Ispapi.domain.AustralianCompanyNumber', true),
'RBN' => Language::_('Ispapi.domain.BusinessRegistrationNumber', true),
'TM' => Language::_('Ispapi.domain.TrademarkNumber', true)
]
]
]);
// .NET.AU
Configure::set('Ispapi.domain_fields.net.au', Configure::get('Ispapi.domain_fields.com.au', true));
// .ORG.AU
Configure::set('Ispapi.domain_fields.org.au', Configure::get('Ispapi.domain_fields.com.au', true));
// .ID.AU
Configure::set('Ispapi.domain_fields.id.au', Configure::get('Ispapi.domain_fields.com.au', true));
// .LV
Configure::set('Ispapi.domain_fields.lv', [
'X-VATID' => [
'label' => Language::_('Ispapi.domain.VatID', true),
'type' => 'text'
],
'X-IDNUMBER' => [
'label' => Language::_('Ispapi.domain.IDnumber', true),
'type' => 'text'
],
]);
<file_sep>const { series, src, dest } = require('gulp')
const clean = require('gulp-clean')
const zip = require('gulp-zip')
const exec = require('util').promisify(require('child_process').exec)
const cfg = require('./gulpfile.json')
/**
* Perform PHP Linting
*/
async function doLint() {
// these may fail, it's fine
try {
await exec(`${cfg.phpcsfixcmd} ${cfg.phpcsparams}`)
} catch (e) {
}
// these shouldn't fail
try {
await exec(`${cfg.phpcschkcmd} ${cfg.phpcsparams}`)
await exec(`${cfg.phpcomptcmd} ${cfg.phpcsparams}`)
// await exec(`${cfg.phpstancmd}`);
} catch (e) {
await Promise.reject(e.message)
}
await Promise.resolve()
}
/**
* cleanup old build folder / archive
* @return stream
*/
function doDistClean() {
return src([cfg.archiveBuildPath, `${cfg.archiveFileName}-latest.zip`], { read: false, base: '.', allowEmpty: true })
.pipe(clean({ force: true }))
}
/**
* Copy all files/folders to build folder
* @return stream
*/
function doCopyFiles() {
return src(cfg.filesForArchive, { base: '.' })
.pipe(dest(cfg.archiveBuildPath))
}
/**
* Clean up files
* @return stream
*/
function doFullClean() {
return src(cfg.filesForCleanup, { read: false, base: '.', allowEmpty: true })
.pipe(clean({ force: true }))
}
/**
* build latest zip archive
* @return stream
*/
function doGitZip() {
return src(`./${cfg.archiveBuildPath}/**`)
.pipe(zip(`${cfg.archiveFileName}-latest.zip`))
.pipe(dest('.'))
}
/**
* build zip archive
* @return stream
*/
function doZip() {
return src(`./${cfg.archiveBuildPath}/**`)
.pipe(zip(`${cfg.archiveFileName}.zip`))
.pipe(dest('./pkg'))
}
exports.lint = series(
doLint
)
exports.copy = series(
doDistClean,
doCopyFiles
)
exports.prepare = series(
exports.lint,
exports.copy
)
exports.archives = series(
doGitZip,
doZip
)
exports.default = series(
exports.prepare,
exports.archives,
doFullClean
)
exports.release = series(
exports.copy,
exports.archives,
doFullClean
)
<file_sep><?php
use \HEXONET\Logger;
use \HEXONET\Response;
class BlestaLogger extends Logger
{
private string $apiURL;
private Ispapi $mod;
public function __construct($mod, $apiURL)
{
$this->mod = $mod;
$this->apiURL = $apiURL;
}
/**
* output/log given data
*/
public function log(string $post, Response $r, string $error = null): void
{
$this->mod->log(
$this->apiURL,
$r->getCommandPlain() . "\n" . $post,
'input',
true
);
$this->mod->log(
$this->apiURL,
($error ? $error . "\n\n" : "") . $r->getPlain(),
'output',
$error ? false : $r->isSuccess()
);
}
}
<file_sep><?php
/**
* @copyright Copyright (c) 2018-2021, HEXONET
* @license https://raw.githubusercontent.com/hexonet/blesta-ispapi-registrar/master/LICENSE MIT
*/
// Basics
$lang['Ispapi.name'] = 'Ispapi';
$lang['Ispapi.description'] = 'Resell domains through HEXONET.';
$lang['Ispapi.module_row'] = 'Account';
$lang['Ispapi.module_row_plural'] = 'Accounts';
// Module management
$lang['Ispapi.add_module_row'] = 'Add Account';
$lang['Ispapi.manage.module_rows_title'] = 'Accounts';
$lang['Ispapi.manage.module_rows_heading.user'] = 'User';
$lang['Ispapi.manage.module_rows_heading.key'] = 'API Key';
$lang['Ispapi.manage.module_rows_heading.sandbox'] = 'Sandbox';
$lang['Ispapi.manage.module_rows_heading.options'] = 'Options';
$lang['Ispapi.manage.module_rows.edit'] = 'Edit';
$lang['Ispapi.manage.module_rows.delete'] = 'Delete';
$lang['Ispapi.manage.module_rows.confirm_delete'] = 'Are you sure you want to delete this account?';
$lang['Ispapi.manage.module_rows_no_results'] = 'There are no accounts.';
// Row Meta
$lang['Ispapi.row_meta.user'] = 'User';
$lang['Ispapi.row_meta.key'] = 'Password';
$lang['Ispapi.row_meta.sandbox'] = 'Sandbox';
$lang['Ispapi.row_meta.sandbox_true'] = 'Yes';
$lang['Ispapi.row_meta.sandbox_false'] = 'No';
// Add row
$lang['Ispapi.add_row.box_title'] = 'Add Ispapi Account';
$lang['Ispapi.add_row.basic_title'] = 'Basic Settings';
$lang['Ispapi.add_row.add_btn'] = 'Add Account';
// Edit row
$lang['Ispapi.edit_row.box_title'] = 'Edit Ispapi Account';
$lang['Ispapi.edit_row.basic_title'] = 'Basic Settings';
$lang['Ispapi.edit_row.add_btn'] = 'Update Account';
// Package fields
$lang['Ispapi.package_fields.type'] = 'Type';
$lang['Ispapi.package_fields.type_domain'] = 'Domain Registration';
$lang['Ispapi.package_fields.type_ssl'] = 'SSL Certificate';
$lang['Ispapi.package_fields.tld_options'] = 'TLDs';
$lang['Ispapi.package_fields.ns1'] = 'Name Server 1';
$lang['Ispapi.package_fields.ns2'] = 'Name Server 2';
$lang['Ispapi.package_fields.ns3'] = 'Name Server 3';
$lang['Ispapi.package_fields.ns4'] = 'Name Server 4';
$lang['Ispapi.package_fields.ns5'] = 'Name Server 5';
// Service management
$lang['Ispapi.tab_whois.title'] = 'Whois';
$lang['Ispapi.tab_whois.section_Registrant'] = 'Registrant';
$lang['Ispapi.tab_whois.section_Admin'] = 'Administrative';
$lang['Ispapi.tab_whois.section_Tech'] = 'Technical';
$lang['Ispapi.tab_whois.section_Billing'] = 'Billing';
$lang['Ispapi.tab_whois.field_submit'] = 'Update Whois';
$lang['Ispapi.tab_nameservers.title'] = 'Name Servers';
$lang['Ispapi.tab_nameserver.field_ns'] = 'Name Server %1$s'; // %1$s is the name server number
$lang['Ispapi.tab_nameservers.field_submit'] = 'Update Name Servers';
$lang['Ispapi.tab_settings.title'] = 'Settings';
$lang['Ispapi.tab_settings.field_registrar_lock'] = 'Registrar Lock';
$lang['Ispapi.tab_settings.field_registrar_lock_yes'] = 'Set the registrar lock. Recommended to prevent unauthorized transfer.';
$lang['Ispapi.tab_settings.field_registrar_lock_no'] = 'Release the registrar lock so the domain can be transferred.';
$lang['Ispapi.tab_settings.field_request_epp'] = 'Request EPP Code/Transfer Key';
$lang['Ispapi.tab_settings.field_submit'] = 'Update Settings';
$lang['Ispapi.tab_transfer.title'] = 'Transfer';
$lang['Ispapi.tab_transfer.field_submit'] = 'Transfer Domain';
// Manual Renewals
$lang['Ispapi.manage.manual_renewal'] = "Manually Renew (select years)";
// Domain Data
$lang['Ispapi.renew.note'] = 'Please note that the HEXONET prices will be applied when you renew a domain';
$lang['Ispapi.domain.domaininformation'] = 'Domain data at your registrar system:';
$lang['Ispapi.domain.domainstatus'] = 'Status';
$lang['Ispapi.domain.expirydate'] = 'Expiry Date';
// Errors
$lang['Ispapi.!error.user.valid'] = 'Please enter a user.';
$lang['Ispapi.!error.key.valid'] = 'Please enter a password.';
$lang['Ispapi.!error.key.valid_connection'] = 'The user and password combination appear to be invalid, or your Ispapi account may not be configured to allow API access.';
// Domain Transfer Fields
$lang['Ispapi.transfer.domain'] = 'Domain Name';
$lang['Ispapi.transfer.EPPCode'] = 'EPP Code';
$lang['Ispapi.transfer.EPPCodeTransfer'] = 'EPP Code ( if required )';
#$lang['Ispapi.transfer.transfer_key'] = 'EPP Code';
// Domain Fields
$lang['Ispapi.domain.domain'] = 'Domain Name';
$lang['Ispapi.domain.NumYears'] = 'Years';
$lang['Ispapi.domain.WhoisPrivacy'] = "Whois Privacy";
$lang["Ispapi.domain.DomainAction"] = "Domain Action";
$lang["Ispapi.domain.TldSelection"] = "Select a TLD";
$lang['Ispapi.domain.registrationPeriod'] = 'Registration Period';
// Nameserver Fields
$lang['Ispapi.nameserver.ns1'] = 'Name Server 1';
$lang['Ispapi.nameserver.ns2'] = 'Name Server 2';
$lang['Ispapi.nameserver.ns3'] = 'Name Server 3';
$lang['Ispapi.nameserver.ns4'] = 'Name Server 4';
$lang['Ispapi.nameserver.ns5'] = 'Name Server 5';
// Whois Fields
$lang['Ispapi.whois.RegistrantFirstName'] = 'First Name';
$lang['Ispapi.whois.RegistrantLastName'] = 'Last Name';
$lang['Ispapi.whois.RegistrantOrganization'] = 'Company Name';
$lang['Ispapi.whois.RegistrantAddress1'] = 'Address 1';
$lang['Ispapi.whois.RegistrantAddress2'] = 'Address 2';
$lang['Ispapi.whois.RegistrantCity'] = 'City';
$lang['Ispapi.whois.RegistrantStateProvince'] = 'State/Province';
$lang['Ispapi.whois.RegistrantPostalCode'] = 'Postal Code';
$lang['Ispapi.whois.RegistrantCountry'] = 'Country';
$lang['Ispapi.whois.RegistrantPhone'] = 'Phone';
$lang['Ispapi.whois.RegistrantEmailAddress'] = 'Email';
$lang['Ispapi.whois.TechFirstName'] = 'First Name';
$lang['Ispapi.whois.TechLastName'] = 'Last Name';
$lang['Ispapi.whois.TechOrganization'] = 'Company Name';
$lang['Ispapi.whois.TechAddress1'] = 'Address 1';
$lang['Ispapi.whois.TechAddress2'] = 'Address 2';
$lang['Ispapi.whois.TechCity'] = 'City';
$lang['Ispapi.whois.TechStateProvince'] = 'State/Province';
$lang['Ispapi.whois.TechPostalCode'] = 'Postal Code';
$lang['Ispapi.whois.TechCountry'] = 'Country';
$lang['Ispapi.whois.TechPhone'] = 'Phone';
$lang['Ispapi.whois.TechEmailAddress'] = 'Email';
$lang['Ispapi.whois.AdminFirstName'] = '<NAME>';
$lang['Ispapi.whois.AdminLastName'] = '<NAME>';
$lang['Ispapi.whois.AdminOrganization'] = 'Company Name';
$lang['Ispapi.whois.AdminAddress1'] = 'Address 1';
$lang['Ispapi.whois.AdminAddress2'] = 'Address 2';
$lang['Ispapi.whois.AdminCity'] = 'City';
$lang['Ispapi.whois.AdminStateProvince'] = 'State/Province';
$lang['Ispapi.whois.AdminPostalCode'] = 'Postal Code';
$lang['Ispapi.whois.AdminCountry'] = 'Country';
$lang['Ispapi.whois.AdminPhone'] = 'Phone';
$lang['Ispapi.whois.AdminEmailAddress'] = 'Email';
$lang['Ispapi.whois.BillingFirstName'] = '<NAME>';
$lang['Ispapi.whois.BillingLastName'] = '<NAME>';
$lang['Ispapi.whois.BillingOrganization'] = 'Company Name';
$lang['Ispapi.whois.BillingAddress1'] = 'Address 1';
$lang['Ispapi.whois.BillingAddress2'] = 'Address 2';
$lang['Ispapi.whois.BillingCity'] = 'City';
$lang['Ispapi.whois.BillingStateProvince'] = 'State/Province';
$lang['Ispapi.whois.BillingPostalCode'] = 'Postal Code';
$lang['Ispapi.whois.BillingCountry'] = 'Country';
$lang['Ispapi.whois.BillingPhone'] = 'Phone';
$lang['Ispapi.whois.BillingEmailAddress'] = 'Email';
// Additional domain fields
// .US domain fields
$lang['Ispapi.domain.RegistrantNexus'] = 'Registrant Type';
$lang['Ispapi.domain.RegistrantNexus.c11'] = 'US citizen';
$lang['Ispapi.domain.RegistrantNexus.c12'] = 'Permanent resident of the US';
$lang['Ispapi.domain.RegistrantNexus.c21'] = 'US entity or organization';
$lang['Ispapi.domain.RegistrantNexus.c31'] = 'Foreign organization';
$lang['Ispapi.domain.RegistrantNexus.c32'] = 'Foreign organization with an office in the US';
$lang['Ispapi.domain.RegistrantPurpose'] = 'Purpose';
$lang['Ispapi.domain.RegistrantPurpose.p1'] = 'Business';
$lang['Ispapi.domain.RegistrantPurpose.p2'] = 'Non-profit';
$lang['Ispapi.domain.RegistrantPurpose.p3'] = 'Personal';
$lang['Ispapi.domain.RegistrantPurpose.p4'] = 'Educational';
$lang['Ispapi.domain.RegistrantPurpose.p5'] = 'Governmental';
$lang['Ispapi.domain.RegistrantCountry'] = 'Specify the two-letter country-code of the registrant (if Nexus Category is either C31 or C32)';
// .BERLIN domain fields
$lang['Ispapi.domain.BerlinOptions'] = 'Registrant and/or Admin-C are domiciled in Berlin / Use Local Presence Service';
// .RUHR domain fields
$lang['Ispapi.domain.RuhrOptions'] = 'Registrant and/or Admin-C are domiciled in Ruhr / Use Local Presence Service';
// .HAMBURG domain fields
$lang['Ispapi.domain.HamburgOptions'] = 'Registrant and/or Admin-C are domiciled in Hamburg / Use Local Presence Service';
// .BAYERN domain fields
$lang['Ispapi.domain.BayernOptions'] = 'Registrant and/or Admin-C are domiciled in Bayern / Use Local Presence Service';
// .JP domain fields
$lang['Ispapi.domain.JpOptions'] = 'Registrant and/or Admin-C are domiciled in Japan / Use Local Presence Service';
//.EU domain fields
$lang['Ispapi.domain.euOptions'] = 'Registrant is domiciled in the EU / Use Local Presence Service';
// .SG domain fields
$lang['Ispapi.domain.sgOptions'] = 'Registrant and/or Admin-C are domiciled in Singapore / Use Local Presence Service';
$lang['Ispapi.domain.RCBSingaporeID'] = 'RCB/Singapore ID';
$lang['Ispapi.domain.AdminIDnumber'] = 'Admin ID number';
// .AERO domain fields
$lang['Ispapi.domain.AeroID'] = '.aero ID';
$lang['Ispapi.domain.AeroPassword'] = '<PASSWORD>';
// .TRAVEL domain fields
$lang['Ispapi.domain.TravelIndustry'] = '.travel Industry';
// .FR domain fields
$lang['Ispapi.domain.frOptions'] = 'Registrant and/or Admin-C are domiciled in France / Use Local Presence Service';
$lang['Ispapi.domain.DateOfBirth'] = 'Date of Birth';
$lang['Ispapi.domain.PlaceOfBirth'] = 'Place of Birth';
$lang['Ispapi.domain.VatIDorSiren'] = 'VATID or SIREN/SIRET number';
$lang['Ispapi.domain.TrademarkNumber'] = 'Trademark Number';
$lang['Ispapi.domain.DunsNumber'] = 'DUNS number';
$lang['Ispapi.domain.LocalID'] = 'Local ID';
$lang['Ispapi.domain.DateOfDeclaration'] = 'Date of Declaration';
$lang['Ispapi.domain.NumberJo'] = 'Number [JO]';
$lang['Ispapi.domain.JoPage'] = 'Page of Announcement [JO]';
$lang['Ispapi.domain.DateOfPublicationJo'] = 'Date of Publication [JO]';
// .JOBS domain fields
$lang['Ispapi.domain.CompanyURL'] = 'Company URL';
$lang['Ispapi.domain.IndustryClassification'] = 'Industry Classification';
$lang['Ispapi.domain.AccountingBankingFinance'] = 'Accounting/Banking/Finance';
$lang['Ispapi.domain.AgricultureFarming'] = 'Agriculture/Farming';
$lang['Ispapi.domain.Biotechnologycience'] = 'Biotechnology/Science';
$lang['Ispapi.domain.ComputerInformationechnology'] = 'Computer/Information Technology';
$lang['Ispapi.domain.ConstructionBuildingServices'] = 'Construction/Building Services';
$lang['Ispapi.domain.Consulting'] = 'Consulting';
$lang['Ispapi.domain.EducationTrainingLibrary'] = 'Education/Training/Library';
$lang['Ispapi.domain.Entertainment'] = 'Entertainment';
$lang['Ispapi.domain.Environmental'] = 'Environmental';
$lang['Ispapi.domain.Hospitality'] = 'Hospitality';
$lang['Ispapi.domain.GovernmentCivilService'] = 'Government/Civil Service';
$lang['Ispapi.domain.Healthcare'] = 'Healthcare';
$lang['Ispapi.domain.HRRecruiting'] = 'HR/Recruiting';
$lang['Ispapi.domain.Insurance'] = 'Insurance';
$lang['Ispapi.domain.Legal'] = 'Legal';
$lang['Ispapi.domain.Manufacturing'] = 'Manufacturing';
$lang['Ispapi.domain.MediaAdvertising'] = 'Media/Advertising';
$lang['Ispapi.domain.ParksRecreation'] = 'Parks & Recreation';
$lang['Ispapi.domain.Pharmaceutical'] = 'Pharmaceutical';
$lang['Ispapi.domain.RealEstate'] = 'Real Estate';
$lang['Ispapi.domain.RestaurantFoodService'] = 'Restaurant/Food Service';
$lang['Ispapi.domain.Retail'] = 'Retail';
$lang['Ispapi.domain.Telemarketing'] = 'Telemarketing';
$lang['Ispapi.domain.Transportation'] = 'Transportation';
$lang['Ispapi.domain.Other'] = 'Other';
// .PRO domain fields
$lang['Ispapi.domain.Profession'] = 'Profession';
$lang['Ispapi.domain.Authority'] = 'Authority';
$lang['Ispapi.domain.AuthorityWebsite'] = 'Authority Website';
$lang['Ispapi.domain.LicenseNumber'] = 'License Number';
$lang['Ispapi.domain.PROTerms'] = '.PRO Terms';
$lang['Ispapi.domain.PROTerms.yes'] = 'Tick to confirm that you agree to the .PRO End User Terms Of Use at: http://www.registry.pro/legal/user-terms';
// .HK domain fields
$lang['Ispapi.domain.RegistrantDocumentType'] = 'Registrant Document Type';
$lang['Ispapi.domain.HongKongIdentityNumber'] = 'Individual - Hong Kong Identity Number';
$lang['Ispapi.domain.OtherCountryIdentityNumber'] = 'Individual - Others Country Identity Number';
$lang['Ispapi.domain.PassportNo'] = 'Individual - Passport No.';
$lang['Ispapi.domain.BirthCertificate'] = 'Individual - Birth Certificate';
$lang['Ispapi.domain.OthersIndividualDocument'] = 'Individual - Others Individual Document';
$lang['Ispapi.domain.BusinessRegistrationCertificate'] = 'Organization - Business Registration Certificate';
$lang['Ispapi.domain.CertificateofIncorporation'] = 'Organization - Certificate of Incorporation';
$lang['Ispapi.domain.CertificateofRegistrationofaSchool'] = 'Organization - Certificate of Registration of a School';
$lang['Ispapi.domain.HongKongSpecialAdministrativeRegionGovernment'] = 'Organization - Hong Kong Special Administrative Region Government Department';
$lang['Ispapi.domain.OrdinanceofHongKong'] = 'Organization - Ordinance of Hong Kong';
$lang['Ispapi.domain.OthersOrganizationDocument'] = 'Organization - Others Organization Document';
$lang['Ispapi.domain.RegistrantDocumentNumber'] = 'Registrant Document Number';
$lang['Ispapi.domain.RegistrantDocumentOriginCountry'] = 'Registrant Document Origin Country';
$lang['Ispapi.domain.RegistrantBirthDateforindividuals'] = 'Registrant Birth Date for individuals';
$lang['Ispapi.domain.HKTermsforindividuals'] = 'HK Terms for individuals';
$lang['Ispapi.domain.HKTermsforindividuals.yes'] = 'Accept the .HK https://www.hkirc.hk/content.jsp?id=3#!/6 (mandatory, if the registrant is an individual)';
// .FI domain fields
$lang['Ispapi.domain.FICORAAgreement'] = 'FICORA Agreement';
$lang['Ispapi.domain.IDNumber'] = 'ID Number';
$lang['Ispapi.domain.FIagreement.yes'] = 'I Accept the https://domain.fi/info/en/index/hakeminen/kukavoihakea.html FI Domain Name Agreement';
// .SE domain fields
$lang['Ispapi.domain.RegistrantIDNumber'] = 'Registrant ID Number';
$lang['Ispapi.domain.RegistrantVatID'] = 'Registrant VAT ID';
// .DK domain fields
$lang['Ispapi.domain.RegistrantVatID'] = 'Registrant VAT ID';
$lang['Ispapi.domain.AdminVATID'] = 'Admin VAT ID';
$lang['Ispapi.domain.Registrantcontact'] = 'Registrant contact';
$lang['Ispapi.domain.Admincontact'] = 'Admin contact';
// .IT domain fields
$lang['Ispapi.domain.PIN'] = 'PIN';
$lang['Ispapi.domain.Section3Agreemen'] = 'Section 3 Agreement';
$lang['Ispapi.domain.Section3Agreemen.yes'] = 'Section 3 - Declarations and assumptions of liability The Registrant of the domain name in question, declares under their own responsibility that they are:
in possession of the citizenship or resident in a country belonging to the European Union (in the case of registration for natural persons);
established in a country belonging to the European Union (in the case of registration for other organizations);
aware and accept that the registration and management of a domain name is subject to the Rules of assignment and management of domain names in ccTLD. it and Regulations for the resolution of disputes in the ccTLD.it and their subsequent amendments;
entitled to the use and/or legal availability of the domain name applied for, and that they do not prejudice, with the request for registration, the rights of others;
aware that for the inclusion of personal data in the Database of assigned domain names, and their possible dissemination and accessibility via the Internet, consent must be given explicitly by ticking the appropriate boxes in the information below. See The policy of the .it Registry in the Whois Database on the website of the Registry (http://www.nic.it);
aware and agree that in the case of erroneous or false declarations in this request, the Registry shall immediately revoke the domain name, or proceed with other legal actions. In such case the revocation shall not in any way give rise to claims against the Registry;
release the Registry from any liability resulting from the assignment and use of the domain name by the natural person that has made the request;
accept Italian jurisdiction and laws of the Italian State.';
$lang['Ispapi.domain.Section5Agreemen'] = 'Section 5 Agreement';
$lang['Ispapi.domain.Section5Agreemen.yes'] = 'Section 5 - Consent to the processing of personal data for registration
The interested party, after reading the above disclosure, gives consent to the processing of information required for registration, as defined in the above disclosure. Giving consent is optional, but if no consent is given, it will not be possible to finalize the registration, assignment and management of the domain name.';
$lang['Ispapi.domain.Section6Agreemen'] = 'Section 6 Agreement';
$lang['Ispapi.domain.Section6Agreemen.yes'] = 'Section 6 - Consent to the processing of personal data for diffusion and accessibility via the Internet
The interested party, after reading the above disclosure, gives consent to the dissemination and accessibility via the Internet, as defined in the disclosure above. Giving consent is optional, but absence of consent does not allow the dissemination and accessibility of Internet data.';
$lang['Ispapi.domain.Section7Agreemen'] = 'Section 7 Agreement';
$lang['Ispapi.domain.Section7Agreemen.yes'] = 'Section 7 - Explicit Acceptance of the following points
For explicit acceptance, the interested party declares that they:
d) are aware and agree that the registration and management of a domain name is subject to the Rules of assignment and management of domain names in ccTLD.it and Regulations for the resolution of disputes in the ccTLD.it and their subsequent amendments;
e) are aware and agree that in the case of erroneous or false declarations in this request, the Registry shall immediately revoke the domain name, or proceed with other legal actions. In such case the revocation shall not in any way give rise to claims against the Registry;
f) release the Registry from any liability resulting from the assignment and use of the domain name by the natural person that has made the request;
g) accept the Italian jurisdiction and laws of the Italian State.';
// .NYC domain fields
$lang['Ispapi.domain.NEXUSCategory'] = 'NEXUS Category';
$lang['Ispapi.domain.NaturalPerson'] = 'Natural Person - primary domicile with physical address in NYC';
$lang['Ispapi.domain.Entityororganization'] = 'Entity or organization - primary domicile with physical address in NYC';
// .ES domain fields
$lang['Ispapi.domain.RegistrantType'] = 'Registrant Type';
$lang['Ispapi.domain.RegistrantIdentificationNumber'] = 'Registrant Identification Number';
$lang['Ispapi.domain.AdminContactType'] = 'Admin-Contact Type';
$lang['Ispapi.domain.AdminContactIdentificationNumber'] = 'Admin-Contact Identification Number';
$lang['Ispapi.domain.ESAgreement'] = 'I agree to the .ES registration TAC for individuals';
$lang['Ispapi.domain.Alien'] = 'Alien registration card';
$lang['Ispapi.domain.NIF'] = 'NIF/NIE; For Spanish Individual or Organization';
$lang['Ispapi.domain.Otra'] = 'Otra; For non-spanish owner';
// .ES .VOTE .VOTO
$lang['Ispapi.domain.Agreement'] = 'Agreement';
// .IE domain fields
$lang['Ispapi.domain.RegistrantClass'] = 'Registrant Class';
$lang['Ispapi.domain.CompanyBusinessOwnerClub'] = 'Company,Business Owner,Club';
$lang['Ispapi.domain.Band'] = 'Band';
$lang['Ispapi.domain.LocalGroupSchool'] = 'Local Group,School';
$lang['Ispapi.domain.CollegeStateAgencyCharityBlogger'] = 'College,State Agency,Charity,Blogger';
$lang['Ispapi.domain.Other'] = 'Other';
$lang['Ispapi.domain.ProofofconnectiontoIreland'] = 'Proof of connection to Ireland';
// .NU .NO domain fields
$lang['Ispapi.domain.RegistrantIDnumber'] = 'Registrant ID number';
// .NU domain fields
$lang['Ispapi.domain.VatID'] = 'Vat ID';
// . NO domain fields
$lang['Ispapi.domain.Faxrequired'] = 'Fax required';
$lang['Ispapi.domain.NOFaxrequired.yes'] = 'I confirm I will send the following form back to complete the registration process: http://www.domainform.net/form/no/search?view=registration';
// .VOTE domain fields
$lang['Ispapi.domain.VOTEAgreement.yes'] = 'I confirm bona fide use of this domain name for a relevant election cycle with a clearly identified political/democratic process.';
// .VOTO domain fields
$lang['Ispapi.domain.VOTOAgreement.yes'] = 'I confirm bona fide use of this domain name for a relevant election cycle with a clearly identified political/democratic process.';
// .RO domain fields
$lang['Ispapi.domain.RegistrantVatID'] = 'Registrant VAT ID';
$lang['Ispapi.domain.RegistrantIDnumber'] = 'Registrant ID Number';
// .IT .FR .SG .EU .DE .JP .BAYERN .HAMBURG .RUHR .BERLIN domain fields
$lang['Ispapi.domain.LocalPresence'] = 'Local Presence';
// .DE domain fields
$lang['Ispapi.domain.deOptions'] = 'Registrant and/or Admin-C are domiciled in Germany / Use Local Presence Service';
// .ECO domain fields
$lang['Ispapi.domain.HighlyRegulatedTLD'] = 'I agree - Highly Regulated TLD:';
$lang['Ispapi.domain.ECOHighlyRegulatedTLD.yes'] = 'All .ECO domain names will be first registered with “server hold” status pending the completion of the minimum requirements of the Eco Profile, namely, the .ECO registrant 1) affirming their compliance with the .ECO Eligibility Policy and 2) pledging to support positive change for the planet and to be honest when sharing information on their environmental actions. The registrant will be emailed with instructions on how to create an Eco Profile. Once these steps have been completed, the .ECO domain will be immediately activated by the registry.';
// .PT domain fields
$lang['Ispapi.domain.RegistrantVatID'] = 'Registrant Vat ID';
$lang['Ispapi.domain.TechvatID'] = 'Tech Vat ID';
// .LV domain fields
$lang['Ispapi.domain.VatID'] = 'Vat ID';
$lang['Ispapi.domain.IDnumber'] = 'ID number';
// .SWISS domain fields
$lang['Ispapi.domain.EnterpriseID'] = 'Enterprise ID';
$lang['Ispapi.domain.SWISSIntendeduse'] = 'Intended use';
// .SCOT domain fields
$lang['Ispapi.domain.SCOTIntendeduse'] = 'Intended use';
// .QUEBEC domain fields
$lang['Ispapi.domain.QUEBECIntendeduse'] = 'Intended use';
// .COM.AU domain fields
$lang['Ispapi.domain.RegistrantIDType'] = 'Registrant ID Type';
$lang['Ispapi.domain.AustralianBusinessNumber'] = 'Australian Business Number';
$lang['Ispapi.domain.AustralianCompanyNumber'] = 'Australian Company Number';
$lang['Ispapi.domain.BusinessRegistrationNumber'] = 'Business Registration Number';
$lang['Ispapi.domain.TrademarkNumber'] = 'Trademark Number';
// .CA domain fields
$lang['Ispapi.domain.CIRALegalType'] = 'Legal Type';
$lang['Ispapi.domain.RegistrantPurpose.cco'] = 'Corporation';
$lang['Ispapi.domain.RegistrantPurpose.cct'] = 'Canadian citizen';
$lang['Ispapi.domain.RegistrantPurpose.res'] = 'Canadian resident';
$lang['Ispapi.domain.RegistrantPurpose.gov'] = 'Government entity';
$lang['Ispapi.domain.RegistrantPurpose.edu'] = 'Educational';
$lang['Ispapi.domain.RegistrantPurpose.ass'] = 'Unincorporated Association';
$lang['Ispapi.domain.RegistrantPurpose.hop'] = 'Hospital';
$lang['Ispapi.domain.RegistrantPurpose.prt'] = 'Partnership';
$lang['Ispapi.domain.RegistrantPurpose.tdm'] = 'Trade-mark';
$lang['Ispapi.domain.RegistrantPurpose.trd'] = 'Trade Union';
$lang['Ispapi.domain.RegistrantPurpose.plt'] = 'Political Party';
$lang['Ispapi.domain.RegistrantPurpose.lam'] = 'Libraries, Archives and Museums';
$lang['Ispapi.domain.RegistrantPurpose.trs'] = 'Trust';
$lang['Ispapi.domain.RegistrantPurpose.abo'] = 'Aboriginal Peoples';
$lang['Ispapi.domain.RegistrantPurpose.inb'] = 'Indian Band';
$lang['Ispapi.domain.RegistrantPurpose.lgr'] = 'Legal Representative';
$lang['Ispapi.domain.RegistrantPurpose.omk'] = 'Official Mark';
$lang['Ispapi.domain.RegistrantPurpose.maj'] = 'The Queen';
$lang['Ispapi.domain.CIRAWhoisDisplay'] = 'Whois';
$lang['Ispapi.domain.CIRAWhoisDisplay.full'] = 'Make Public';
$lang['Ispapi.domain.CIRAWhoisDisplay.private'] = 'Keep Private';
$lang['Ispapi.domain.CIRALanguage'] = 'Preferred language for communication';
$lang['Ispapi.domain.CIRALanguage.en'] = 'English';
$lang['Ispapi.domain.CIRALanguage.fr'] = 'French';
| a051fe27dae54b9c9ecfd3a2c5e42d020af16c2d | [
"Markdown",
"JavaScript",
"PHP",
"Shell"
] | 9 | Markdown | hexonet/blesta-ispapi-registrar | afac8d4b85bc2ce08564755b1f088f2788a14a30 | 4d5425ceee1adb008807488c9e4648d565a267d8 |
refs/heads/master | <repo_name>semartin3/master2016<file_sep>/r_ejercicio2.R
suma.dos.numeros <-function(n,m){
n+m
}
suma.dos.numeros(33,4)
menor.dos.numeros <-function(n,m){
min(n,m)
}
menor.dos.numeros(6,6)
<file_sep>/R/suma.dos.numeros.R
suma.dos.numeros <-
function(n,m){
n+m
}
<file_sep>/package1/R/menor.dos.numeros.R
menor.dos.numeros <-
function(n,m){
min(n,m)
}
| 032f241b25b0140aa4fe4e569fa34318c27683a0 | [
"R"
] | 3 | R | semartin3/master2016 | 2c4577547eb323a134c74f74895eda36492e8426 | 244500669288d46aca0ca1b81fa1d0e6a5e8a05a |
refs/heads/master | <repo_name>moonlight83340/Bash_test<file_sep>/ctoh.sh
#!/bin/bash
for name in *.c ; do
touch ${name%%c}h
done
| 756d740b6b0ad79d605e1799636ee815f7398666 | [
"Shell"
] | 1 | Shell | moonlight83340/Bash_test | 4ca986c9e365bb366917c2c05d99a08b5923298f | 64151993f485966bab7c18c920b9e0a02a7ed24a |
refs/heads/master | <repo_name>rpeterson/zamboni<file_sep>/mkt/developers/tests/test_forms.py
import json
import os
import shutil
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.core.files.uploadedfile import SimpleUploadedFile
import mock
from nose.tools import eq_
from test_utils import RequestFactory
import amo
import amo.tests
from amo.tests.test_helpers import get_image_path
from addons.models import Addon
from files.helpers import copyfileobj
import mkt
from mkt.developers import forms
from mkt.site.fixtures import fixture
from mkt.webapps.models import AddonExcludedRegion, Webapp
class TestPreviewForm(amo.tests.TestCase):
fixtures = ['base/addon_3615']
def setUp(self):
self.addon = Addon.objects.get(pk=3615)
self.dest = os.path.join(settings.TMP_PATH, 'preview')
if not os.path.exists(self.dest):
os.makedirs(self.dest)
@mock.patch('amo.models.ModelBase.update')
def test_preview_modified(self, update_mock):
name = 'transparent.png'
form = forms.PreviewForm({'caption': 'test', 'upload_hash': name,
'position': 1})
shutil.copyfile(get_image_path(name), os.path.join(self.dest, name))
assert form.is_valid()
form.save(self.addon)
assert update_mock.called
def test_preview_size(self):
name = 'non-animated.gif'
form = forms.PreviewForm({'caption': 'test', 'upload_hash': name,
'position': 1})
with storage.open(os.path.join(self.dest, name), 'wb') as f:
copyfileobj(open(get_image_path(name)), f)
assert form.is_valid()
form.save(self.addon)
eq_(self.addon.previews.all()[0].sizes,
{u'image': [250, 297], u'thumbnail': [180, 214]})
def check_file_type(self, type_):
form = forms.PreviewForm({'caption': 'test', 'upload_hash': type_,
'position': 1})
assert form.is_valid()
form.save(self.addon)
return self.addon.previews.all()[0].filetype
@mock.patch('lib.video.tasks.resize_video')
def test_preview_good_file_type(self, resize_video):
eq_(self.check_file_type('x.video-webm'), 'video/webm')
def test_preview_other_file_type(self):
eq_(self.check_file_type('x'), 'image/png')
def test_preview_bad_file_type(self):
eq_(self.check_file_type('x.foo'), 'image/png')
class TestRegionForm(amo.tests.WebappTestCase):
fixtures = ['webapps/337141-steamcube']
def setUp(self):
super(TestRegionForm, self).setUp()
self.request = RequestFactory()
self.kwargs = {'product': self.app}
def test_initial_empty(self):
form = forms.RegionForm(data=None, **self.kwargs)
eq_(form.initial['regions'], mkt.regions.REGION_IDS)
eq_(form.initial['other_regions'], True)
def test_initial_excluded_in_region(self):
AddonExcludedRegion.objects.create(addon=self.app,
region=mkt.regions.BR.id)
regions = list(mkt.regions.REGION_IDS)
regions.remove(mkt.regions.BR.id)
eq_(self.get_app().get_region_ids(), regions)
form = forms.RegionForm(data=None, **self.kwargs)
eq_(form.initial['regions'], regions)
eq_(form.initial['other_regions'], True)
def test_initial_excluded_in_regions_and_future_regions(self):
for region in [mkt.regions.BR, mkt.regions.UK, mkt.regions.WORLDWIDE]:
AddonExcludedRegion.objects.create(addon=self.app,
region=region.id)
regions = list(mkt.regions.REGION_IDS)
regions.remove(mkt.regions.BR.id)
regions.remove(mkt.regions.UK.id)
eq_(self.get_app().get_region_ids(), regions)
form = forms.RegionForm(data=None, **self.kwargs)
eq_(form.initial['regions'], regions)
eq_(form.initial['other_regions'], False)
def test_worldwide_only(self):
form = forms.RegionForm(data={'other_regions': 'on'}, **self.kwargs)
eq_(form.is_valid(), True)
form.save()
eq_(self.app.get_region_ids(True), [mkt.regions.WORLDWIDE.id])
def test_no_regions(self):
form = forms.RegionForm(data={}, **self.kwargs)
eq_(form.is_valid(), False)
eq_(form.errors,
{'__all__': ['You must select at least one region or '
'"Other and new regions."']})
class TestNewManifestForm(amo.tests.TestCase):
@mock.patch('mkt.developers.forms.verify_app_domain')
def test_normal_validator(self, _verify_app_domain):
form = forms.NewManifestForm({'manifest': 'http://omg.org/yes.webapp'},
is_standalone=False)
assert form.is_valid()
assert _verify_app_domain.called
@mock.patch('mkt.developers.forms.verify_app_domain')
def test_standalone_validator(self, _verify_app_domain):
form = forms.NewManifestForm({'manifest': 'http://omg.org/yes.webapp'},
is_standalone=True)
assert form.is_valid()
assert not _verify_app_domain.called
class TestNewManifestForm(amo.tests.TestCase):
@mock.patch('mkt.developers.forms.verify_app_domain')
def test_normal_validator(self, _verify_app_domain):
form = forms.NewManifestForm({'manifest': 'http://omg.org/yes.webapp'},
is_standalone=False)
assert form.is_valid()
assert _verify_app_domain.called
@mock.patch('mkt.developers.forms.verify_app_domain')
def test_standalone_validator(self, _verify_app_domain):
form = forms.NewManifestForm({'manifest': 'http://omg.org/yes.webapp'},
is_standalone=True)
assert form.is_valid()
assert not _verify_app_domain.called
class TestPackagedAppForm(amo.tests.AMOPaths, amo.tests.WebappTestCase):
def setUp(self):
path = self.packaged_app_path('mozball.zip')
self.files = {'upload': SimpleUploadedFile('mozball.zip',
open(path).read())}
def test_not_there(self):
form = forms.NewPackagedAppForm({}, {})
eq_(form.is_valid(), False)
eq_(form.errors['upload'], [u'This field is required.'])
eq_(form.file_upload, None)
def test_right_size(self):
form = forms.NewPackagedAppForm({}, self.files)
eq_(form.is_valid(), True)
assert form.file_upload
def test_too_big(self):
form = forms.NewPackagedAppForm({}, self.files, max_size=5)
eq_(form.is_valid(), False)
validation = json.loads(form.file_upload.validation)
assert 'messages' in validation, 'No messages in validation.'
eq_(validation['messages'][0]['message'],
[u'Packaged app too large for submission.',
u'Packages must be less than 5 bytes.'])
| 51ebee1aae82052e36f1d868e7a5157027881dc6 | [
"Python"
] | 1 | Python | rpeterson/zamboni | 7d8a4a14f11a3adb5cf306a40e77371372e8e79b | fb1bae485c078a5deb482c5a601b016bceeb8e71 |
refs/heads/master | <file_sep># GameOfLifeSharp
 
Example implementation for the (Conway's) Game of Life. See [Wikipedia entry](https://en.wikipedia.org/wiki/Conway's_Game_of_Life).
<file_sep>namespace GameOfLife.Tests
{
[TestClass]
public class ExampleTest
{
[TestMethod]
public void Example_NextUniverseIsCorrect()
{
// ARRANGE
// Ausgangs-Universum
// 0 1 2 3 4
// 0
// 1 x
// 2 x
// 3 x
// 4 x
var universe = new Universe();
universe.VitalizeCell(2, 1);
universe.VitalizeCell(3, 2);
universe.VitalizeCell(4, 3);
universe.VitalizeCell(2, 4);
// ACT
var nextUniverse = universe.Next();
// ASSERT
// Ziel-Universum
// 0 1 2 3 4
// 0
// 1
// 2 x
// 3 x
// 4
var expectedUniverse = new Universe();
expectedUniverse.VitalizeCell(3, 2);
expectedUniverse.VitalizeCell(3, 3);
Assert.IsTrue(nextUniverse.AliveCells.SetEquals(expectedUniverse.AliveCells));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace GameOfLife
{
public class Universe
{
HashSet<Tuple<int, int>> RelevantCells { get; } = new HashSet<Tuple<int, int>>();
public HashSet<Tuple<int, int>> AliveCells { get; } = new HashSet<Tuple<int, int>>();
delegate void CellAction(Tuple<int, int> position);
// Universum soll nach Spezifikation immutable sein => neues Universum ausgeben.
public Universe Next()
{
var nextUniverse = new Universe();
foreach (var cellPosition in RelevantCells)
{
// Zähle Nachbarn
var neighborCount = 0;
ProcessNeighbors(cellPosition, pos =>
{
if (!cellPosition.Equals(pos) && AliveCells.Contains(pos))
{
neighborCount++;
}
});
// Lebende mit 2-3 Nachbarn überleben
if (AliveCells.Contains(cellPosition))
{
if (neighborCount == 2 || neighborCount == 3)
nextUniverse.VitalizeCell(cellPosition);
}
// Tote mit 3 Nachbarn werden lebend
else
{
if (neighborCount == 3)
nextUniverse.VitalizeCell(cellPosition);
}
// Der Rest ist nicht am Leben
}
return nextUniverse;
}
public void VitalizeCell(Tuple<int, int> position)
{
AliveCells.Add(position);
// Relevante Zellen speichern, um nicht gesamtes Grid durchlaufen zu müssen
ProcessNeighbors(position, pos => RelevantCells.Add(pos));
}
public void VitalizeCell(int x, int y)
{
VitalizeCell(new Tuple<int, int>(x, y));
}
void ProcessNeighbors(Tuple<int, int> position, CellAction action)
{
for (var x = position.Item1 - 1; x <= position.Item1 + 1; x++)
for (var y = position.Item2 - 1; y <= position.Item2 + 1; y++)
{
action(new Tuple<int, int>(x, y));
}
}
}
}
<file_sep>using System;
using System.Threading;
namespace GameOfLife
{
class Program
{
static void Main(string[] args)
{
// Visualisierung vom Test
// ARRANGE
var universe = new Universe();
universe.VitalizeCell(2, 1);
universe.VitalizeCell(3, 2);
universe.VitalizeCell(4, 3);
universe.VitalizeCell(2, 4);
Console.WriteLine("Original Universum:");
PrintUniverse(universe, 0, 4, 0, 4);
// ACT
var nextUniverse = universe.Next();
Console.WriteLine("Nächstes Universum:");
PrintUniverse(nextUniverse, 0, 4, 0, 4);
// ASSERT
var expectedUniverse = new Universe();
expectedUniverse.VitalizeCell(3, 2);
expectedUniverse.VitalizeCell(3, 3);
Console.WriteLine("Erwartetes Universum:");
PrintUniverse(expectedUniverse, 0, 4, 0, 4);
// "Glider" Spaceship
Console.WriteLine("=====================");
universe = new Universe();
universe.VitalizeCell(0, 1);
universe.VitalizeCell(1, 2);
universe.VitalizeCell(2, 0);
universe.VitalizeCell(2, 1);
universe.VitalizeCell(2, 2);
while (true)
{
Thread.Sleep(500);
Console.WriteLine("Nächstes Universum:");
if (!PrintUniverse(universe, 0, 4, 0, 4, false))
{
Console.WriteLine("Universum lässt sich nicht weiter beobachten…");
break;
}
universe = universe.Next();
}
}
static bool PrintUniverse(Universe universe, int minX, int maxX, int minY, int maxY, bool printHeader = true)
{
var hasObservableContent = false;
for (var y = minY - 1; y <= maxY; y++)
{
for (var x = minX - 1; x <= maxX; x++)
{
if (y < minY && printHeader)
{
if (x < minX)
Console.Write(" ");
else
Console.Write($"{x} ");
}
else
{
if (x < minX && printHeader)
Console.Write($"{y} ");
else
{
if (universe.AliveCells.Contains(new Tuple<int, int>(x, y)))
{
Console.Write("x ");
hasObservableContent = true;
}
else
Console.Write(" ");
}
}
}
Console.WriteLine("");
}
return hasObservableContent;
}
}
}
| 6600890d3c22953c54f6d15cbed82f448f9f55bb | [
"Markdown",
"C#"
] | 4 | Markdown | genericFJS/GameOfLifeSharp | aeac9dcbaccb014cde88b6a6ec676810c8e31d46 | 6c179e5d742aa34e6c70f0b449e4797bbbe8913d |
refs/heads/main | <repo_name>aeither/Discovery<file_sep>/packages/discovery-dapp/components/mobile-menu-toggle.js
import React from "react";
import {
Box,
Drawer,
DrawerBody,
DrawerHeader,
DrawerOverlay,
DrawerContent,
DrawerCloseButton,
useDisclosure,
VStack,
Tooltip,
SimpleGrid,
} from "@chakra-ui/react";
import { Mail, MailOutline, Menu } from "heroicons-react";
import MobileMenuButton from "./mobile-menu-button";
import MobileMenuItem from "./mobile-menu-item";
const MobileMenuToggle = ({ mobile }) => {
const { isOpen, onOpen, onClose } = useDisclosure();
const btnRef = React.useRef();
return (
<Box>
<Tooltip label="Newsletter">
<MobileMenuButton label="Menu" icon={<Menu />} onClick={onOpen} />
</Tooltip>
<Drawer
isOpen={isOpen}
placement="bottom"
onClose={onClose}
finalFocusRef={btnRef}
>
<DrawerOverlay>
<DrawerContent borderTopRadius="6px">
<DrawerCloseButton />
<DrawerHeader>Menu</DrawerHeader>
<DrawerBody pb={4}>
<VStack>
<MobileMenuItem href="/" title="Home" />
<MobileMenuItem href="/link" title="Get started" />
<MobileMenuItem href="/link" title="Paths" />
<MobileMenuItem href="/link" title="Get Involved" />
<SimpleGrid columns={2} spacing={2} w="100%">
<MobileMenuItem href="/link" title="Github" />
<MobileMenuItem href="/link" title="Community" />
</SimpleGrid>
</VStack>
</DrawerBody>
</DrawerContent>
</DrawerOverlay>
</Drawer>
</Box>
);
};
export default MobileMenuToggle;
<file_sep>/packages/discovery-dapp/pages/paths.js
import React from "react";
import { VStack, Text, Heading, useColorModeValue } from "@chakra-ui/react";
import PageTransition from "../components/page-transitions";
import Section from "../components/section";
import { ethers } from "ethers";
import { useEffect, useState } from "react";
import Web3Modal from "web3modal";
const Paths = () => {
const [address, setAddress] = useState();
useEffect(() => {
fetchUser();
}, []);
async function fetchUser() {
const web3Modal = new Web3Modal();
const connection = await web3Modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
const signer = provider.getSigner();
const userAddress = await signer.getAddress();
setAddress(userAddress);
setEventListeners(provider);
console.log("Account:", userAddress);
}
function setEventListeners(provider) {
// Subscribe to accounts change
provider.on("accountsChanged", (accounts) => {
console.log(accounts);
});
// Subscribe to chainId change
provider.on("chainChanged", (chainId) => {
console.log(chainId);
});
// Subscribe to provider connection
provider.on("connect", (info) => {
console.log(info);
});
// Subscribe to provider disconnection
provider.on("disconnect", (error) => {
console.log(error);
});
}
return (
<PageTransition>
<VStack spacing={8}>
<Section>
<VStack>
<Text
fontSize={["m", "l"]}
color={useColorModeValue("gray.800", "gray.600")}
maxW="lg"
textAlign="center"
>
Connected with: {address}
</Text>
<Heading as="h1">Paths</Heading>
<Text
fontSize={["xl", "2xl"]}
color={useColorModeValue("gray.500", "gray.200")}
maxW="lg"
textAlign="center"
>
Discovery paths categories: social entertainment, video, virtual
reality, art & collectibles
</Text>
</VStack>
</Section>
</VStack>
</PageTransition>
);
};
export default Paths;
<file_sep>/packages/discovery-dapp/pages/_app.js
import * as React from "react";
import { Box, ChakraProvider } from "@chakra-ui/react";
import { extendTheme } from "@chakra-ui/react";
import Header from "../components/header";
import MobileNavigation from "../components/mobile-navigation";
const colors = {
brand: {
900: "#1a365d",
800: "#153e75",
700: "#2a69ac",
},
};
const theme = extendTheme({ colors });
function App({ Component, pageProps }) {
return (
<ChakraProvider theme={theme}>
<Header />
<Box as="main" pt={{ base: 16, md: 32 }} pb={{ base: 24, md: 16 }}>
<Component {...pageProps} />
</Box>{" "}
<MobileNavigation />
</ChakraProvider>
);
}
export default App;
<file_sep>/packages/discovery-dapp/components/avatar-navigation.js
import React from "react";
import { Avatar } from "@chakra-ui/react";
import Link from "next/link";
const AvatarNavigation = () => {
return (
<Link href="/">
<Avatar
name="Discovery Dapp"
size="sm"
// src="/logo.png"
cursor="pointer"
/>
</Link>
);
};
export default AvatarNavigation;
<file_sep>/packages/discovery-dapp/pages/index.js
import { ethers } from "ethers";
import { useEffect, useState } from "react";
import axios from "axios";
import Web3Modal from "web3modal";
import Link from 'next/link'
export default function Home() {
const [address, setAddress] = useState();
useEffect(() => {
async function fetchUser() {
const web3Modal = new Web3Modal()
const connection = await web3Modal.connect()
const provider = new ethers.providers.Web3Provider(connection)
const signer = provider.getSigner()
const userAddress = await signer.getAddress()
setAddress(userAddress)
console.log("Account:", userAddress);
// const provider = new ethers.providers.Web3Provider(
// window.ethereum,
// "any"
// );
// // Prompt user for account connections
// await provider.send("eth_requestAccounts", []);
// const signer = provider.getSigner();
// console.log("Account:", await signer.getAddress());
}
fetchUser();
},[]);
return <div>Hello world</div>; {address}
}
| 4fb4161178ed0b7806a200446a369d7587fc92f8 | [
"JavaScript"
] | 5 | JavaScript | aeither/Discovery | eb3f729d93b5d8da66069182e923581795471f53 | a5a8827cf4d6eb30e08e5d257fdeb68c7972dbfd |
refs/heads/master | <file_sep>'''
Created on 07.05.2012
@author: alekam
'''
from django.conf import settings
from django.core.management.base import BaseCommand
from shpaml import shpaml
import os
class Command(BaseCommand):
help = "Find SHPAML templates and compile its to HTML Django templates."
requires_model_validation = False
def handle(self, filename=None, force=False, **options):
self.force = force
if filename is None:
for pathname in settings.TEMPLATE_DIRS:
self.process_dir(pathname)
else:
if not filename.endswith('.shpaml'):
print u'File "%s" is not shpaml template' % filename
for dirname in settings.TEMPLATE_DIRS:
file_name = os.path.join(dirname, filename)
if os.path.exists(file_name):
self.process_file(dirname, filename)
else:
print u'File "%s" is not found' % file_name
def process_dir(self, pathname):
for dirname, dirnames, filenames in os.walk(pathname):
for subdirname in dirnames:
self.process_dir(os.path.join(dirname, subdirname))
for filename in filenames:
if filename.endswith('.shpaml'):
self.process_file(dirname, filename)
def process_file(self, pathname, filename):
html_filename = os.path.join(pathname, u"%s.html" % filename[:-7])
f = open(os.path.join(pathname, filename))
if os.path.exists(html_filename):
if not self.force:
print u"File %s already exists and will be skipped" % html_filename
return
os.remove(html_filename)
html_f = open(html_filename, 'w+')
html_f.write(shpaml.convert_text(f.read()))
f.close()
html_f.close()
print u"Write file %s" % html_filename
| 56879bc0ff92a6c861a8b7b0175ac999b9cfb976 | [
"Python"
] | 1 | Python | alekam/shpaml | 9fe8b03e0912fa42d9228757f6734f063e5ec0ba | 0d533061b7bd5ea236d680376924a2af17ccba34 |
refs/heads/master | <file_sep>package xmlGenerator.GUI;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import Main.Car;
import Main.Driver;
import Main.Position;
import Main.Vehicule;
import xmlGenerator.Type;
public class MenuAction
{
/**
* opens an image and display it in the drawPanel
* @param menuBar menubar
* @return actionListener
*/
public static ActionListener openImage(final MenuBar menuBar)
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileExplorer = new JFileChooser();
int result = fileExplorer.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
{
File file = fileExplorer.getSelectedFile();
try
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screenWidth = screenSize.getWidth();
double screenHeight = screenSize.getHeight();
if(ImageIO.read(file).getWidth() > screenWidth || ImageIO.read(file).getHeight() > screenHeight )
{
JOptionPane.showMessageDialog(null, "Image resolution is too big.");
}
else
{
menuBar.getDrawPanel().setImage(ImageIO.read(file));
System.out.println(fileExplorer.getSelectedFile().getName());
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
return;
}
}
};
}
/**
* Erases the last pointer draw
* @param menuBar menuBar
* @return actionListener
*/
public static ActionListener erase(final MenuBar menuBar)
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
menuBar.getDrawPanel().erase();
}
};
}
/**
* Erases all the pointers contained in the drawPanel
* @param menuBar menubar
* @return actionListener
*/
public static ActionListener eraseAll(final MenuBar menuBar)
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
menuBar.getDrawPanel().eraseAll();
}
};
}
/**
* Quits the application
* @param menuBar menubar
* @return actionListener
*/
public static ActionListener quit(final MenuBar menuBar)
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (JOptionPane.showConfirmDialog(null, "Do you really want to quit Photop ?", "Confirmation", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION)
System.exit(0);
}
};
}
/**
* Saves the image and all the pointers contained in the drawpanel
* @param menuBar menubar
* @return ActionListener
*/
public static ActionListener saveImage(final MenuBar menuBar)
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser directoryChooser = new JFileChooser();
directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(menuBar.getImageAlreadySaved())
{
try
{
JOptionPane.showMessageDialog(null, "Saving in progress");
menuBar.setCurrentImage(new Robot().createScreenCapture(new Rectangle(menuBar.getDrawPanel().getLocationOnScreen().x, menuBar.getDrawPanel().getLocationOnScreen().y, menuBar.getDrawPanel().getWidth(), menuBar.getDrawPanel().getHeight())));
ImageIO.write(menuBar.getCurrentImage(), "PNG", new File(menuBar.getImagePath()+"/"+menuBar.getImageName()+".PNG"));
JOptionPane.showMessageDialog(null, "Image "+menuBar.getImageName()+".png saved !");
}
catch (IOException e1)
{
e1.printStackTrace();
}
catch (AWTException e1)
{
e1.printStackTrace();
}
}
else
{
menuBar.setImageName(JOptionPane.showInputDialog(menuBar.getDrawPanel(),"Name of the image ?"));
if(menuBar.getImageName() != null)
{
if(directoryChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
menuBar.setImagePath(directoryChooser.getSelectedFile().getPath());
try
{
try
{
menuBar.setCurrentImage(new Robot().createScreenCapture(new Rectangle(menuBar.getDrawPanel().getLocationOnScreen().x, menuBar.getDrawPanel().getLocationOnScreen().y, menuBar.getDrawPanel().getWidth(), menuBar.getDrawPanel().getHeight())));
ImageIO.write(menuBar.getCurrentImage(), "PNG", new File(menuBar.getImagePath()+"/"+menuBar.getImageName()+".PNG"));
JOptionPane.showMessageDialog(null, "Image "+menuBar.getImageName()+".png saved !");
menuBar.setImageAlreadySaved(true);
}
catch (AWTException e1)
{
e1.printStackTrace();
}
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
}
};
}
/**
*
* @param menuBar menubar
* @return ActionListener
*/
public static ActionListener saveAsImage(final MenuBar menuBar)
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser directoryChooser = new JFileChooser();
directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
menuBar.setImageName(JOptionPane.showInputDialog(menuBar.getDrawPanel(),"Name of the image ?"));
if(menuBar.getImageName() != null)
{
if(directoryChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
menuBar.setImagePath(directoryChooser.getSelectedFile().getPath());
try
{
try
{
menuBar.setCurrentImage(new Robot().createScreenCapture(new Rectangle(menuBar.getDrawPanel().getLocationOnScreen().x, menuBar.getDrawPanel().getLocationOnScreen().y, menuBar.getDrawPanel().getWidth(), menuBar.getDrawPanel().getHeight())));
ImageIO.write(menuBar.getCurrentImage(), "PNG", new File(menuBar.getImagePath()+"/"+menuBar.getImageName()+".PNG"));
JOptionPane.showMessageDialog(null, "Image "+menuBar.getImageName()+".png saved !");
menuBar.setImageAlreadySaved(true);
}
catch (AWTException e1)
{
e1.printStackTrace();
}
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
};
}
/**
* Creates an image with a specific height and width and display it in the drawPanel
* @param menuBar menubar
* @param window window
* @return ActionListener actionListener
*/
public static ActionListener createImage(final MenuBar menuBar, final JFrame window)
{
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
int height = Integer.parseInt(new JOptionPane().showInputDialog(null,"Which height do you want ?"));
int width = Integer.parseInt(new JOptionPane().showInputDialog(null,"Which width do you want ?"));
if(height <= 0 || width <= 0)
{
JOptionPane.showMessageDialog(null, "Invalid size");
}
else
{
menuBar.getDrawPanel().eraseAll();
window.setSize(width, height);
window.setResizable(false);
}
}
};
}
public static ActionListener car(final MenuBar menuBar)
{
return new ActionListener()
{
public void actionPerformed(ActionEvent e, Vehicule v)
{
menuBar.getDrawPanel().setPointerType(Type.CAR);
System.out.println("vehicule créé");
Collection<Vehicule> vehicule = new ArrayList<Vehicule>();
Vehicule v1 = new Car(100, 10,new Position(90,90), new Position(100,100) , new Driver(),10);
vehicule.add(v1);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
}
public static ActionListener truck(MenuBar menuBar) {
return new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
menuBar.getDrawPanel().setPointerType(Type.TRUCK);
}
};
}
}
<file_sep>package Main;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author Bastien26
*
*/
public class XML {
//public Scenario scenario;
public void toXML(Scenario s){
/*
* Etape 1 : récupération d'une instance de la classe "DocumentBuilderFactory"
*/
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
/*
* Etape 2 : création d'un parseur
*/
final DocumentBuilder builder = factory.newDocumentBuilder();
/*
* Etape 3 : création d'un Document
*/
final Document document= builder.newDocument();
/*
* Etape 4 : création de l'Element racine
*/
Collection<Vehicule> vehicule = s.getVehicules();
Environement e = s.getEnvironement();
Collection<Signaling> signaling = e.getSignaling();
/**
* Partie Véhicule
*/
final Element racine = document.createElement("Scenario");
document.appendChild(racine);
/*
* Etape 5 : création d'une personne
*/
int compteurId = 1;
for (Vehicule v: vehicule){
final Element vehi = document.createElement(v.getType());
vehi.setAttribute("id", Integer.toString(compteurId));
racine.appendChild(vehi);
final Element lenth = document.createElement("lenth");
lenth.appendChild(document.createTextNode(v.getLenth().toString()));
final Element maxSpeed = document.createElement("maxSpeed");
maxSpeed.appendChild(document.createTextNode(v.getMaxSpeed().toString()));
final Element brakingDistance = document.createElement("brakingDistance");
brakingDistance.appendChild(document.createTextNode(v.getBrakingDistance().toString()));
final Element startingPositionX = document.createElement("startingPositionX");
startingPositionX.appendChild(document.createTextNode(v.getStartingPosition().getX().toString()));
final Element startingPositionY = document.createElement("startingPositionY");
startingPositionY.appendChild(document.createTextNode(v.getStartingPosition().getY().toString()));
final Element endingPositionX = document.createElement("endingPositionX");
endingPositionX.appendChild(document.createTextNode(v.getEndingPosition().getX().toString()));
final Element endingPositionY = document.createElement("endingPositionY");
endingPositionY.appendChild(document.createTextNode(v.getEndingPosition().getX().toString()));
final Element driver = document.createElement("driver");
driver.appendChild(document.createTextNode("driver"));
final Element width = document.createElement("width");
width.appendChild(document.createTextNode(v.getWidth().toString()));
vehi.appendChild(lenth);
vehi.appendChild(maxSpeed);
vehi.appendChild(brakingDistance);
vehi.appendChild(startingPositionX);
vehi.appendChild(startingPositionY);
vehi.appendChild(endingPositionX);
vehi.appendChild(endingPositionY);
vehi.appendChild(driver);
vehi.appendChild(width);
compteurId++;
}
/**
* Partie environement
*/
final Element pic = document.createElement("Picture");
racine.appendChild(pic);
final Element picture = document.createElement("file");
picture.appendChild(document.createTextNode("./img/picture"));
pic.appendChild(picture);
for (Signaling si: signaling){
final Element signa = document.createElement(si.getType());
racine.appendChild(signa);
final Element id = document.createElement("id");
id.appendChild(document.createTextNode(si.getId().toString()));
signa.appendChild(id);
final Element positionX = document.createElement("positionX");
positionX.appendChild(document.createTextNode(si.getPosition().getX().toString()));
signa.appendChild(positionX);
final Element positionY = document.createElement("positionY");
positionY.appendChild(document.createTextNode(si.getPosition().getY().toString()));
signa.appendChild(positionY);
final Element idSignalingPosible = document.createElement("idSignalingPosible");
idSignalingPosible.appendChild(document.createTextNode(si.getIdSignalingPosible().toString()));
signa.appendChild(idSignalingPosible);
if(si.getType() == "TrafficLight"){
final Element redDuration = document.createElement("redDuration");
redDuration.appendChild(document.createTextNode(si.getRedDuration().toString()));
signa.appendChild(redDuration);
final Element greenDuration = document.createElement("greenDuration");
greenDuration.appendChild(document.createTextNode(si.getGreenDuration().toString()));
signa.appendChild(greenDuration);
}
}
/*
* affichage
*/
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
final DOMSource source = new DOMSource(document);
final StreamResult sortie = new StreamResult(new File("file.xml"));
//final StreamResult result = new StreamResult(System.out);
//prologue
transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
//formatage
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
//sortie
transformer.transform(source, sortie);
}
catch (final ParserConfigurationException e) {
e.printStackTrace();
}
catch (TransformerConfigurationException e) {
e.printStackTrace();
}
catch (TransformerException e) {
e.printStackTrace();
}
}
}
<file_sep>package Main;
/**
*
* @author Bastien26
*
*/
//on s'en sert pas pour l'instant
// peut etre la supprimer plust tard
public class Graph {
public Position position;
public Signaling object;
}
<file_sep>package Main;
import java.util.Collection;
/**
*
* @author Bastien26
*
*/
public class Crossroad extends Signaling{
public Crossroad(Integer id, Position position,Collection<Integer> idSignalingPosible) {
super(id, position, idSignalingPosible);
}
@Override
String getType() {
// TODO Auto-generated method stub
return "Crossroad";
}
@Override
Integer getRedDuration() {
// TODO Auto-generated method stub
return null;
}
@Override
Integer getGreenDuration() {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>package xmlGenerator.GUI;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import xmlGenerator.XmlGenerator;
/**
* where we create the GUI
*/
public class GUIXmlGenerator implements Runnable
{
/**
* The window of the application
*/
private JFrame window;
/**
* the generator
*/
private XmlGenerator generator;
/**
* the drawing panel
*/
private DrawPanel drawPanel;
/**
* the MenuBar
*/
private MenuBar menuBar;
/**
* the constructor of the GUI
* @param photop photop
*/
public GUIXmlGenerator (XmlGenerator photop)
{
this.generator = photop;
}
/**
* Creates the GUI
*/
private void GUIPhotopCreator()
{
this.window = new JFrame();
this.window.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.window.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.window.setLocationRelativeTo(null);
this.window.setTitle("XML-Generator");
this.drawPanel = new DrawPanel(null);
this.menuBar = new MenuBar(this.drawPanel);
this.menuBar.initMenu(this.window);
this.window.getContentPane().add(drawPanel);
this.window.setVisible(true);
}
/**
* The method run
*/
@Override
public void run()
{
this.GUIPhotopCreator();
}
}
<file_sep>package Main;
import java.util.Collection;
/**
*
* @author Bastien26
*
*/
public class Sign extends Signaling{
public Sign(Integer id, Position position, Collection<Integer> idSignalingPosible) {
super(id, position, idSignalingPosible);
}
@Override
String getType() {
return "Sign";
}
@Override
Integer getRedDuration() {
// TODO Auto-generated method stub
return null;
}
@Override
Integer getGreenDuration() {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>package xmlGenerator;
import java.awt.Color;
public class Pointer
{
/**
* the pointer's type
*/
private Type type;
/**
* The pointer's size
*/
private int size;
/**
* Initializes the default pointer
* The default pointer is black, is a circle and measures 100px
*/
public Pointer()
{
this.type = Type.CAR;
this.size = 100;
}
/**
* Initializes the pointer with a given color, type and size
* @param col the given color
* @param shap the given type
* @param siz the given size
*/
public Pointer(Color col, Type shap, int siz)
{
this.type = shap;
this.size = siz;
}
/**
* Sets the pointer's type with a given TypeShape
* @param shape shape
*/
public void setShape(Type shape)
{
this.type = shape;
}
/**
* Sets the pointer's size with a given size
* @param size size
*/
public void setSize(int size)
{
this.size = size;
}
/**
* Returns the pointer's type
* @return type the pointer's type
*/
public Type getType()
{
return type;
}
/**
* Returns the pointer's size
* @return size the pointer's size
*/
public int getSize()
{
return size;
}
}
<file_sep>package Main;
import java.util.Collection;
/**
*
* @author Bastien26
*
*/
public class Environement {
public String picture;
public Collection<Signaling> signaling;
public Environement(String picture, Collection<Signaling> signaling) {
this.picture = picture;
this.signaling = signaling;
}
public String getPicture() {
return picture;
}
public Collection<Signaling> getSignaling() {
return signaling;
}
}
<file_sep>package Main;
/**
*
* @author Bastien26
*
*/
public class Picture {
//public File picture;
}
<file_sep>package xmlGenerator;
public enum Type
{
CAR,
TRUCK;
}
<file_sep>package Main;
public class Arc {
private int id ;
private Node nonestart;
private Node nonefinish;
private int vitessemax;
public Arc(int id, Node nonestart, Node nonefinish, int vitessemax) {
this.id = id;
this.nonestart = nonestart;
this.nonefinish = nonefinish;
this.vitessemax = vitessemax;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Node getNonestart() {
return nonestart;
}
public void setNonestart(Node nonestart) {
this.nonestart = nonestart;
}
public Node getNonefinish() {
return nonefinish;
}
public void setNonefinish(Node nonefinish) {
this.nonefinish = nonefinish;
}
public int getVitessemax() {
return vitessemax;
}
public void setVitessemax(int vitessemax) {
this.vitessemax = vitessemax;
}
} | b00b2a1634251c18e2a7899265bec03585057ae1 | [
"Java"
] | 11 | Java | polocea/XML-generator | 2275e838c011ab8d7ae53f66d42c54bb4f21f235 | d5379e7156b59dc90085d55928059562bfd4eafa |
refs/heads/master | <file_sep>#!/usr/bin/python3
#
# Copyright 2017 Canonical, Ltd. Authored by <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
import os
import sys
import yaml
def get_kubeconfig(cfg):
if not os.path.exists(cfg):
return
with open(cfg) as f:
return yaml.safe_load(f.read())
def merge_cfg(cfg, new_cfg):
if not isinstance(cfg, dict) or not isinstance(new_cfg, dict):
return None
for k, v in new_cfg.items():
if k not in cfg:
cfg[k] = v
elif isinstance(v, list):
cfg[k] = cfg[k] + v
else:
cfg[k] = merge_cfg(cfg[k], v)
return cfg
def merge_config(kubecfg_file, newcfg_file, name):
kubecfg = get_kubeconfig(kubecfg_file)
newcfg = get_kubeconfig(newcfg_file)
if not kubecfg or not newcfg:
print("kubecfg {} newcfg {}".format(kubecfg_file, newcfg_file))
print(kubecfg, kubecfg_file)
return 1
newcfg['clusters'][0]['name'] = '{}-cluster'.format(name)
newcfg['users'][0]['name'] = '{}-user'.format(name)
newcfg['contexts'][0]['name'] = name
newcfg['contexts'][0]['context']['cluster'] = '{}-cluster'.format(name)
newcfg['contexts'][0]['context']['user'] = '{}-user'.format(name)
kubecfg = merge_cfg(kubecfg, newcfg)
with open(kubecfg_file, 'r+') as f:
f.seek(0)
f.write(yaml.dump(kubecfg, default_flow_style=False))
f.truncate()
if __name__ == '__main__':
KUBEHOME = os.path.expanduser('~/.kube')
KUBECONFIG_FILE = os.path.join(KUBEHOME, 'config')
if len(sys.argv) != 3:
print('Where da args at?' if len(sys.argv) < 3 else 'Too many args bruv')
sys.exit(1)
NEWCONFIG_FILE = os.path.expanduser(sys.argv[1])
NAME = sys.argv[2]
rc = merge_config(KUBECONFIG_FILE, NEWCONFIG_FILE, NAME) or 0
sys.exit(rc)
<file_sep># Matrial Used in the "Federated K8s with on-prem Clusters and Juju (WIP)" post
| 03e08517dd592a618a161e1d47b93dd84153f6b1 | [
"Markdown",
"Python"
] | 2 | Python | ktsakalozos/blog-post-federation | 890589cac5e0fd2d6a3ba4a21ce8052c06afba34 | 4cfe0ef6165cf8568db7eecff89c4095d88cefd0 |
refs/heads/master | <repo_name>woxry/test2php<file_sep>/server/structure.sql
-- STRUCTURE INDEX
-- Instructions: Run the code in the console, when you alredy log into your Mysql user
-- 1- CREATE DATABASE (nombre de la base de datos)
-- 2- VIDEO GAMES TABLE
-- 3- DEFAULT VIDEO GAMES
CREATE DATABASE test2_db;
CREATE TABLE IF NOT EXISTS video_games (
id_video_game INT(11) NOT NULL AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
developer VARCHAR(255) COLLATE utf8_spanish_ci NOT NULL,
description VARCHAR(500) COLLATE utf8_spanish_ci NOT NULL,
console VARCHAR(255) COLLATE utf8_spanish_ci NOT NULL,
release_date DATE NOT NULL,
qualification DOUBLE NOT NULL,
video_game_picture VARCHAR(255) NOT NULL,
PRIMARY KEY (id_video_game)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
INSERT INTO video_games (title, developer, description, console, release_date, qualification, video_game_picture)
VALUES("Black Desert", "Pearl Abyss", "BD is a sandbox-oriented massively multiplayer online role-playing game by Korean video game developer Pearl Abyss.", "PC", "2016-03-03", "5", "http://www.black-desert.com/wp-content/uploads/2013/07/BlackDesert.jpg"),
("Ragnarok", "Gravity", "(Ro is a korean game, alternatively subtitled The Final Destiny of the Gods), often referred to as RO, is a Korean massive multiplayer online role-playing game or MMORPG created by GRAVITY Co., Ltd.", "PC", "2010-08-31", "4", "https://www.google.com/search?q=ragnarok+wiki&espv=2&biw=1438&bih=756&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiKm4f_x4_MAhWLOD4KHeRZBEAQ_AUIBigB#imgrc=Gok5g5zOcIHORM%3A"),
("Archeage", "XLGames", "AA is an MMORPG developed by Korean developer <NAME> (former developer of Lineage) and his development company, XL Games. The game was released in Korea on January 15, 2013, Europe and North America on September 16, 2014, and has also had a closed beta in China.", "PC", "2013-01-15", "5", "http://mp4vod-archeage.x-cdn.com/preview_en/res_1/images/zone/area/3.jpg");
<file_sep>/README.md
# Second Test PHP + MySQL
##About the test
#To use the project
>1 Download or install composer in the root of the project --> https://getcomposer.org/doc/00-intro.md
>2 php composer.phar install (root)
>3 Download Postman to test the routes
>4 You need MySQL to create the database
>5 Use the api.txt in the server folder for more instructions
<file_sep>/server/app/src/controllers/GameController.php
<?php
namespace App\Controllers;
use App\Services\LoggingService;
use App\Services\GameService;
use Slim\Http\Request;
class GameController {
private $gameService;
/**
* GameController constructor.
*/
public function __construct() {
$this->gameService = new GameService();
}
/**
* Update one by Id
* @param Request $request
*
* @return []
*/
public function update($request, $args) {
$result = [];
$id_video_game = $args['id'];
$formData = $request->getParsedBody();
$title = null;
$developer = null;
$description = null;
$console = null;
$release_date = null;
$qualification = null;
$video_game_picture = null;
// Verify the entry of title
if (array_key_exists("title", $formData)) {
$title = $formData["title"];
}
// Verify the entry of developer
if (array_key_exists("developer", $formData)) {
$developer = $formData["developer"];
}
// Verify the entry of description
if (array_key_exists("description", $formData)) {
$description = $formData["description"];
}
// Verify the entry of console
if (array_key_exists("console", $formData)) {
$console = $formData["console"];
}
// Verify the entry of release_date
if (array_key_exists("release_date", $formData)) {
$release_date = $formData["release_date"];
}
// Verify the entry of qualification
if (array_key_exists("qualification", $formData)) {
$qualification = $formData["qualification"];
}
// Verify the entry of video_game_picture
if (array_key_exists("video_game_picture", $formData)) {
$video_game_picture = $formData["video_game_picture"];
}
if (isset($title, $developer, $description, $console, $release_date, $qualification, $video_game_picture)) {
$updateResult = $this->gameService->update($id_video_game, $title, $developer, $description, $console, $release_date, $qualification, $video_game_picture);
if (array_key_exists("error", $updateResult)) {
$result["error"] = true;
}
$result["message"] = $updateResult["message"];
}else {
$result["error"] = true;
$result["message"] = "No pueden haber datos vacíos.";
}
return $result;
}
/**
* Delete one by Id
* @param Request $request
*
* @return []
*/
public function delete($request, $args) {
$result = [];
$id_video_game = $args['id'];
$deleteResult = $this->gameService->delete($id_video_game);
if (array_key_exists("error", $deleteResult)) {
$result["error"] = true;
}
$result["message"] = $deleteResult["message"];
return $result;
}
/**
* Get one video game by Id
* @param Request $request
*
* @return []
*/
public function getOne($request, $args) {
$result = [];
$id_video_game = $args['id'];
$getOneResult = $this->gameService->getOne($id_video_game);
if (array_key_exists("error", $getOneResult)) {
$result["error"] = true;
} else {
$result["game"] = $getOneResult["game"];
}
$result["message"] = $getOneResult["message"];
return $result;
}
/**
* Get all the video games
*
* @param Request $request
*
* @return []
*/
public function getAll($request) {
$result = [];
$getAllResult = $this->gameService->getAll();
if (array_key_exists("error", $getAllResult)) {
$result["error"] = true;
} else {
$result["data"] = $getAllResult["data"];
}
$result["message"] = $getAllResult["message"];
return $result;
}
/**
* Register a new video game into de database
* @param Request $request
*
* @return string []
*/
public function register($request) {
$result = [];
$formData = $request->getParsedBody();
$title = null;
$developer = null;
$description = null;
$console = null;
$release_date = null;
$qualification = null;
$video_game_picture = null;
// Verify the entry of title
if (array_key_exists("title", $formData)) {
$title = $formData["title"];
}
// Verify the entry of developer
if (array_key_exists("developer", $formData)) {
$developer = $formData["developer"];
}
// Verify the entry of description
if (array_key_exists("description", $formData)) {
$description = $formData["description"];
}
// Verify the entry of console
if (array_key_exists("console", $formData)) {
$console = $formData["console"];
}
// Verify the entry of release_date
if (array_key_exists("release_date", $formData)) {
$release_date = $formData["release_date"];
}
// Verify the entry of qualification
if (array_key_exists("qualification", $formData)) {
$qualification = $formData["qualification"];
}
// Verify the entry of video_game_picture
if (array_key_exists("video_game_picture", $formData)) {
$video_game_picture = $formData["video_game_picture"];
}
if (isset($title, $developer, $description, $console, $release_date, $qualification, $video_game_picture)) {
$registerResult = $this->gameService->register($title, $developer, $description, $console, $release_date, $qualification, $video_game_picture);
if (array_key_exists("error", $registerResult)) {
$result["error"] = $registerResult["error"];;
}
$result["message"] = $registerResult["message"];
} else {
$result["error"] = true;
$result["message"] = "No pueden haber datos vacíos.";
}
return $result;
}
}
<file_sep>/server/index.php
<?php
/**
* index.php
* Start the app and provide the backend
*/
require "bootstrap.php";
use Slim\Http\Request;
use Slim\Http\Response;
// Show all the errors
$configuration = [
'settings' => [
'displayErrorDetails' => true,
],
];
$container = new \Slim\Container($configuration);
// Create a new slim instance and show the errors
$app = new \Slim\App($container);
/*********************************** ROUTES ***********************************/
//Register
$app->post(
'/game/register',
function ($request, $response) {
$gameController = new App\Controllers\GameController();
$result = $gameController->register($request);
return $response->withJson($result);
}
);
//Get all
$app->get(
'/games',
function ($request, $response) {
$gameController = new App\Controllers\GameController();
$result = $gameController->getAll($request);
return $response->withJson($result);
}
);
//Get one
$app->get(
'/games/{id}',
function ($request, $response, $args) {
$gameController = new App\Controllers\GameController();
$result = $gameController->getOne($request, $args);
return $response->withJson($result);
}
);
//Delete
$app->delete(
'/games/{id}',
function ($request, $response, $args) {
$gameController = new App\Controllers\GameController();
$result = $gameController->delete($request, $args);
return $response->withJson($result);
}
);
//Update
$app->post(
'/games/{id}',
function ($request, $response, $args) {
$gameController = new App\Controllers\GameController();
$result = $gameController->update($request, $args);
return $response->withJson($result);
}
);
//Run our app
$app->run();
<file_sep>/server/app/src/services/GameService.php
<?php
/**
* EventTypeService.php
*/
namespace App\Services;
class GameService {
private $storage;
/**
* GameService constructor.
*/
public function __construct() {
/* Database verification */
$this->storage = new StorageService();
}
/**
* Update a video game in the system
* @param varchar $title;
* @param varchar $developer;
* @param varchar $description;
* @param varchar $console;
* @param date $release_date;
* @param double $qualification;
* @param varchar $video_game_picture;
* @return array
*/
public function update($id_video_game, $title, $developer, $description, $console, $release_date, $qualification, $video_game_picture) {
$result = [];
// Verify that title has at least one character, no spaces
if (strlen(trim($title)) > 0) {
// Verify that developer has at least one character, no spaces
if (strlen(trim($developer)) > 0) {
// Verify that description has at least one character, no spaces
if (strlen(trim($description)) > 0) {
// Verify that console has at least one character, no spaces
if (strlen(trim($console)) > 0) {
// Verify that release_date has at least one character, no spaces
if (strlen(trim($release_date)) > 0) {
// Verify that qualification has at least one character, no spaces
if (strlen(trim($qualification)) > 0) {
// Verify that qualification is a valid number
if (is_numeric($qualification)) {
// Verify that qualification is a valid number
if ($qualification > 0 && $qualification < 6) {
// Verify that video game picture has at least one character, no spaces
if (strlen(trim($video_game_picture)) > 0) {
// Start the query if everything is ok
// Query to update a video game
$query = "UPDATE video_games SET title = :title, developer = :developer, description = :description, console = :console, release_date = :release_date, qualification = :qualification, video_game_picture = :video_game_picture
WHERE id_video_game = :id_video_game";
// Parameters of queryUpdate
$params = [":id_video_game" => $id_video_game, ":title" => $title, ":developer" => $developer, ":description" => $description, ":console" => $console, ":release_date" => $release_date, ":qualification" => $qualification, ":video_game_picture" => $video_game_picture];
$updateGameResult = $this->storage->query($query, $params);
if ($updateGameResult["data"]["count"] == 1) {
$result["message"] = "Video Juego actualizado exitosamente.";
} else {
$result["error"] = true;
$result["message"] = "Hubo un error o el video juego no existe";
}
} else {
//Video Game picture date is blank
$result["message"] = "La foto del video juego es requerida.";
$result["error"] = true;
}
} else {
//Qualification is not a number between 1 and 5
$result["message"] = "La calificación debe ser un número entre 1 y 5.";
$result["error"] = true;
}
} else {
//Qualification is not numeric
$result["message"] = "La calificación debe ser un número.";
$result["error"] = true;
}
} else {
//Qualification is blank
$result["message"] = "La calificación es requerida.";
$result["error"] = true;
}
} else {
// Releas date is blank
$result["message"] = "La fecha de lanzamiento es requerida.";
$result["error"] = true;
}
} else {
// Console is blank
$result["message"] = "El nombre de la consola es requerido.";
$result["error"] = true;
}
} else {
// Description is blank
$result["message"] = "La descripcion del video juego es requerida.";
$result["error"] = true;
}
} else {
// Developer is blank
$result["message"] = "El desarrollador del video juego es requerido.";
$result["error"] = true;
}
} else {
// Title is blank
$result["message"] = "El titulo del video juego es requerido.";
$result["error"] = true;
}
return $result;
}
/**
* Delete one user by Id
* @param int $id_user
* @return array
*/
public function delete($id_video_game) {
$result = [];
// Verify if the id is numeric
if (is_numeric($id_video_game)) {
// Current query
$query = "DELETE FROM video_games WHERE id_video_game = :id_video_game LIMIT 1";
// Query params
$params = [":id_video_game" => $id_video_game];
$deleteResult = $this->storage->query($query, $params);
// Success
if ($deleteResult["data"]["count"] == 1) {
$result["message"] = "Video Juego eliminado correctamente.";
} else {
$result["error"] = true;
$result["message"] = "Error al borrar el video juego o el juego no existe";
}
} else {
// Invalid id
$result["message"] = "El id es inválido.";
$result["error"] = true;
}
return $result;
}
/**
* Get one video game by Id
* @param int $id_video_game
* @return array
*/
public function getOne($id_video_game) {
$result = [];
// Verify if the id is numeric
if (is_numeric($id_video_game)) {
// Current query
$query = "SELECT id_video_game, title, developer, description, console, release_date, qualification, video_game_picture FROM video_games WHERE id_video_game = :id_video_game LIMIT 1";
// Query params
$params = [":id_video_game" => $id_video_game];
$getOneResult = $this->storage->query($query, $params);
// Success
if (count($getOneResult["data"]) > 0) {
$game = $getOneResult["data"][0];
$result["message"] = "Video juego obtenido satisfactoriamente.";
$result["game"] = $game;
} else {
$result["error"] = true;
$result["message"] = "Este video juego no existe";
}
} else {
// Invalid id
$result["message"] = "El id es inválido.";
$result["error"] = true;
}
return $result;
}
/**
* Get all Video games
* @return array
*/
public function getAll() {
$result = [];
// Current query
$query = "SELECT id_video_game, title, console, release_date FROM video_games";
// Query params
$params = [];
$getAllResult = $this->storage->query($query, $params);
// Success
if (count($getAllResult["data"]) > 0) {
$video_games = $getAllResult["data"];
$result["message"] = "Video Juegos obtenidos satisfactoriamente.";
$result["data"] = $video_games;
} else {
$result["error"] = true;
$result["message"] = "Error en la petición";
}
return $result;
}
/**
* Register a video game in the system
* @param varchar $title;
* @param varchar $developer;
* @param varchar $description;
* @param varchar $console;
* @param date $release_date;
* @param double $qualification;
* @param varchar $video_game_picture;
* @return array
*/
public function register($title, $developer, $description, $console, $release_date, $qualification, $video_game_picture) {
$result = [];
// Verify that title has at least one character, no spaces
if (strlen(trim($title)) > 0) {
// Verify that developer has at least one character, no spaces
if (strlen(trim($developer)) > 0) {
// Verify that description has at least one character, no spaces
if (strlen(trim($description)) > 0) {
// Verify that console has at least one character, no spaces
if (strlen(trim($console)) > 0) {
// Verify that release_date has at least one character, no spaces
if (strlen(trim($release_date)) > 0) {
// Verify that qualification has at least one character, no spaces
if (strlen(trim($qualification)) > 0) {
// Verify that qualification is a valid number
if (is_numeric($qualification)) {
// Verify that qualification is a valid number
if ($qualification > 0 && $qualification < 6) {
// Verify that video game picture has at least one character, no spaces
if (strlen(trim($video_game_picture)) > 0) {
// Start the query if everything is ok
// Query to register a typeEvent
$query = "INSERT INTO video_games (title, developer, description, console, release_date, qualification, video_game_picture)
VALUES(:title, :developer, :description, :console, :release_date, :qualification, :video_game_picture)";
$release_date = date_create()->format('Y-m-d H:i:s');
// Parameters of query
$params = [":title" => $title, ":developer" => $developer, ":description" => $description, ":console" => $console, ":release_date" => $release_date, ":qualification" => $qualification, ":video_game_picture" => $video_game_picture];
$createGameResult = $this->storage->query($query, $params);
if ($createGameResult["data"]["count"] == 1) {
$result["message"] = "El video juego fue creado exitosamente.";
} else {
$result["error"] = true;
$result["message"] = "Hubo un error al crear el video juego, por favor intente de nuevo";
}
} else {
//Video Game picture date is blank
$result["message"] = "La foto del video juego es requerida.";
$result["error"] = true;
}
} else {
//Qualification is not a number between 1 and 5
$result["message"] = "La calificación debe ser un número entre 1 y 5.";
$result["error"] = true;
}
} else {
//Qualification is not numeric
$result["message"] = "La calificación debe ser un número.";
$result["error"] = true;
}
} else {
//Qualification is blank
$result["message"] = "La calificación es requerida.";
$result["error"] = true;
}
} else {
// Releas date is blank
$result["message"] = "La fecha de lanzamiento es requerida.";
$result["error"] = true;
}
} else {
// Console is blank
$result["message"] = "El nombre de la consola es requerido.";
$result["error"] = true;
}
} else {
// Description is blank
$result["message"] = "La descripcion del video juego es requerida.";
$result["error"] = true;
}
} else {
// Developer is blank
$result["message"] = "El desarrollador del video juego es requerido.";
$result["error"] = true;
}
} else {
// Title is blank
$result["message"] = "El titulo del video juego es requerido.";
$result["error"] = true;
}
return $result;
}
}
| d1acea94d7a48af8e7c29f2858f558f05d9523ac | [
"Markdown",
"SQL",
"PHP"
] | 5 | SQL | woxry/test2php | dcfe16ac25490630262de134d60149117c867751 | 146e25aa1bcd6de777c844ad3a2a90bcb16da6e3 |
refs/heads/master | <repo_name>mulargui/healthylinkx-ux-graphql<file_sep>/src/components/providershortlist.js
import React, { Component } from 'react'
import { SELECTED } from '../actions/actiontypes'
import { NewSearch } from '../actions/action'
export class ProvidersShortList extends Component {
constructor(props) {
super(props)
// This bindings are necessary to make `this` work in the callback
this.SearchClick = this.SearchClick.bind(this)
this.storeChanged = this.storeChanged.bind(this)
this.state = {
transaction: 0
, shortlist: []
, visible: false
}
this.props.store.subscribe(this.storeChanged)
}
storeChanged() {
let v = this.props.store.getState()
if(v.state === SELECTED)
this.setState({transaction: v.selected.transaction, shortlist: v.selected.shortlist.slice(), visible:true})
else
this.setState({visible:false})
}
SearchClick() {
this.props.store.dispatch(NewSearch())
}
render(){
if (!this.state.visible) return null
return (
<div className="container">
<legend>Short list of Matching Providers</legend>
<table className="table table-bordered table-striped">
<thead><tr>
<th>NPI</th>
<th>Name</th>
<th>Street</th>
<th>City</th>
<th>Telephone</th>
</tr></thead>
<tbody>
{/* eslint-disable-next-line */}
{this.state.shortlist.map((entry) =>
<tr key={entry.npi}>
<td>{entry.npi}</td>
<td>{entry.fullName}</td>
<td>{entry.fullStreet}</td>
<td>{entry.fullCity}</td>
<td>{entry.telephone}</td>
</tr>
)}
<tr><td>Transaction number: {this.state.transaction} </td></tr>
</tbody>
</table>
<button className="btn btn-link" onClick={this.SearchClick}>
<i className="glyphicon glyphicon-search"></i> New Search</button>
</div>
)
}
}<file_sep>/src/components/providerslist.js
import React, { Component } from 'react'
import { SELECTEDAPI } from '../graphql/constants'
import { LIST } from '../actions/actiontypes'
import { NewSearch, SelectDoctors, ErrorMessage } from '../actions/action'
export class ProvidersList extends Component {
constructor(props) {
super(props)
// This bindings are necessary to make `this` work in the callback
this.SelectClick = this.SelectClick.bind(this)
this.SearchClick = this.SearchClick.bind(this)
this.checkBoxChanged = this.checkBoxChanged.bind(this)
this.storeChanged = this.storeChanged.bind(this)
//most of the state is kept in the controls of the form
this.state = { doctorslist: []
, visible: false
, options: []
}
this.props.store.subscribe(this.storeChanged)
}
storeChanged() {
let v = this.props.store.getState()
if(v.state === LIST)
this.setState({doctorslist: v.doctorslist.slice(), options: [], visible:true})
else
this.setState({visible:false})
}
SelectClick() {
const options = this.state.options
//no doctor selected
if(options.length === 0) {
this.props.store.dispatch(ErrorMessage('Please select up to three doctors'))
return
}
//no more than 3 doctors selected
if(options.length > 3) {
this.props.store.dispatch(ErrorMessage('You cannot select more than 3 doctors'))
return
}
//get the list of npis selected
var npis = []
options.map(function(entry, index) {
npis.push(entry.toString());
})
//lets call the api, collect the data and dispath the result to the store
let store = this.props.store
return this.props.client.mutate({mutation: SELECTEDAPI, variables: {npi: npis}})
.then(function(response) {
return response.data.BookProviders
})
.then(function(response) {
if (response.length === 0)
throw new Error("No matching providers were found.")
return store.dispatch(SelectDoctors(response))
})
.catch(function(error) {
store.dispatch(ErrorMessage(error.message))
})
}
SearchClick() {
this.props.store.dispatch(NewSearch())
}
checkBoxChanged(e) {
// current array of options
const options = this.state.options
let index
// check if the check box is checked or unchecked
if (e.target.checked) {
// add the numerical value of the checkbox to options array
options.push(+e.target.value)
} else {
// or remove the value from the unchecked checkbox from the array
index = options.indexOf(+e.target.value)
options.splice(index, 1)
}
// update the state with the new array of options
this.setState({ options: options })
}
render(){
if (!this.state.visible) return null
return (
<div className="container">
<legend>List of Matching Providers</legend>
<table className="table table-bordered table-striped">
<thead><tr>
<th> </th>
<th>Name</th>
<th>Street</th>
<th>City</th>
</tr></thead>
<tbody>
{this.state.doctorslist.map((entry) =>
<tr key={entry.npi}>
<td><input type="checkbox" value={entry.npi} onChange={this.checkBoxChanged}></input></td>
<td>{entry.fullName}</td>
<td>{entry.fullStreet}</td>
<td>{entry.fullCity}</td>
</tr>
)}
</tbody>
</table>
<button className="btn btn-link" onClick={this.SelectClick}>
<i className="glyphicon glyphicon-list-alt"></i> Select Providers</button>
<button className="btn btn-link" onClick={this.SearchClick}>
<i className="glyphicon glyphicon-search"></i> New Search</button>
</div>
)
}
}
<file_sep>/src/containers/store.js
import { createStore } from 'redux'
import { myreducer } from '../reducers/reducer'
export function configureStore() {
return createStore(myreducer)
}
<file_sep>/src/reducers/reducer.js
import { UNIVERSE, LIST, SELECTED, SEARCH, SELECT, SPECIALITIES, ERRORMESSAGE, NEWSEARCH } from '../actions/actiontypes'
const initialState = {
state: UNIVERSE
, search: {
specialty: ''
, lastname: ''
, gender: ''
, zipcode: ''
, distance: ''
}
, specialities: []
, doctorslist: []
, selected: {
transaction: 0
, shortlist: []
}
, errorMessage: ''
}
export function myreducer(state = initialState, action) {
switch(action.type){
case SEARCH:
return Object.assign({}, state, {
state: LIST
, search: action.search
, doctorslist: action.doctorslist.slice()
, errorMessage: ''
})
case SPECIALITIES:
return Object.assign({}, state, {
specialities: action.specialities.slice()
, errorMessage: ''
})
case ERRORMESSAGE:
return Object.assign({}, state, {
errorMessage: action.errorMessage
})
case NEWSEARCH:
return Object.assign({}, state, {
state: UNIVERSE
, errorMessage: ''
})
case SELECT:
return Object.assign({}, state, {
state: SELECTED
, selected: {
transaction: action.selected.id
, shortlist: action.selected.providers.slice()
}
, errorMessage: ''
})
default:
return state
}
}
<file_sep>/docker/container.sh
#!/usr/bin/env bash
set -x
export DEBIAN_FRONTEND=noninteractive
# Absolute path to this repo
SCRIPT=$(readlink -f "$0")
export REPOPATH=$(dirname "$SCRIPT")/..
# what you can do
CLEANUP=N
BUILD=N
# you can also set the flags using the command line
for var in "$@"
do
if [ "CLEANUP" == "$var" ]; then CLEANUP=Y
fi
if [ "BUILD" == "$var" ]; then BUILD=Y
fi
done
# clean up all images
if [ "${CLEANUP}" == "Y" ]; then
sudo docker rmi -f react
fi
# create image
if [ "${BUILD}" == "Y" ]; then
# this is a hack
# docker can only copy files in the container from the docker folder
cp -r $REPOPATH/public $REPOPATH/docker
cp -r $REPOPATH/fonts $REPOPATH/docker
cp -r $REPOPATH/src $REPOPATH/docker
sudo docker build --rm=true -t react $REPOPATH/docker
# now we do the cleanup
rm -r $REPOPATH/docker/public
rm -r $REPOPATH/docker/fonts
rm -r $REPOPATH/docker/src
fi
<file_sep>/src/components/search.js
import React, { Component } from 'react'
import AsyncSelect from 'react-select/lib/Async';
import { TAXONOMYAPI, PROVIDERSAPI } from '../graphql/constants'
import { UNIVERSE } from '../actions/actiontypes'
import { SearchDoctors, ErrorMessage } from '../actions/action'
export class Search extends Component {
constructor(props) {
super(props)
// This bindings are necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this)
this.loadSpecialities = this.loadSpecialities.bind(this)
this.storeChanged = this.storeChanged.bind(this)
//most of the state is kept in the controls of the form
this.state = {specialty : '', visible: true}
this.props.store.subscribe(this.storeChanged)
}
storeChanged() {
//the state is kept in the controls of the form, nothing to do
//this.setState(store.getState())
let v = this.props.store.getState()
if(v.state === UNIVERSE) this.setState({visible: true})
else this.setState({visible: false})
}
loadSpecialities(input) {
let store = this.props.store
return this.props.client.query({query: TAXONOMYAPI})
.then(function(response) {
return response.data.SpecialityList
})
.then(function(response) {
if (!response.length === 0)
throw new Error("No taxonomies!")
var taxonomyTags = []
response.forEach(function(entry) {
taxonomyTags.push({ value: entry.name, label: entry.name })
})
return taxonomyTags
})
.catch(function(error) {
store.dispatch(ErrorMessage(error.message))
})
}
handleClick() {
//lets call the api, collect the data and dispath the result to the store
let store = this.props.store
let specialty = this.state.specialty.value
let gender = this.gender.value
let zipcode = this.zipcode.value
let distance = this.distance.value
var lastname = this.lastname.value.trim().split(/ +/)
// no speciality selected
if (typeof this.state.specialty.value === "undefined")
specialty=""
//no lastname
if (lastname[0] === "")
lastname = []
return this.props.client.query({query: PROVIDERSAPI, variables: {distance: parseInt(distance), postalCode: zipcode,
gender: gender, classification: specialty, lastName: lastname}})
.then(function(response) {
return response.data.SearchProviders
})
.then(function(response) {
if (response.length === 0)
throw new Error("No matching providers were found.")
return store.dispatch(SearchDoctors( specialty, lastname, gender, zipcode, distance, response))
})
.catch(function(error) {
store.dispatch(ErrorMessage(error.message))
})
}
render(){
if (!this.state.visible) return null
return (
<div className="container">
<legend>Providers Search</legend>
<div className="row">
<AsyncSelect
name="form-field-name"
onChange={value => this.setState({specialty:value})}
value={this.state.specialty}
defaultOptions
cacheOptions
isSearchable
loadOptions={this.loadSpecialities}
placeholder="Type a Medical Specialty"
/>
<p></p>
</div>
<div className="row">
<input type="text" className="form-control" ref={(e) => this.lastname = e} placeholder="<NAME>" maxLength="30" pattern="\w+"></input>
<p></p>
</div>
<div className="row">
<select className="form-control" ref={(e) => this.gender = e}>
<option value="">No gender preference</option>
<option value="F">Female only</option>
<option value="M">Male only</option>
</select>
<p></p>
</div>
<div className="row">
<input type="text" className="form-control" ref={(e) => this.zipcode = e} placeholder="Zip Code" autoComplete="off" maxLength="5" pattern="\d{5}"></input>
<p></p>
</div>
<div className="row">
<select className="form-control" ref={(e) => this.distance = e}>
<option value="5">Within 5 miles</option>
<option value="10">Within 10 miles</option>
<option value="25">Within 25 miles</option>
</select>
<p></p>
</div>
<div className="row">
<button className="btn btn-link" onClick={this.handleClick}>
<i className="glyphicon glyphicon-search"></i> Search</button>
</div>
</div>
)
}
}<file_sep>/docker/Dockerfile
FROM node:8.15-alpine
RUN yarn create react-app theapp
RUN cd /theapp \
&& yarn add \
bootstrap@3 \
react-bootstrap \
redux \
react-fontawesome \
react-select \
# react-redux
graphql \
apollo-boost \
react-apollo
COPY public/ /theapp/public/
COPY fonts /theapp/src/fonts
COPY src/ /theapp/src/
EXPOSE 3000
# By default, simply start the app
CMD cd /theapp && yarn start
<file_sep>/src/graphql/constants.js
import {gql} from 'apollo-boost'
// minikube ip
const URL = window.location.hostname
// healthylinkx-api-service port
const PORT = '30100'
export const ENDPOINT = 'http://' + URL + ':' + PORT + '/graphql'
export const TAXONOMYAPI = gql `{SpecialityList {name}}`;
export const PROVIDERSAPI = gql ` query searchproviders(
$distance: Int,
$postalCode: String,
$gender: String,
$classification: String,
$lastName: [String]
){
SearchProviders(
lastName: $lastName,
postalCode: $postalCode,
distance: $distance,
gender: $gender,
classification: $classification
){
npi,
fullName,
fullStreet,
fullCity
}
}
`;
export const SELECTEDAPI = gql ` mutation bookproviders(
$npi: [String!]!
){
BookProviders(
npi: $npi
){
id,
providers{
npi,
fullName,
fullStreet,
fullCity,
telephone
}
}
}
`;
<file_sep>/src/components/messagesbox.js
import React, { Component } from 'react'
export class Messages extends Component {
constructor(props) {
super(props)
// This bindings are necessary to make `this` work in the callback
this.storeChanged = this.storeChanged.bind(this)
//state of the controls in the div
this.state = { message: '', visible: false}
this.props.store.subscribe(this.storeChanged)
}
storeChanged() {
let v = this.props.store.getState()
if(v.errorMessage === '') this.setState({message: '', visible: false})
else this.setState({message: v.errorMessage, visible:true})
}
render(){
if (!this.state.visible) return null
return (
<div className="container">
<p></p>
<div className="alert alert-danger">
<span>{this.state.message}</span>
</div>
</div>
)
}
}
<file_sep>/src/actions/actiontypes.js
//states
export const UNIVERSE = 'UNIVERSE'
export const LIST = 'LIST'
export const SELECTED = 'SELECTED'
//actions
export const ERRORMESSAGE = 'ERROR'
export const SEARCH = 'SEARCH'
export const NEWSEARCH = 'NEWSEARCH'
export const SELECT = 'SELECT'
export const SPECIALITIES = 'SPECIALITIES'
| 8263c5262a0d09a4806ea964678881e4fb8b2975 | [
"JavaScript",
"Dockerfile",
"Shell"
] | 10 | JavaScript | mulargui/healthylinkx-ux-graphql | 63c0a20ad1ad2c0bc2f513a762d25b498772e2b0 | ca760127f27391dc4e69f162d5c01f64cb21d24d |
refs/heads/master | <file_sep>require 'pry'
class String
def sentence?
if self.end_with?(".")
true
else
false
end
end
def question?
if self.end_with?("?")
true
else
false
end
end
def exclamation?
if self.end_with?("!")
true
else
false
end
end
def count_sentences
self.split(/[.?!]/).reject {|n| n.empty? || n == ","}.length
end
end | 07d43be722760e83e92e2e859c9a6b05f3ca549e | [
"Ruby"
] | 1 | Ruby | Gamoundo/ruby-oo-self-count-sentences-lab-nyc04-seng-ft-041920 | 148cc0948879a1b8b283fa7dd8b55e3c6ced935e | 9e53238c60305263464180dfe06ba2ba11b69396 |
refs/heads/master | <repo_name>leoslamas/ios-courses-swift<file_sep>/Snapchat/Tinder/UserViewController.swift
//
// UserViewController.swift
// Tinder
//
// Created by <NAME> on 20/10/2014.
// Copyright (c) 2014 Appfish. All rights reserved.
//
import UIKit
class UserViewController: UITableViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var userArray: [String] = []
var activeRecipient = 0
var timer = NSTimer()
// Update - removed ! after UIImagePickerController
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
println("Image selected")
self.dismissViewControllerAnimated(true, completion: nil)
// Upload to Parse
var imageToSend = PFObject(className:"image")
imageToSend["photo"] = PFFile(name: "image.jpg", data: UIImageJPEGRepresentation(image, 0.5))
imageToSend["senderUsername"] = PFUser.currentUser().username
imageToSend["recipientUsername"] = userArray[activeRecipient]
imageToSend.save()
}
@IBAction func pickImage(sender: AnyObject) {
var image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
var query = PFUser.query()
query.whereKey("username", notEqualTo: PFUser.currentUser().username)
var users = query.findObjects()
for user in users {
userArray.append(user.username)
tableView.reloadData()
}
timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("checkForMessage"), userInfo: nil, repeats: true)
}
func checkForMessage() {
println("checking for message...")
var query = PFQuery(className: "image")
query.whereKey("recipientUsername", equalTo: PFUser.currentUser().username)
var images = query.findObjects()
var done = false
for image in images {
if done == false {
var imageView:PFImageView = PFImageView()
// Update - replaced as with as!
imageView.file = image["photo"] as! PFFile
imageView.loadInBackground({ (photo, error) -> Void in
if error == nil {
var senderUsername = ""
if image["senderUsername"] != nil {
// Update - replaced as NSString with as! String
senderUsername = image["senderUsername"]! as! String
} else {
senderUsername = "unknown user"
}
var alert = UIAlertController(title: "You have a message", message: "Message from \(senderUsername)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
(action) -> Void in
var backgroundView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
backgroundView.backgroundColor = UIColor.blackColor()
backgroundView.alpha = 0.8
backgroundView.tag = 3
self.view.addSubview(backgroundView)
var displayedImage = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
displayedImage.image = photo
displayedImage.tag = 3
displayedImage.contentMode = UIViewContentMode.ScaleAspectFit
self.view.addSubview(displayedImage)
image.delete()
self.timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("hideMessage"), userInfo: nil, repeats: false)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
})
done = true
}
}
}
func hideMessage() {
for subview in self.view.subviews {
if subview.tag == 3 {
subview.removeFromSuperview()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return userArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Update - replaced as with as!
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = userArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
activeRecipient = indexPath.row
pickImage(self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "logout" {
PFUser.logOut()
}
}
}
<file_sep>/SwiftApp/SwiftApp/ViewController.swift
//
// ViewController.swift
// SwiftApp
//
// Created by <NAME> on 22/03/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var myTableView: UITableView!
private var testeArray = ["Olar", "Caxoro", "Rato", "Papagaio", "Mula"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTableView.dataSource = self
self.myTableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.testeArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var myCell = UITableViewCell()
myCell.textLabel?.text = testeArray[indexPath.row]
return myCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("DetailsSegue", sender: self.testeArray[indexPath.row])
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var detailViewController = segue.destinationViewController as DetailViewController
detailViewController.testeName = (sender as String)
}
}
<file_sep>/README.md
# ios-courses-swift
iOS-Swift courses.
<file_sep>/Swift-Flappy-master/README.md
##SwiftFlappy
A step-by-step commit on creating a Flappy Birds clone in Swift in 17 easy steps!
Step #1 - [Initial Clean Project with Assets](https://github.com/ReyHaynes/SwiftFlappy/commit/499262a)
Step #2 - [Adding Flappy Bird to the Scene](https://github.com/ReyHaynes/SwiftFlappy/commit/dd891c0)
Step #3 - [Make It Flap](https://github.com/ReyHaynes/SwiftFlappy/commit/10442ee)
Step #4 - [Color The Sky](https://github.com/ReyHaynes/SwiftFlappy/commit/f69c87d)
Step #5 - [Loop the Ground](https://github.com/ReyHaynes/SwiftFlappy/commit/646622f)
Step #6 - [Add some Skyline](https://github.com/ReyHaynes/SwiftFlappy/commit/598b5aa)
Step #7 - [Kill the Status Bar!](https://github.com/ReyHaynes/SwiftFlappy/commit/acd8816)
Step #8 - [Make the ground move.](https://github.com/ReyHaynes/SwiftFlappy/commit/20017a4)
Step #9 - [Make the skyline move...but with some depth.](https://github.com/ReyHaynes/SwiftFlappy/commit/f17908b)
Step #10 - [Add some physics to Flappy and alter gravity](https://github.com/ReyHaynes/SwiftFlappy/commit/6a6d0dc)
Step #11 - [Add touch and rotation physics](https://github.com/ReyHaynes/SwiftFlappy/commit/3f7ca68)
Step #12 - [Adding first enemy pipe!](https://github.com/ReyHaynes/SwiftFlappy/commit/a8142b7) (See Bug fix #1)
Step #13 - [Spawning enemy pipes infinitely!](https://github.com/ReyHaynes/SwiftFlappy/commit/a629b3a)
Step #14 - [Collison Detection](https://github.com/ReyHaynes/SwiftFlappy/commit/bed00e4)
Step #15 - [Reset Game after collision](https://github.com/ReyHaynes/SwiftFlappy/commit/dab06ed)
Step #16 - [Kill the bird](https://github.com/ReyHaynes/SwiftFlappy/commit/0d30e6b)
Step #17 - [Scoring](https://github.com/ReyHaynes/SwiftFlappy/commit/d27638a)
Bug Fix #1 - [XCode 6 Beta 4 fix. CGFloat Conversion.](https://github.com/ReyHaynes/SwiftFlappy/commit/0ef055e)
Play around with everything. Don't forget to Option+Click anything in xcode you don't understand!
Enjoy!!
<file_sep>/Segues Example/Segues Example/ScrollViewController.swift
//
// ScrollViewController.swift
// Segues Example
//
// Created by <NAME> on 02/04/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class ScrollViewController: UIViewController {
@IBOutlet weak var scrollview: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
scrollview.contentSize = CGSizeMake(200, 200)
}
}
<file_sep>/Where Am I/Where Am I/ViewController.swift
//
// ViewController.swift
// Where Am I
//
// Created by <NAME> on 26/03/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var manager:CLLocationManager!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var courseLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var altitudeLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println(locations)
var userLocation: CLLocation = locations[0] as CLLocation
latitudeLabel.text = "\(userLocation.coordinate.latitude)"
longitudeLabel.text = "\(userLocation.coordinate.longitude)"
courseLabel.text = "\(userLocation.course)"
speedLabel.text = "\(userLocation.speed)"
altitudeLabel.text = "\(userLocation.altitude)"
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {
(placemarks, error) -> Void in
if error != nil {
println(error)
}else{
if let p = CLPlacemark(placemark: placemarks?[0] as CLPlacemark!) {
println(p)
self.addressLabel.text = "\(p.subAdministrativeArea) \(p.postalCode) \(p.country)"
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/Audio/Audio/ViewController.swift
//
// ViewController.swift
// Audio
//
// Created by <NAME> on 27/03/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var player : AVAudioPlayer = AVAudioPlayer()
@IBOutlet weak var volume: UISlider!
@IBAction func play(sender: AnyObject) {
player.play()
}
@IBAction func pause(sender: AnyObject) {
player.pause()
}
@IBAction func stop(sender: AnyObject) {
player.stop()
player.currentTime = 0
}
@IBAction func volumeChanged(sender: AnyObject) {
player.volume = volume.value
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
println(error)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var audioPath = NSBundle.mainBundle().pathForResource("theme", ofType: "mp3")!
var error : NSError? = nil
player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath), error: &error)
player.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/Parse Demo/Parse Demo/ViewController.swift
//
// ViewController.swift
// Parse Demo
//
// Created by <NAME> on 30/03/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var testObject:PFObject = PFObject(className: "TestObject")
testObject["foo"] = "bar"
testObject.saveInBackgroundWithBlock { (ok, error) -> Void in
if ok {
println("ok!")
} else {
println(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| e44eb1e08d5abe59e8e7ca14319c81bf3f21e376 | [
"Swift",
"Markdown"
] | 8 | Swift | leoslamas/ios-courses-swift | ee9f123b85c328cf4bfc961a7715d4b7b5ff96fe | 98c12bd6061429f31ca653b5cfe55010c247550d |
refs/heads/master | <file_sep>var template = require('./templates/param.hbs')
var BSON = require('./lib/bson')
var cssAnimEventTypes = require('./lib/anim-events')
xtag.register('compose-shell-param', {
lifecycle: {
created: function(){
this.params = xtag.queryChildren(this, 'compose-shell-param')
this.group = !!this.params.length
this.innerHTML = template({
before: this.getAttribute('before'),
group: this.group,
editable: this.editable,
value: this.parseValue(this.getAttribute('value')),
type: this.type,
content: this.textContent,
after: this.getAttribute('after'),
placeholder: this.placeholder
})
this.hide()
if (this.params.length > 0) {
var groupEl = this.querySelector('.params-group')
for (var param in this.params) {
this.params[param].shell = this.shell
this.params[param].addEventListener('show', this.updateVisibility.bind(this))
this.params[param].addEventListener('hide', this.updateVisibility.bind(this))
groupEl.appendChild(this.params[param])
// this.updateVisibility()
}
}
// this.params = xtag.queryChildren(this, 'compose-shell-param')
if (this.type)
this.shell.registerParam(this)
if (this.type === 'text' || (this.getAttribute('value') || this.required))
this.visible = true
}
},
events: {
'focus:delegate(span[contenteditable])': function(event) {
var param = event.currentTarget
if (param.group) return
if (param.placeholder) {
if (this.textContent === param.placeholder && /placeholder/.test(this.className))
this.textContent = ''
}
},
'blur:delegate(span[contenteditable])': function(event) {
var param = event.currentTarget
if (param.group) return
if (param.placeholder)
if (this.textContent === '') {
this.textContent = param.placeholder
if (!/placeholder/.test(this.className))
this.className += ' placeholder'
} else {
this.className = this.className.replace('placeholder', '')
}
},
show: function(event){
if (this.customInput)
this.customInput.focus()
if (this.hint)
this.showHint()
}
},
accessors: {
// params: { get: function(){ return xtag.queryChildren(this, 'compose-shell-param') } },
name: { get: function(){ return this.getAttribute('name') } },
type: { get: function(){ return this.getAttribute('type') } },
placeholder: { get: function(){ return this.getAttribute('placeholder') } },
hint: { get: function(){ return this.getAttribute('hint') } },
required: { get: function(){ return this.getAttribute('required') } },
// group: { get: function() { return this.params.length > 0 } },
editable: { get: function() { return !this.group && this.type && this.type !== 'boolean' } },
optional: { get: function(){ return !!this.getAttribute('optional') } },
dependency: { get: function(){ return this.getAttribute('dependency') } },
customInput: { get: function() { return this.querySelector('span[contenteditable]') } },
parser: { get: function() { return this.getAttribute('parser') } },
visible: {
get: function(){ return !this.getAttribute('hidden') },
set: function(visible){
if (visible === true) {
this.removeAttribute('hidden')
xtag.fireEvent(this, 'show')
} else if (visible === false) {
this.setAttribute('hidden', true)
xtag.fireEvent(this, 'hide')
}
}
},
value: {
get: function(){
var val;
if (!this.visible)
return null // no value
if (this.type === 'boolean') {
val = 1
} else if (this.customInput) {
// ensure stuff by blurring.
this.customInput.blur()
val = this.customInput.textContent
if (this.placeholder) {
if (/placeholder/.test(this.customInput.className) && val === this.placeholder)
val = ""
}
if (val && this.type === 'hash')
val = '{' + val + '}'
}
return this.serializeValue(val)
}
}
},
methods: {
registerParam: function(param){
// Pass through
this.shell.registerParam(param)
},
toggle: function(){ this.visible = !this.visible },
show: function(){ this.visible = true },
hide: function(){ this.visible = false },
updateVisibility: function(){
this.visible = [].some.call(this.params, function(child){ return child.visible })
},
showHint: function(){
var hintEl = this.querySelector('.hint')
if (hintEl)
this.removeChild(hintEl)
hintEl = document.createElement('span')
hintEl.className = 'hint'
hintEl.textContent = this.hint
clearTimeout(this.hintTimeout)
this.appendChild(hintEl)
this.hintTimeout = setTimeout(function(){
hintEl.className += ' out'
hintEl.addEventListener(cssAnimEventTypes.end, function animEnd(event){
this.removeChild(hintEl)
hintEl.removeEventListener(cssAnimEventTypes.end, animEnd)
}.bind(this), false)
}.bind(this), 2000)
},
serializeValue: function(value){
if (!this.parser)
return value
if (this.parser === 'bson') {
try {
return JSON.stringify(BSON.bsonEval(value))
} catch (error) {
console.log(error)
xtag.fireEvent(this, 'error', {detail: {error: new Error('Unparsable value for ' + this.name)}})
}
}
},
parseValue: function(value){
if (!this.parser)
return value
if (this.parser === 'bson' && value) {
try {
return stripWrapper(BSON.toBsonString(JSON.parse(value), {indentation: 0}))
} catch (error) {
console.log(error)
return value
}
}
}
}
})
function stripWrapper(queryString) {
var matches = queryString.match(/\{(.+)\}/)
if (matches)
return matches[1]
} | 152e9cb23acc2ab04fa8aad6a692eef777e3572d | [
"JavaScript"
] | 1 | JavaScript | codepope/shell | 72f0af2dfb624d33b3e309845ca1b242a25cd910 | 5f5339e161f4abb184f936c7c5836d44fbdf98e5 |
refs/heads/master | <repo_name>rmiller02/LeapYear<file_sep>/LeapYearTest.java
package LeapYear;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class LeapYearTest {
@Test
public void returnsBooleanIfLeapYear() {
LeapYear leapYear = new LeapYear();
assertEquals(true, leapYear.leapYear(1996));
assertEquals(false, leapYear.leapYear(2001));
assertEquals(true, leapYear.leapYear(2000));
assertEquals(false, leapYear.leapYear(1900));
}
} | 60d465bed46e4337e503a5eb7cda278604295cc8 | [
"Java"
] | 1 | Java | rmiller02/LeapYear | 5ae6ce8ff622ef6b14becdbc994e8dbf3aed32be | 1f8556e05ff9021f45c2313bc20d080f5bedd265 |
refs/heads/master | <repo_name>tata8k/squidb<file_sep>/squidb-tests/src/com/yahoo/squidb/test/TestDatabase.java
/*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache 2.0 License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.squidb.test;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yahoo.squidb.data.AbstractDatabase;
import com.yahoo.squidb.sql.AttachDetachTest;
import com.yahoo.squidb.sql.Index;
import com.yahoo.squidb.sql.Table;
import com.yahoo.squidb.sql.View;
public class TestDatabase extends AbstractDatabase {
public boolean caughtCustomMigrationException;
private static final Index INDEX_TESTMODELS_LUCKYNUMBER = TestModel.TABLE
.index("index_testmodels_luckynumber", TestModel.LUCKY_NUMBER);
public TestDatabase(Context context) {
super(context);
}
@Override
protected String getName() {
return "testDb";
}
@Override
protected Table[] getTables() {
return new Table[]{
TestModel.TABLE,
Thing.TABLE,
Employee.TABLE,
TriggerTester.TABLE,
BasicData.TABLE,
TestVirtualModel.TABLE
};
}
@Override
protected Index[] getIndexes() {
return new Index[]{INDEX_TESTMODELS_LUCKYNUMBER};
}
@Override
protected View[] getViews() {
return new View[]{
TestViewModel.VIEW
};
}
@Override
protected int getVersion() {
return 1;
}
@Override
protected void onTablesCreated(SQLiteDatabase db) {
super.onTablesCreated(db);
}
@Override
protected boolean onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
return true;
}
@Override
protected void onConfigure(SQLiteDatabase db) {
/** @see AttachDetachTest#testAttacherInTransactionOnAnotherThread() */
db.enableWriteAheadLogging();
}
@Override
protected boolean onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new CustomMigrationException(getName(), oldVersion, newVersion);
}
@Override
protected void onMigrationFailed(MigrationFailedException failure) {
if (failure instanceof CustomMigrationException) {
// suppress
caughtCustomMigrationException = true;
}
}
private static class CustomMigrationException extends MigrationFailedException {
public CustomMigrationException(String dbName, int oldVersion, int newVersion) {
super(dbName, oldVersion, newVersion);
}
}
}
<file_sep>/squidb/src/com/yahoo/squidb/sql/Validatable.java
/*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache 2.0 License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.squidb.sql;
import java.util.List;
/**
* An extension of compilable that lets us pass a boolean flag to signal that extra validation is needed. This
* is useful when compiling queries that need validation to guard against malicious arguments.
*/
abstract class Validatable extends CompilableWithArguments {
@Override
final void appendCompiledStringWithArguments(StringBuilder sql, List<Object> selectionArgsBuilder) {
appendCompiledStringWithArguments(sql, selectionArgsBuilder, false);
}
abstract void appendCompiledStringWithArguments(StringBuilder sql, List<Object> selectionArgsBuilder,
boolean withValidation);
}
<file_sep>/squidb-tests/src/com/yahoo/squidb/data/PropertyTest.java
/*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache 2.0 License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.squidb.data;
import com.yahoo.squidb.sql.Property.LongProperty;
import com.yahoo.squidb.sql.Query;
import com.yahoo.squidb.test.SquidTestCase;
import com.yahoo.squidb.test.TestModel;
import com.yahoo.squidb.test.TestViewModel;
import com.yahoo.squidb.test.TestVirtualModel;
import com.yahoo.squidb.test.Thing;
public class PropertyTest extends SquidTestCase {
public void testPropertyAliasing() {
LongProperty p = TestModel.ID;
assertEquals(p.getQualifiedExpression(), "testModels._id");
assertEquals(p.getExpression(), "_id");
assertEquals(p.getName(), "_id");
LongProperty basicAlias = p.as("newAlias");
assertEquals(p.table, basicAlias.table);
assertEquals(p.getExpression(), basicAlias.getExpression());
assertEquals("newAlias", basicAlias.getName());
assertEquals("SELECT testModels._id AS newAlias", Query.select(basicAlias).toString());
LongProperty aliasWithTable = p.as("newTable", "newAlias");
assertEquals("newTable", aliasWithTable.table.getName());
assertEquals(p.getExpression(), aliasWithTable.getExpression());
assertEquals("newAlias", aliasWithTable.getName());
assertEquals("SELECT newTable._id AS newAlias", Query.select(aliasWithTable).toString());
LongProperty asSelectionFromTable = basicAlias.asSelectionFromTable(TestViewModel.VIEW, "superAlias");
assertEquals(TestViewModel.VIEW.getName(), asSelectionFromTable.table.getName());
assertEquals(basicAlias.getName(), asSelectionFromTable.getExpression());
assertEquals("superAlias", asSelectionFromTable.getName());
assertEquals("SELECT testView.newAlias AS superAlias", Query.select(asSelectionFromTable).toString());
assertEquals(TestVirtualModel.ID.getQualifiedExpression(), "virtual_models.rowid");
assertEquals(TestVirtualModel.ID.getExpression(), "rowid");
assertEquals(TestVirtualModel.ID.getName(), "rowid");
assertEquals(Thing.ID.getQualifiedExpression(), "things.id");
assertEquals(Thing.ID.getExpression(), "id");
assertEquals(Thing.ID.getName(), "id");
}
}
| 0c5af3ddd62e2e431f56a193cc86710532d39d2f | [
"Java"
] | 3 | Java | tata8k/squidb | 60812d852d1ccca0a1868b921b9544d0db436105 | 542d3fd0db88b5418ce77de37f07256f22d3446e |
refs/heads/master | <repo_name>Ryddan/Games<file_sep>/BolinhaVermelha/teste.cpp
#define ALLEGRO_STATICLINK //sempre linkar isso
/*#include <stdio.h>
#include <allegro5/allegro.h> //biblioteca allegro
// Nossa conhecida função main...
int main()
{
// Variável representando a janela principal
ALLEGRO_DISPLAY *janela = NULL;
// Inicializamos a biblioteca
al_init();
// Criamos a nossa janela - dimensões de 640x480 px
janela = al_create_display(640, 480);
// Preenchemos a janela de branco
al_clear_to_color(al_map_rgb(255, 255, 255));
// Atualiza a tela
al_flip_display();
// Segura a execução por 10 segundos
al_rest(10.0);
// Finaliza a janela
al_destroy_display(janela);
return 0;
} */
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#include <stdio.h>
#include <stdbool.h>
const int LARGURA_TELA = 640;
const int ALTURA_TELA = 480;
ALLEGRO_DISPLAY *janela = NULL;
ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;
bool inicializar();
int main(void)
{
bool sair = false;
if (!inicializar())
{
return -1;
}
float raio = 30.0;
float x = raio;
float y = raio;
int dir_x = 1, dir_y = 1;
while (!sair)
{
if (!al_is_event_queue_empty(fila_eventos))
{
ALLEGRO_EVENT evento;
al_wait_for_event(fila_eventos, &evento);
if (evento.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
{
sair = true;
}
}
al_draw_filled_circle(x, y, raio, al_map_rgb(255, 0, 0));
al_flip_display();
al_clear_to_color(al_map_rgb(0, 0, 0));
x += 4.0 * dir_x;
y += 4.0 * dir_y;
if (x >= LARGURA_TELA - raio)
{
dir_x = -1;
x = LARGURA_TELA - raio;
} else if (x <= raio) {
dir_x = 1;
x = raio;
}
if (y >= ALTURA_TELA - raio)
{
dir_y = -1;
y = ALTURA_TELA - raio;
} else if (y <= raio) {
dir_y = 1;
y = raio;
}
al_rest(0.005);
}
al_destroy_event_queue(fila_eventos);
al_destroy_display(janela);
return 0;
}
bool inicializar()
{
if (!al_init())
{
fprintf(stderr, "Falha ao inicializar Allegro.\n");
return false;
}
if (!al_init_primitives_addon())
{
fprintf(stderr, "Falha ao inicializar add-on allegro_primitives.\n");
return false;
}
janela = al_create_display(LARGURA_TELA, ALTURA_TELA);
if (!janela)
{
fprintf(stderr, "Falha ao criar janela.\n");
return false;
}
al_set_window_title(janela, "Animando!!!");
fila_eventos = al_create_event_queue();
if (!fila_eventos)
{
fprintf(stderr, "Falha ao criar fila de eventos.\n");
al_destroy_display(janela);
return false;
}
al_register_event_source(fila_eventos, al_get_display_event_source(janela));
return true;
}
<file_sep>/Squareinvasion/Assets/Scripts/ScriptTelas/MainMenuScript.cs
using UnityEngine;
using System.Collections;
public class MainMenuScript : MonoBehaviour {
//coloca uma mensagem na tela de menu
private string instructionText = "Instrução:\nPressione seta esquerda e direita(ou as letras A e D) para mover paras os lados\nPressione a tecla espaço para atirar!";
//adciona a variavel de um botão e seu tamanho
//private int buttonWitdh = 200;
//private int buttonHeight = 50;
//cria variavel pra textura
public Texture backgroundTexture;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void OnGUI()
{
/*GUI.Label (new Rect (10, 10, 200, 200), instructionText);
//cria o botão e caso aperte, carrega a fase
if (GUI.Button (new Rect (Screen.width / 2 - buttonWitdh / 2, Screen.height / 2 - buttonHeight / 2, buttonWitdh, buttonHeight), "Comece o jogo"))
{
Application.LoadLevel (1);
}
*/
//joga a textura na tela e pede pra aperta um botão
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), backgroundTexture);
GUI.Label (new Rect (10, 10, 200, 200), instructionText);
if(Input.anyKeyDown)
{
Application.LoadLevel (1);
}
}
}
<file_sep>/Squareinvasion/Assets/Scripts/EnemyScript.cs
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour {
//velocidade do quadrado assassino
public float minSpeed;
public float maxSpeed;
private float currentSpeed;
private float x, y, z;
//variaveis para mudar o tamanho do inimigo
private float MinRotateSpeed = 60f;
private float MaxRotateSpeed = 100f;
private float MinScale = .6f;
private float MaxScale = 2f;
//velocidade de rotação
private float currentRotateSpeed;
private float currentScaleX;
private float currentScaleY;
private float currentScaleZ;
// Use this for initialization
void Start ()
{
SetPositionAndSpeed ();
}
// Update is called once per frame
void Update ()
{
//rotação do inimigo
float rotationSpeed = currentRotateSpeed * Time.deltaTime;
transform.Rotate (new Vector3 (-1, 0, 0) * rotationSpeed);
//multiplica a velocidade pelo tempo
float amtToMove = currentSpeed * Time.deltaTime;
//manda o item pra baixo e girando com o space.world
transform.Translate (Vector3.down * amtToMove, Space.World);
//inimigo transferido a uma parte aleatoria em cima assim que chegar em baixo
if (transform.position.y <= -2)
{
SetPositionAndSpeed ();
PlayerScript.missed++;
}
// os quadrados perdidos forem 3 ou maior carrega a loseScene
if(PlayerScript.missed >= 3)
{
Application.LoadLevel (3);
}
}
public void SetPositionAndSpeed()
{
//faz a rotação e velocidade
currentRotateSpeed = Random.Range(MinRotateSpeed, MaxRotateSpeed);
currentScaleX = Random.Range (MinScale, MaxScale);
currentScaleY = Random.Range (MinScale, MaxScale);
currentScaleZ = Random.Range (MinScale, MaxScale);
//inicia a variavel currentSpeed com um valor aleatorio
currentSpeed = Random.RandomRange (minSpeed, maxSpeed);
//muda a posição do inimigo
x = Random.RandomRange (-6f, 6f);
y = 10.0f;
z = 0.0f;
transform.position = new Vector3 (x, y, z);
//transforma a posição
transform.localScale = new Vector3(currentScaleX, currentScaleY, currentScaleZ);
}
}
<file_sep>/Squareinvasion/Assets/Scripts/StarScript.cs
using UnityEngine;
using System.Collections;
public class StarScript : MonoBehaviour {
//variavel pra velocidade
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
//amtToMove = amount to move ou quantidade a mecher
float amtToMove = speed * Time.deltaTime;
//vector.down meche o vetor pra baixo e o space.world aplica a transformação emrelação as coordenadas do sistema
transform.Translate (Vector3.down * amtToMove, Space.World);
//se a posição for menor que -8.5 ele muda a posição
if (transform.position.y < -8.5)
{
transform.position = new Vector3 (transform.position.x, 15f, transform.position.z);
}
}
}
<file_sep>/Squareinvasion/Assets/Scripts/PlayerScript.cs
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
//estados da nave
enum State
{
Playing,
Explosion,
Invincible
}
//estado jogando
private State state = State.Playing;
/*velocidade do jogador
* objeto prefab
* vida e pontuação
* morte do jogador
* quadrados que passaram
*/
public float PlayerSpeed;
public GameObject Fire1Prefab;
public static int scores = 0;
public static int lives = 3;
public GameObject ExplosionPrefab;
public static int missed = 0;
//posicionando o tiro
private float fire1OffSet = 1.2f;
//variaveis de tempo etc para os estados da nave
private float ShipInvisibleTime = 1.5f;
private float shipMoveOnToScreenSpeed = 5;
private float blinkRate = .1f;
private int numberofTimesToBlink = 10;
private int blinkCount;
//variavel para os tipos de tiros e level do jogador
public static int typeFire = 1;
public static int levelPlayer = 1;
// Sempre é executado na inicialização do jogo
void Start ()
{
/*muda a posição do objeto
*
*/
transform.position = new Vector3 (0, 0.5f, transform.position.z);
}
// é executado a cada frame(quadro do jogo)
void Update ()
{
if(state != State.Explosion)
{
/*
* amount to move é a quantidade de movimento que sera feita * a velocidade * o tempo, para todas as direções
*/
float amtToMove = Input.GetAxisRaw ("Horizontal") * PlayerSpeed * Time.deltaTime;
float amtToMove2 = Input.GetAxisRaw ("Vertical") * PlayerSpeed * Time.deltaTime;
transform.Translate(Vector3.right * amtToMove);
transform.Translate (Vector3.up * amtToMove2);
/*
* condições que verificam se o jogador saiu da tela, caso verdadeiro ele sera transferido para a direção contraria
*/
if (transform.position.x <= -7.4f)
{
transform.position = new Vector3 (7.4f, transform.position.y, transform.position.z);
}
else if(transform.position.x >= 7.4f)
{
transform.position = new Vector3 (-7.4f, transform.position.y, transform.position.z);
}
if (transform.position.y <= -1.6f)
{
transform.position = new Vector3 (transform.position.x, 9.6f, transform.position.z);
}
else if (transform.position.y >= 9.6f)
{
transform.position = new Vector3 (transform.position.x, -1.6f, transform.position.z);
}
/*
* ao apertar o botao especificado ele solta o objeto
*/
if (Input.GetKeyDown ("space"))
{
/*transform.localScale.y é usado para transformação da escal em relação ao pai(no caso o jogador) na posição y
* Instantiate é usada para determinar a posição do projetil
* Vector3 position = new Vector3 (transform.position.x, transform.position.y + fire1OffSet);
* Instantiate (Fire1Prefab, position, Quaternion.identity);
*/
if (typeFire == 1)
{
Vector3 position = new Vector3 (transform.position.x, transform.position.y + 0.3f + fire1OffSet);
Instantiate (Fire1Prefab, position, Quaternion.identity);
}
if (typeFire == 2)
{
Vector3 position = new Vector3 (transform.position.x, transform.position.y + 0.3f + fire1OffSet);
Instantiate (Fire1Prefab, position, Quaternion.identity);
Vector3 position3 = new Vector3 (transform.position.x + 0.7f, transform.position.y + fire1OffSet);
Instantiate (Fire1Prefab, position3, Quaternion.identity);
}
if (typeFire == 3) {
Vector3 position = new Vector3 (transform.position.x, transform.position.y + 0.3f + fire1OffSet);
Instantiate (Fire1Prefab, position, Quaternion.identity);
Vector3 position2 = new Vector3 (transform.position.x - 0.7f, transform.position.y + fire1OffSet);
Instantiate (Fire1Prefab, position2, Quaternion.identity);
Vector3 position3 = new Vector3 (transform.position.x + 0.7f, transform.position.y + fire1OffSet);
Instantiate (Fire1Prefab, position3, Quaternion.identity);
}
}
}
}
//mostra a interface grafica pra pontuação e vida serem exibidos em texto
void OnGUI()
{
//rect é um retangulo 2d
GUI.Label (new Rect (10, 10, 105, 20), "Pontuação: " + PlayerScript.scores.ToString ());
GUI.Label (new Rect (10, 30, 60, 20), "Vida: " + PlayerScript.lives.ToString());
GUI.Label (new Rect (10, 50, 80, 20), "Perdidos: " + PlayerScript.missed.ToString ());
GUI.Label (new Rect (200, 10, 100, 20), "Level Jogador: " + PlayerScript.levelPlayer.ToString ());
}
//objeto colide com jogador e da explosao e diminui a vida
void OnTriggerEnter(Collider otherObject)
{
if (otherObject.tag == "enemy" && state == State.Playing)
{
PlayerScript.lives--;
EnemyScript enemyScript = (EnemyScript)otherObject.gameObject.GetComponent ("EnemyScript");
enemyScript.SetPositionAndSpeed ();
Instantiate(ExplosionPrefab, transform.position, Quaternion.identity);
//destroi o jogador
StartCoroutine(DestroyShip());
}
}
//rotina para o jogador caso morra
IEnumerator DestroyShip()
{
//estado de explosão
state = State.Explosion;
Instantiate (ExplosionPrefab, transform.position, Quaternion.identity);
//desabilita a renderização do jogador
gameObject.GetComponent<Renderer>().enabled = false;
transform.position = new Vector3 (0f, -2.5f, transform.position.z);
//utiliza a função para esperar um determinado tempo
yield return new WaitForSeconds (ShipInvisibleTime);
//se a vida for 0 reseta o jogo
if (PlayerScript.lives > 0)
{
//habilita a renderização do jogador
gameObject.GetComponent<Renderer> ().enabled = true;
while (transform.position.y <= 0.5f)
{
float amtToMove = shipMoveOnToScreenSpeed * Time.deltaTime;
transform.position = new Vector3 (0f, transform.position.y + amtToMove, transform.position.z);
yield return 0;
}
state = State.Invincible;
//ele fica invencivel/invisivel e volta pro local
while(blinkCount < numberofTimesToBlink)
{
gameObject.GetComponent<Renderer> ().enabled = !gameObject.GetComponent<Renderer> ().enabled;
if (gameObject.GetComponent<Renderer> ().enabled == true)
{
blinkCount++;
}
yield return new WaitForSeconds (blinkRate);
}
blinkCount = 0;
state = State.Playing;
}
else
{
Application.LoadLevel (3);
}
}
}
<file_sep>/README.md
# Games
Here are some games made for learning
<file_sep>/Squareinvasion/Assets/Scripts/Fire1Script.cs
using UnityEngine;
using System.Collections;
public class Fire1Script : MonoBehaviour {
//cria variavel para velocidade do projetil
public float fire1Speed;
//cria variavel para a explosão
public GameObject ExplosionPrefab;
//cria a variavel pro inimigo
private EnemyScript enemyScript;
//variavel para acessar o script do jogador
private PlayerScript playerScript;
// Use this for initialization
void Start ()
{
//acha o inimigo no script do inimigo(acha o gameobject pelo nome e retorna)
enemyScript = (EnemyScript)GameObject.Find ("Enemy").GetComponent ("EnemyScript");
//acho o jogador no script do jogador(acha o gameobject pelo nome e retorna tambem)
playerScript = (PlayerScript)GameObject.Find("SpaceShip").GetComponent("PlayerScript");
}
// Update is called once per frame
void Update ()
{
//move o projetil para cima inicialmente
float amtToMove = fire1Speed * Time.deltaTime;
transform.Translate (Vector3.up * amtToMove);
//condição para que o objeto seja destruido
if (transform.position.y > 10.0f)
{
Destroy (this.gameObject);
}
}
//confere se o tiro acertou o objeto e destroi
void OnTriggerEnter(Collider otherObject)
{
if (otherObject.tag == "enemy")
{
//EnemyScript enemyScript = (EnemyScript)otherObject.gameObject.GetComponent ("EnemyScript");
//faz a explosao ocorrer
Instantiate(ExplosionPrefab, enemyScript.transform.position, enemyScript.transform.rotation);
enemyScript.minSpeed += 0.1f;
enemyScript.maxSpeed += 0.5f;
enemyScript.SetPositionAndSpeed ();
//destroi o objeto do jogo -->Destroy (otherObject.gameObject);
Destroy(gameObject);
//incrementa a pontuação
PlayerScript.scores += 100;
if (PlayerScript.scores >= 1000)
{
PlayerScript.typeFire = 2;
PlayerScript.levelPlayer = 2;
}
if (PlayerScript.scores >= 2000)
{
PlayerScript.typeFire = 3;
PlayerScript.levelPlayer = 3;
}
if(PlayerScript.scores >= 3000)
{
Application.LoadLevel (2);
}
}
}
}
<file_sep>/Squareinvasion/Assets/Scripts/ScriptTelas/WinScript.cs
using UnityEngine;
using System.Collections;
public class WinScript : MonoBehaviour {
//cria as variaveis para os botoes e seus valores(tamanhos)
//private int buttonWitdh = 200;
//private int buttonHeight = 50;
//cria a variavel pra textura
public Texture backgroundTexture;
//cria a interface com o botão
void OnGUI()
{
/*
if (GUI.Button (new Rect (Screen.width / 2 - buttonWitdh / 2, Screen.height / 2 - buttonHeight / 2, buttonWitdh, buttonHeight), "Voce venceu\nJogar novamente ?"))
{
PlayerScript.scores = 0;
PlayerScript.lives = 3;
PlayerScript.missed = 0;
Application.LoadLevel (1);
}
*/
//joga a textura na tela como nos outros scripts
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), backgroundTexture);
if (Input.anyKeyDown)
{
PlayerScript.scores = 0;
PlayerScript.lives = 3;
PlayerScript.missed = 0;
PlayerScript.levelPlayer = 1;
PlayerScript.typeFire = 1;
Application.LoadLevel (1);
}
}
}
<file_sep>/Squareinvasion/Assets/Scripts/ScriptTelas/LoseScript.cs
using UnityEngine;
using System.Collections;
public class LoseScript : MonoBehaviour {
//cria a variavel e os tamanhos dos botoes
//private int buttonWitdh = 200;
//private int buttonHeight = 50;
//cria a variavel textura
public Texture backgroundTexture;
void OnGUI()
{
/*
if (GUI.Button (new Rect (Screen.width / 2 - buttonWitdh / 2, Screen.height / 2 - buttonHeight / 2, buttonWitdh, buttonHeight), "Game Over\nJogar novamente?"))
{
//se o botao for acionado ele reseta tudo e chama o level denovo
PlayerScript.scores = 0;
PlayerScript.lives = 3;
PlayerScript.missed = 0;
Application.LoadLevel (1);
}
*/
//joga a textura na tela
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), backgroundTexture);
if (Input.anyKeyDown)
{
PlayerScript.scores = 0;
PlayerScript.lives = 3;
PlayerScript.missed = 0;
PlayerScript.levelPlayer = 1;
PlayerScript.typeFire = 1;
Application.LoadLevel (1);
}
}
}
| eec04e3d7c1768d07539739f0049b1296dbf4f75 | [
"Markdown",
"C#",
"C++"
] | 9 | C++ | Ryddan/Games | 62b52d5f79d3ebc3e7162182944b0b26f10d6bac | f88d0b7b9fcbd37b1a88f0b76bccbf22d82444a0 |
refs/heads/master | <file_sep>"""
MAIN VERISON
<NAME>
CMETE1
<EMAIL>
"""
from tkinter import *
from tkinter.messagebox import showinfo
import pickle
from operator import *
from time import *
import random
class Model:
"""Model handels all calculations """
def __init__(self, master, name, mines, rows, columns):
self.name = name
self.mines = mines
self.rows = rows
self.columns = columns
self.master = master
self.flag_counter_number = mines
self.bug_fix = 0
self.counter = 0
self.flag_counter = 0
self.correct_flag = 0
self.mine_counter = 0
self.correct_mine = 0
self.start_time = time()
self.end_time = 0
self.game = Toplevel(self.master)
self.gameGrid = {}
self.cellStatus = {}
self.start_game()
""" Method called when the game starts """
def start_game(self):
self.place_mines()
self.button_values()
""" Method called in the beginning which places all mines in random cells """
def place_mines(self):
for a in range(self.mines):
x = random.randint(0, self.rows-1)
y = random.randint(0, self.columns-1)
while (x, y) in self.gameGrid.keys():
x = random.randint(0, self.rows-1)
y = random.randint(0, self.columns-1)
self.gameGrid[(x, y)] = 'Mine'
self.cellStatus[(x, y)] = 'Closed'
VC.build_button(self.master, self, self.game, x, y, '')
""" Method called after mines are placed that will give all cells appropriate values """
def button_values(self):
for x in range(self.rows):
for y in range(self.columns):
if (x, y) not in self.gameGrid.keys():
self.counter = 0
for a in range(3):
for b in range(3):
if 0 <= (x+a-1) < self.rows and 0 <= (y+b-1) < self.columns:
if (x+a-1, y+b-1) in self.gameGrid.keys():
if self.gameGrid[(x+a-1, y+b-1)] == 'Mine':
self.counter += 1
self.gameGrid[(x, y)] = self.counter
self.cellStatus[(x, y)] = 'Closed'
VC.build_button(self.master, self, self.game, x, y, '')
""" Method called when a button is pressed"""
def click(self, x, y, leftRight):
if leftRight == 'left' and self.gameGrid[(x, y)] == 'Mine' and self.bug_fix != 1:
self.fail()
else:
if leftRight == 'left' and (self.cellStatus[(x, y)] == 'Closed' or self.cellStatus[(x, y)] == 'Flagged'):
if self.cellStatus[(x, y)] == 'Flagged':
Model.remove_flag(self, x, y)
else:
if self.gameGrid[(x, y)] == 0:
Model.open_empty(self, x, y)
Model.victory_open(self)
else:
Model.open(self, x, y)
Model.victory_open(self)
if leftRight == 'right' and self.cellStatus[(x, y)] == 'Flagged':
Model.remove_flag(self, x, y)
elif leftRight == 'right' and (self.cellStatus[(x, y)] == 'Closed' or self.cellStatus[(x, y)] == 'Flagged'):
Model.flag(self, x, y)
Model.victory_flags(self)
""" Method called when a button is to be opened """
def open(self, x, y):
if self.gameGrid[(x, y)] == 0:
VC.build_button(self.master, self, self.game, x, y, self.gameGrid[(x, y)])
self.cellStatus[(x, y)] = 'Open'
Model.open_empty(self, x, y)
else:
self.cellStatus[(x, y)] = 'Open'
VC.build_button(self.master, self, self.game, x, y, self.gameGrid[(x, y)])
""" Method called from Click to place a flag """
def flag(self, x, y):
value = '?'
self.cellStatus[(x, y)] = 'Flagged'
self.flag_counter_number = self.flag_counter_number - 1
VC.build_button(self.master, self, self.game, x, y, value)
""" Method called from Click to remove a flag """
def remove_flag(self, x, y):
self.cellStatus[(x, y)] = 'Closed'
self.flag_counter_number = self.flag_counter_number + 1
VC.build_button(self.master, self, self.game, x, y, '')
""" Method that opens all surrounding empty cells if an empty cell is pressed """
def open_empty(self, x, y):
VC.build_button(self.master, self, self.game, x, y, self.gameGrid[(x, y)])
self.cellStatus[(x, y)] = 'Open'
for a in range(3):
for b in range(3):
if 0 <= (x+a-1) < self.rows and 0 <= (y+b-1) < self.columns:
if self.cellStatus[(x+a-1, y+b-1)] == 'Closed':
Model.open(self, x+a-1, y+b-1)
""" Method that checks if the player has won through opening all cells """
def victory_open(self):
self.mine_counter = 0
self.correct_mine = 0
for x in range(self.rows):
for y in range(self.columns):
if self.cellStatus[(x, y)] == 'Closed':
self.mine_counter += 1
for x in range(self.rows):
for y in range(self.columns):
if self.gameGrid[(x, y)] == 'Mine':
self.correct_mine += 1
if self.mine_counter == self.mines == self.correct_mine:
for x in range(self.rows):
for y in range(self.columns):
self.open(x, y)
showinfo('You Won!', 'You won by not clicking on any mines in the field')
self.master.grab_set()
self.end_time = time()
self.calculate_score()
return False
""" Method that checks if the player has flagged all mines"""
def victory_flags(self):
self.flag_counter = 0
self.correct_flag = 0
for x in range(self.rows):
for y in range(self.columns):
if self.cellStatus[(x, y)] == 'Flagged':
self.flag_counter += 1
for x in range(self.rows):
for y in range(self.columns):
if self.cellStatus[(x, y)] == 'Flagged' and self.gameGrid[(x, y)] == 'Mine':
self.correct_flag += 1
if self.flag_counter == self.correct_flag == self.mines:
for x in range(self.rows):
for y in range(self.columns):
if self.cellStatus[(x, y)] != 'Flagged':
self.open(x, y)
self.bug_fix = 1
showinfo('You Won!', 'You won by flagging all mines in the field')
self.master.grab_set()
self.end_time = time()
self.calculate_score()
return False
""" Method called when a mine is pressed. The game will end"""
def fail(self):
for x in range(self.rows):
for y in range(self.columns):
self.open(x, y)
showinfo('You lost!', 'You have clicked on a mine and lost the game')
self.game.destroy()
self.master.deiconify()
""" Method called when the player wins to calculate the score """
def calculate_score(self):
time = self.end_time - self.start_time
self.score = int((self.mines * self.rows * self.columns * 100)/time)
Model.highscore(self)
""" Method called to create a highscore file and sort it """
def highscore(self):
try:
file = open('highscore.txt', 'rb')
score_list = pickle.load(file)
file.close()
except FileNotFoundError:
file = open('highscore.txt', 'w+')
file = open('highscore.txt', 'rb')
score_list = []
file.close()
score_list.append((self.name, self.score))
score_list = sorted(score_list, key=itemgetter(1), reverse=True)[:10]
file = open('highscore.txt', 'wb')
pickle.dump(score_list, file)
file.close()
VC.show_highscore(self.master, self)
class VC():
""" VC handels all graphic content (VC = ViewControl) """
def __init__(self, master):
self.master = master
self.window = Frame(self.master)
self.window.pack()
VC.menu_field(self)
VC.menu_buttons(self)
""" Method called in the beginning to set out all menu text-boxes """
def menu_field(self):
self.label = Label(self.window, text='Choose number of rows, columns and mines!', height=2, width=45)
self.label.pack()
boxWindow = Frame(self.window)
boxWindow.pack()
self.entryName = Entry(boxWindow, width=20)
self.entryName.insert(0, 'Enter your name')
self.entryName.pack()
self.labelMines = Label(boxWindow, text='Mines')
self.labelMines.pack()
self.boxMines = Spinbox(boxWindow, width=10, from_=1, to=500)
self.boxMines.pack()
self.labelRows = Label(boxWindow, text='Rows')
self.labelRows.pack()
self.boxRows = Spinbox(boxWindow, width=10, from_=1, to=500)
self.boxRows.pack()
self.labelColumns = Label(boxWindow, text='Columns')
self.labelColumns.pack()
self.boxColumns = Spinbox(boxWindow, width=10, from_=1, to=500)
self.boxColumns.pack()
""" Method called to add all buttons in the menu """
def menu_buttons(self):
self.buttonWindow = Frame(self.window)
self.buttonWindow.pack()
self.errorInput = Label(self.buttonWindow)
self.errorInput.pack(side=BOTTOM)
self.buttonPlay = Button(text='Play', height=2, command=self.send_values)
self.buttonPlay.pack()
self.buttonQuit = Button(text='Quit', height=2, command=self.master.destroy)
self.buttonQuit.pack()
""" Method that checks all values before sending them to Model """
def send_values(self):
try:
name = self.entryName.get()
if self.boxRows.get().isdigit() and 1 <= int(self.boxRows.get()) <= 10:
self.boxRows.configure(fg="black")
rows = int(self.boxRows.get())
else:
self.boxRows.configure(fg="red")
if self.boxColumns.get().isdigit() and 1 <= int(self.boxColumns.get()) <= 10:
self.boxColumns.configure(fg="black")
columns = int(self.boxColumns.get())
else:
self.boxColumns.configure(fg="red")
if self.boxMines.get().isdigit():
self.boxMines.configure(fg="black")
else:
self.boxMines.configure(fg="red")
if 0 < int(self.boxMines.get()) < int(self.boxRows.get()) * int(self.boxColumns.get()):
self.boxMines.configure(fg="black")
mines = int(self.boxMines.get())
else:
self.boxMines.configure(fg="red")
Model(self.master, name, mines, rows, columns)
self.master.withdraw()
except (UnboundLocalError, ValueError):
self.errorInput.configure(text='You can only use numbers to define Mines, Rows and Columns \n '
'The maximum amount of rows and columns is 10 \n '
'You cannot have a field with only mines')
""" Method called when a button is to be built """
def build_button(self, obj, frame, x, y, value):
if value == '':
cell = Label(frame, text=value, height=2, width=3, bg='white', relief=RAISED)
elif value == 'Mine':
cell = Label(frame, text='*', height=2, width=3, bg='black', fg='red', relief=SUNKEN)
elif value == 0:
cell = Label(frame, text='', height=2, width=3, bg='grey', relief=SUNKEN)
else:
cell = Label(frame, text=value, height=2, width=3, bg='white', relief=SUNKEN)
cell.grid(row=x, column=y)
cell.bind('<Button-2>', lambda event: Model.click(obj, x, y, 'right'))
cell.bind('<Button-1>', lambda event: Model.click(obj, x, y, 'left'))
flag_counter_label = Label(frame, text=obj.flag_counter_number, height=2, width=3)
flag_counter_label.grid(row=obj.rows+1, column=0)
""" Method called to show the highscore after a successful run """
def show_highscore(self, obj):
self.highscore_window = Toplevel(self.master)
obj.game.destroy()
self.highscore_label = Label(self.highscore_window, text='Highscores', height=2, width=40)
self.highscore_label.pack()
self.my_score = Label(self.highscore_window, text=('Your score: ' + obj.name + ' - ' + str(obj.score)), height = 3)
self.my_score.pack()
file = open('highscore.txt', 'rb')
score_list = pickle.load(file)
score_list_size = len(score_list)
for a in range(score_list_size):
score_row = str(score_list[a])
score_row = score_row.replace("',", ' - ')
self.score = Label(self.highscore_window, text=(a+1, score_row))
self.score.pack()
file.close()
obj.master.grab_release()
obj.master.deiconify()
""" Function that starts the game """
def main():
root = Tk()
root.title('Minesweeper')
program = VC(root)
root.mainloop()
if __name__ == '__main__':
main()<file_sep># Python-Minesweeper
Minesweeper game made with Tkinter in Python
</br>

<file_sep>import unittest
from Minesweeper import Model
from tkinter import *
import os.path
class Minesweeper_test(unittest.TestCase):
root = Tk()
m = Model(root, 'Test', 5, 5, 5)
n = Model(root, 'Test', 5, 5, 5)
def test(self):
self.assertIsInstance(self.m.master, Tk)
self.assertIsInstance(self.m.game, Toplevel)
self.assertEqual(self.m.name, 'Test')
self.assertEqual(self.m.flag_counter_number, 5)
self.assertEqual(self.m.mines, 5)
self.assertEqual(len(self.m.cellStatus), len(self.m.gameGrid))
self.assertEqual(self.m.mines, 5)
self.assertEqual(self.m.rows, 5)
self.assertEqual(self.m.columns, 5)
self.assertEqual(self.m.bug_fix, 0)
mine_counter = 0
for i in range(5):
for j in range(5):
self.assertEqual(self.m.cellStatus[(i, j)], 'Closed')
if self.m.gameGrid[(i, j)] == 'Mine':
mine_counter += 1
self.assertEqual(mine_counter, self.m.mines)
counter_buttons = 0
for i in range(5):
for j in range(5):
self.m.open(i, j)
counter_buttons += 1
self.assertEqual(counter_buttons, 25)
self.assertNotEqual(self.m.gameGrid, self.n.gameGrid)
self.assertNotEqual(self.m.cellStatus, self.n.cellStatus)
self.assertFalse(self.m.victory_flags())
self.assertFalse(self.m.victory_open())
self.assertTrue(os.path.isfile('highscore.txt'))
if __name__ == '__main__':
unittest.main() | 81ed3fb8c46c967bc4ba12b48c01a21a6ccfc7a0 | [
"Markdown",
"Python"
] | 3 | Python | JoelWeidenmark/Python-Minesweeper | 0ee8d9c281e7e79b2eeeff8d160f23674950f62f | 8864de4f2367e1a39f2f30822a10656b52199d51 |
refs/heads/master | <repo_name>ANelson82/brazillianEcommerce<file_sep>/str_len.py
x = '48436dade18ac8b2bce089ec2a041202'
print(len(x))<file_sep>/olist_geolocation_dataset.sql
CREATE TABLE public.olist_geolocation_dataset
(
geolocation_zip_code_prefix character varying(32),
geolocation_lat numeric(18,15),
geolocation_lng numeric(18,15),
geolocation_city character varying(64),
geolocation_state character varying(2)
)<file_sep>/olist_customers_dataset.sql
-- Table: public.olist_customers_dataset
-- DROP TABLE public.olist_customers_dataset;
CREATE TABLE public.olist_customers_dataset
(
customer_id character varying(32) COLLATE pg_catalog."default" NOT NULL,
customer_unique_id character varying(32) COLLATE pg_catalog."default",
customer_zip_code_prefix "char",
customer_city "char",
customer_state "char",
CONSTRAINT olist_customers_dataset_pkey PRIMARY KEY (customer_id)
)
TABLESPACE pg_default;
ALTER TABLE public.olist_customers_dataset
OWNER to postgres;<file_sep>/olist_order_payments_dataset.sql
CREATE TABLE public.olist_order_payments_dataset
(
order_id character varying(32),
payment_sequential smallint,
payment_type character varying(32),
payment_installments smallint,
payment_value numeric(10,2)
)<file_sep>/olist_customers_dataset2.sql
CREATE TABLE public.olist_customers_dataset
(
customer_id character varying(32),
customer_unique_id character varying(32),
customer_zip_code_prefix character varying(5),
customer_city character varying(32),
customer_state character varying(2),
CONSTRAINT olist_customers_dataset_pkey PRIMARY KEY (customer_id)
)<file_sep>/olist_order_items_dataset.sql
CREATE TABLE public.olist_order_items_dataset
(
order_id character varying(32),
order_item_id character varying(32),
product_id character varying(32),
seller_id character varying(64),
shipping_limit_date timestamp,
price numeric(10,2),
freight_value numeric(10,2)
CONSTRAINT olist_order_items_dataset_pkey PRIMARY KEY (order_id)
) | 773d857b927deff64f8e3516727d5d363371ce4a | [
"SQL",
"Python"
] | 6 | Python | ANelson82/brazillianEcommerce | a2455550b984a0f6d87f309cc3535fba592cd900 | b5a5f0e357379c4b5282787aa258f93caec4bbe0 |
refs/heads/master | <file_sep>require 'test_helper'
class MyCommentsHelperTest < ActionView::TestCase
end
<file_sep>class ProfilesController < ApplicationController
before_action :authenticate_user!, only: [:new, :edit]
def new
@profile = current_user.build_profile
end
def create
@profile = current_user.build_profile(profile_params)
if @profile.save
redirect_to user_profile_path(current_user,current_user.profile)
else
redirect_to new_user_profile_path(current_user)
end
end
def show
@profile = current_user.profile
end
def edit
@profile = current_user.profile
end
def update
if current_user.profile.update_attributes(profile_params)
redirect_to user_profile_path(current_user,current_user.profile)
else
redirect_to edit_user_profile_path(current_user,current_user.profile)
end
end
def destroy
end
def picture
@profile = current_user.profile
send_data(@profile.picture_data, :type => @profile.content_type, :disposition => 'inline')
end
private
def profile_params
params.require(:profile).permit(:name, :sex, :birthday, :team, :place, :picture_file)
end
end
<file_sep>class TopController < ApplicationController
def index
if user_signed_in?
if current_user.profile.nil?
redirect_to new_user_profile_path(current_user)
end
end
@contents = Content.all
end
end
<file_sep>class CreateContents < ActiveRecord::Migration
def change
create_table :contents do |t|
t.string :title
t.string :body
t.string :place
t.date :day
t.boolean :complete
t.timestamps
end
end
end
<file_sep>class Profile < ActiveRecord::Base
belongs_to :user
validates :name, presence: true
validates :sex, presence: true
validates :birthday, presence: true
validates :team, presence: true
validates :place, presence: true
def picture_file= (p)
if p
self.picture_data= p.read
self.content_type= p.content_type
end
end
end
<file_sep>class MyCommentsController < ApplicationController
def index
@comments = current_user.comments.all
end
end
<file_sep>Rails.application.routes.draw do
devise_for :users, controllers: { registrations: 'registrations' }
resources :users do
resources :profiles do
member do
get :picture
end
end
get 'my_comments/index'
resources :contents do
resources :comments
end
end
root to: "top#index"
end
| ed7a0d6e43c08268bc7fd334c8ef00cd3ce9d9b1 | [
"Ruby"
] | 7 | Ruby | yuichi-masuda/tt_community | 6e63bb891dd502e7cfa217cadca65a587aa5cb46 | af114d58d181cc3cb055570962a7150713fedb41 |
refs/heads/master | <repo_name>rohitsiddha/herokutestapp<file_sep>/app/models/post.rb
class Post < ActiveRecord::Base
attr_accessible :name, :tweet
end
<file_sep>/README.md
herokutestapp
============= | 7de41ac5527a4222717878611634f0813491fbab | [
"Markdown",
"Ruby"
] | 2 | Ruby | rohitsiddha/herokutestapp | 5bcf3cc3904f524b2b5a7253050b93423e672626 | 01525f5ad106e5ed073a6ce6551b61da7daeaf8a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.