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>BrandonTheHamm/fluidsim<file_sep>/pez.linux.cpp
// Pez was developed by <NAME> and released under the MIT License.
#ifdef VKFLUID_LINUX
#include <GL/glx.h>
#include "pez.h"
#include "bstrlib.h"
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <signal.h>
#include <wchar.h>
#include <Xm/MwmUtil.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xmd.h>
typedef struct PlatformContextRec
{
Display* MainDisplay;
Window MainWindow;
} PlatformContext;
unsigned int GetMicroseconds()
{
struct timeval tp;
gettimeofday(&tp, NULL);
return tp.tv_sec * 1000000 + tp.tv_usec;
}
#if 0
int main(int argc, char** argv)
{
int attrib[] = {
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_DOUBLEBUFFER, True,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24,
None
};
PlatformContext context;
context.MainDisplay = XOpenDisplay(NULL);
int screenIndex = DefaultScreen(context.MainDisplay);
Window root = RootWindow(context.MainDisplay, screenIndex);
int fbcount;
PFNGLXCHOOSEFBCONFIGPROC glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress((GLubyte*)"glXChooseFBConfig");
GLXFBConfig *fbc = glXChooseFBConfig(context.MainDisplay, screenIndex, attrib, &fbcount);
if (!fbc)
pezFatal("Failed to retrieve a framebuffer config\n");
PFNGLXGETVISUALFROMFBCONFIGPROC glXGetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) glXGetProcAddress((GLubyte*)"glXGetVisualFromFBConfig");
if (!glXGetVisualFromFBConfig)
pezFatal("Failed to get a GLX function pointer\n");
PFNGLXGETFBCONFIGATTRIBPROC glXGetFBConfigAttrib = (PFNGLXGETFBCONFIGATTRIBPROC) glXGetProcAddress((GLubyte*)"glXGetFBConfigAttrib");
if (!glXGetFBConfigAttrib)
pezFatal("Failed to get a GLX function pointer\n");
if (PezGetConfig().Multisampling) {
int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;
for ( int i = 0; i < fbcount; i++ ) {
XVisualInfo *vi = glXGetVisualFromFBConfig( context.MainDisplay, fbc[i] );
if (!vi) {
continue;
}
int samp_buf, samples;
glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLES , &samples );
//printf( " Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
// " SAMPLES = %d\n",
// i, (unsigned int) vi->visualid, samp_buf, samples );
if ( best_fbc < 0 || (samp_buf && samples > best_num_samp) )
best_fbc = i, best_num_samp = samples;
if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp )
worst_fbc = i, worst_num_samp = samples;
XFree( vi );
}
fbc[0] = fbc[ best_fbc ];
}
XVisualInfo *visinfo = glXGetVisualFromFBConfig(context.MainDisplay, fbc[0]);
if (!visinfo)
pezFatal("Error: couldn't create OpenGL window with this pixel format.\n");
XSetWindowAttributes attr;
attr.background_pixel = 0;
attr.border_pixel = 0;
attr.colormap = XCreateColormap(context.MainDisplay, root, visinfo->visual, AllocNone);
attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeyReleaseMask |
PointerMotionMask | ButtonPressMask | ButtonReleaseMask;
context.MainWindow = XCreateWindow(
context.MainDisplay,
root,
0, 0,
PezGetConfig().Width, PezGetConfig().Height, 0,
visinfo->depth,
InputOutput,
visinfo->visual,
CWBackPixel | /*CWBorderPixel |*/ CWColormap | CWEventMask,
&attr
);
int borderless = 1;
if (borderless) {
Atom mwmHintsProperty = XInternAtom(context.MainDisplay, "_MOTIF_WM_HINTS", 0);
MwmHints hints = {0};
hints.flags = MWM_HINTS_DECORATIONS;
hints.decorations = 0;
XChangeProperty(context.MainDisplay, context.MainWindow, mwmHintsProperty, mwmHintsProperty, 32,
PropModeReplace, (unsigned char *)&hints, PROP_MWM_HINTS_ELEMENTS);
}
XMapWindow(context.MainDisplay, context.MainWindow);
int centerWindow = 1;
if (centerWindow) {
Screen* pScreen = XScreenOfDisplay(context.MainDisplay, screenIndex);
int left = XWidthOfScreen(pScreen)/2 - PezGetConfig().Width/2;
int top = XHeightOfScreen(pScreen)/2 - PezGetConfig().Height/2;
XMoveWindow(context.MainDisplay, context.MainWindow, left, top);
}
GLXContext glcontext = 0;
if (PEZ_FORWARD_COMPATIBLE_GL) {
PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribs = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((GLubyte*)"glXCreateContextAttribsARB");
if (!glXCreateContextAttribs) {
pezFatal("Your platform does not support OpenGL 4.0.\n"
"Try changing PEZ_FORWARD_COMPATIBLE_GL to 0.\n");
}
int attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 4,
GLX_CONTEXT_MINOR_VERSION_ARB, 0,
GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0
};
glcontext = glXCreateContextAttribs(context.MainDisplay, fbc[0], NULL, True, attribs);
} else {
glcontext = glXCreateContext(context.MainDisplay, visinfo, NULL, True);
}
glXMakeCurrent(context.MainDisplay, context.MainWindow, glcontext);
PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress((GLubyte*)"glXSwapIntervalSGI");
if (glXSwapIntervalSGI) {
glXSwapIntervalSGI(PezGetConfig().VerticalSync ? 1 : 0);
}
// Reset OpenGL error state:
glGetError();
// Lop off the trailing .c
bstring name = bfromcstr(PezGetConfig().Title);
pezSwInit("");
// Set up the Shader Wrangler
pezSwAddPath("./", ".glsl");
pezSwAddPath("../", ".glsl");
char qualifiedPath[128];
strcpy(qualifiedPath, pezResourcePath());
strcat(qualifiedPath, "/");
pezSwAddPath(qualifiedPath, ".glsl");
pezSwAddDirective("*", "#version 400");
// Perform user-specified intialization
pezPrintString("OpenGL Version: %s\n", glGetString(GL_VERSION));
PezInitialize();
bstring windowTitle = bmidstr(name, 0, blength(name) - 2);
XStoreName(context.MainDisplay, context.MainWindow, bdata(windowTitle));
bdestroy(windowTitle);
bdestroy(name);
// -------------------
// Start the Game Loop
// -------------------
unsigned int previousTime = GetMicroseconds();
int done = 0;
while (!done) {
if (glGetError() != GL_NO_ERROR)
pezFatal("OpenGL error.\n");
while (XPending(context.MainDisplay)) {
XEvent event;
XNextEvent(context.MainDisplay, &event);
switch (event.type)
{
case Expose:
//redraw(display, event.xany.window);
break;
case ConfigureNotify:
//resize(event.xconfigure.width, event.xconfigure.height);
break;
#ifdef PEZ_MOUSE_HANDLER
case ButtonPress:
PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_DOWN);
break;
case ButtonRelease:
PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_UP);
break;
case MotionNotify:
PezHandleMouse(event.xmotion.x, event.xmotion.y, PEZ_MOVE);
break;
#endif
case KeyRelease: {
// case KeyPress: {
XComposeStatus composeStatus;
char asciiCode[32];
KeySym keySym;
int len;
len = XLookupString(&event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus);
switch (asciiCode[0]) {
case 'x': case 'X': case 'q': case 'Q':
case 0x1b:
done = 1;
break;
default:
PezHandleKey(asciiCode[0]);
}
}
}
}
unsigned int currentTime = GetMicroseconds();
unsigned int deltaTime = currentTime - previousTime;
previousTime = currentTime;
PezUpdate((float) deltaTime / 1000000.0f);
PezRender();
glXSwapBuffers(context.MainDisplay, context.MainWindow);
}
pezSwShutdown();
return 0;
}
#endif
void pezPrintStringW(const wchar_t* pStr, ...)
{
va_list a;
va_start(a, pStr);
wchar_t msg[1024] = {0};
vswprintf(msg, countof(msg), pStr, a);
fputws(msg, stderr);
}
void pezPrintString(const char* pStr, ...)
{
va_list a;
va_start(a, pStr);
char msg[1024] = {0};
vsnprintf(msg, countof(msg), pStr, a);
fputs(msg, stderr);
}
void pezFatalW(const wchar_t* pStr, ...)
{
fwide(stderr, 1);
va_list a;
va_start(a, pStr);
wchar_t msg[1024] = {0};
vswprintf(msg, countof(msg), pStr, a);
fputws(msg, stderr);
exit(1);
}
void _pezFatal(const char* pStr, va_list a)
{
char msg[1024] = {0};
vsnprintf(msg, countof(msg), pStr, a);
fputs(msg, stderr);
fputc('\n', stderr);
exit(1);
}
void pezFatal(const char* pStr, ...)
{
va_list a;
va_start(a, pStr);
_pezFatal(pStr, a);
}
void pezCheck(int condition, ...)
{
va_list a;
const char* pStr;
if (condition)
return;
va_start(a, condition);
pStr = va_arg(a, const char*);
_pezFatal(pStr, a);
}
void pezCheckPointer(void* p, ...)
{
va_list a;
const char* pStr;
if (p != NULL)
return;
va_start(a, p);
pStr = va_arg(a, const char*);
_pezFatal(pStr, a);
}
int pezIsPressing(char key)
{
return 0;
}
const char* pezResourcePath()
{
return ".";
}
#endif//VKFLUID_LINUX
<file_sep>/CMakeModules/FindGLEW.cmake
# Locate GLFW3 library
# This module defines
# GLEW_FOUND, if false, do not try to link to Lua
# GLEW_LIBRARIES
# GLEW_INCLUDE_DIR, where to find glfw3.h
# Set GLEW_USE_STATIC=YES if you want to link against the static glew libraries
FIND_PATH(GLEW_INCLUDE_DIR GL/glew.h
HINTS
$ENV{GLEW_DIR}
${GLEW_DIR}
PATH_SUFFIXES
include
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw # Fink
/opt/local # DarwinPorts
/opt/csw # Blastwave
/opt
)
FIND_LIBRARY(GLEW_LIBRARY_RELEASE
NAMES glew32 GLEW
HINTS
$ENV{GLEW_DIR}
${GLEW_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
FIND_LIBRARY(GLEW_LIBRARY_DEBUG
NAMES glew32d GLEWd
HINTS
$ENV{GLEW_DIR}
${GLEW_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
FIND_LIBRARY(GLEW_STATIC_LIBRARY_RELEASE
NAMES glew32s GLEWs
HINTS
$ENV{GLEW_DIR}
${GLEW_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
FIND_LIBRARY(GLEW_STATIC_LIBRARY_DEBUG
NAMES glew32sd GLEWsd
HINTS
$ENV{GLEW_DIR}
${GLEW_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
SET(GLEW_FOUND FALSE)
if(GLEW_INCLUDE_DIR)
if(GLEW_USE_STATIC)
MESSAGE(STATUS "GLEW - using STATIC libs")
if(GLEW_STATIC_LIBRARY_RELEASE AND GLEW_STATIC_LIBRARY_DEBUG)
MESSAGE(STATUS "GLEW - using BOTH STATIC libs")
SET(GLEW_FOUND TRUE)
SET(GLEW_LIBRARY debug ${GLEW_STATIC_LIBRARY_DEBUG} optimized ${GLEW_STATIC_LIBRARY_RELEASE})
ADD_DEFINITIONS(-DGLEW_STATIC)
elseif(GLEW_STATIC_LIBRARY_RELEASE)
MESSAGE(STATUS "GLEW - using ONLY release STATIC libs")
SET(GLEW_FOUND TRUE)
ADD_DEFINITIONS(-DGLEW_STATIC)
SET(GLEW_LIBRARY ${GLEW_STATIC_LIBRARY_RELEASE})
endif()
else()#!GLEW_USE_STATIC
MESSAGE(STATUS "GLEW - NOT using STATIC libs")
if(GLEW_LIBRARY_RELEASE AND GLEW_LIBRARY_DEBUG)
SET(GLEW_FOUND TRUE)
SET(GLEW_LIBRARY debug ${GLEW_LIBRARY_DEBUG} optimized ${GLEW_LIBRARY_RELEASE})
elseif(GLEW_LIBRARY_RELEASE)
SET(GLEW_FOUND TRUE)
SET(GLEW_LIBRARY ${GLEW_LIBRARY_RELEASE})
endif()
endif()#GLEW_USE_STATIC
endif()#GLEW_INCLUDE_DIR
#INCLUDE(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set GLEW_FOUND to TRUE if
# all listed variables are TRUE
#FIND_PACKAGE_HANDLE_STANDARD_ARGS(GLEW DEFAULT_MSG GLEW_LIBRARY GLEW_INCLUDE_DIR)
# MARK_AS_ADVANCED(GLEW_INCLUDE_DIR GLEW_LIBRARY)
<file_sep>/Makefile
CC=g++
CFLAGS=-Wall -c -O3 -DVKFLUID_LINUX
LIBS=-lX11 -lGL -lpng -lGLEW -lglfw
MAINCPP=Fluid3d.o Utility.o
CSHARED=pez.o pez.linux.o bstrlib.o
SHADERS=Fluid.glsl Raycast.glsl Light.glsl
run: fluid
./fluid
fluid: $(MAINCPP) $(CSHARED) $(SHADERS)
$(CC) $(MAINCPP) $(CSHARED) -o fluid $(LIBS)
.c.o:
$(CC) $(CFLAGS) $< -o $@
.cpp.o:
$(CC) $(CFLAGS) $< -o $@
clean:
rm -rf *.o fluid
<file_sep>/pez.win32.cpp
#ifdef VKFLUID_WIN32
#include "pez.h"
#include "bstrlib.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <signal.h>
#include <wchar.h>
void pezPrintStringW(const wchar_t* pStr, ...)
{
va_list a;
va_start(a, pStr);
wchar_t msg[1024] = {0};
vswprintf(msg, countof(msg), pStr, a);
fputws(msg, stderr);
}
void pezPrintString(const char* pStr, ...)
{
va_list a;
va_start(a, pStr);
char msg[1024] = {0};
vsnprintf(msg, countof(msg), pStr, a);
fputs(msg, stderr);
}
void pezFatalW(const wchar_t* pStr, ...)
{
fwide(stderr, 1);
va_list a;
va_start(a, pStr);
wchar_t msg[1024] = {0};
vswprintf(msg, countof(msg), pStr, a);
fputws(msg, stderr);
exit(1);
}
void _pezFatal(const char* pStr, va_list a)
{
char msg[1024] = {0};
vsnprintf(msg, countof(msg), pStr, a);
fputs(msg, stderr);
fputc('\n', stderr);
exit(1);
}
void pezFatal(const char* pStr, ...)
{
va_list a;
va_start(a, pStr);
_pezFatal(pStr, a);
}
void pezCheck(int condition, ...)
{
va_list a;
const char* pStr;
if (condition)
return;
va_start(a, condition);
pStr = va_arg(a, const char*);
_pezFatal(pStr, a);
}
void pezCheckPointer(void* p, ...)
{
va_list a;
const char* pStr;
if (p != NULL)
return;
va_start(a, p);
pStr = va_arg(a, const char*);
_pezFatal(pStr, a);
}
int pezIsPressing(char key)
{
return 0;
}
const char* pezResourcePath()
{
return ".";
}
#endif//VKFLUID_WIN32
<file_sep>/Fluid3d.cpp
//#define GL3_PROTOTYPES
//#include "gl3.h"
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glu.h>
//#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include "pez.h"
#include "bstrlib.h"
#include "Utility.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
using namespace vmath;
typedef enum render_type_t
{
Renderer_OPENGL,
Renderer_VULKAN,
} render_type_t;
typedef struct ContextRec
{
GLFWwindow *MainWindow;
render_type_t RendererType;
struct {
float X, Y;
int Buttons[GLFW_MOUSE_BUTTON_LAST];
} MouseState;
struct {
double StartTime;
unsigned FrameCount;
float FramesPerSecond;
} FrameStats;
bool WindowWasResized;
bool StopRequested;
} context_t;
static context_t GlobalContext = {};
typedef void(*render_init_func_t)(void);
typedef void(*update_func_t)(float dtseconds);
typedef void(*render_func_t)(void);
typedef void(*finalize_frame_func_t)(void);
typedef struct
{
render_init_func_t Initialize;
render_func_t RenderFrame;
update_func_t Update;
finalize_frame_func_t FinishFrame;
} renderer_t;
#ifdef _MSC_VER
//#define OpenGLError (GL_NO_ERROR == glGetError()), "%s:%d - OpenGL Error - %s", __FILE__, __LINE__, __FUNC__
static GLenum _errorCode;
#define OpenGLError ((_errorCode = glGetError()) == GL_NO_ERROR), "%s:%d OpenGL Error : %s", __FILE__, __LINE__, gluErrorString(_errorCode)
#else
#define OpenGLError GL_NO_ERROR == glGetError(), "%s:%d - OpenGL Error - %s", __FILE__, __LINE__, __FUNCTION__
#endif
static struct {
SlabPod Velocity;
SlabPod Density;
SlabPod Pressure;
SlabPod Temperature;
} Slabs;
static struct {
SurfacePod Divergence;
SurfacePod Obstacles;
SurfacePod LightCache;
SurfacePod BlurredDensity;
} Surfaces;
static struct {
Matrix4 Projection;
Matrix4 Modelview;
Matrix4 View;
Matrix4 ModelviewProjection;
} Matrices;
static struct {
GLuint CubeCenter;
GLuint FullscreenQuad;
} Vaos;
static const Point3 EyePosition = Point3(0, 0, 2);
static GLuint RaycastProgram;
static GLuint LightProgram;
static GLuint BlurProgram;
static float FieldOfView = 0.7f;
static bool SimulateFluid = true;
static const float DefaultThetaX = 0;
static const float DefaultThetaY = 0.75f;
static float ThetaX = DefaultThetaX;
static float ThetaY = DefaultThetaY;
static int ViewSamples = GridWidth*2;
static int LightSamples = GridWidth;
static float Fips = -4;
PezConfig PezGetConfig() {
PezConfig config;
config.Title = "Fluid3d";
config.Width = 853*2;
config.Height = 480*2;
config.Multisampling = 0;
config.VerticalSync = 0;
return config;
}
void PezInitialize() {
PezConfig cfg = PezGetConfig();
RaycastProgram = LoadProgram("Raycast.VS", "Raycast.GS", "Raycast.FS");
LightProgram = LoadProgram("Fluid.Vertex", "Fluid.PickLayer", "Light.Cache");
BlurProgram = LoadProgram("Fluid.Vertex", "Fluid.PickLayer", "Light.Blur");
glGenVertexArrays(1, &Vaos.CubeCenter);
glBindVertexArray(Vaos.CubeCenter);
CreatePointVbo(0, 0, 0);
glEnableVertexAttribArray(SlotPosition);
glVertexAttribPointer(SlotPosition, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);
glGenVertexArrays(1, &Vaos.FullscreenQuad);
glBindVertexArray(Vaos.FullscreenQuad);
CreateQuadVbo();
glEnableVertexAttribArray(SlotPosition);
glVertexAttribPointer(SlotPosition, 2, GL_SHORT, GL_FALSE, 2 * sizeof(short), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
Slabs.Velocity = CreateSlab(GridWidth, GridHeight, GridDepth, 3);
Slabs.Density = CreateSlab(GridWidth, GridHeight, GridDepth, 1);
Slabs.Pressure = CreateSlab(GridWidth, GridHeight, GridDepth, 1);
Slabs.Temperature = CreateSlab(GridWidth, GridHeight, GridDepth, 1);
Surfaces.Divergence = CreateVolume(GridWidth, GridHeight, GridDepth, 3);
Surfaces.LightCache = CreateVolume(GridWidth, GridHeight, GridDepth, 1);
Surfaces.BlurredDensity = CreateVolume(GridWidth, GridHeight, GridDepth, 1);
InitSlabOps();
Surfaces.Obstacles = CreateVolume(GridWidth, GridHeight, GridDepth, 3);
CreateObstacles(Surfaces.Obstacles);
ClearSurface(Slabs.Temperature.Ping, AmbientTemperature);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
pezCheck(OpenGLError);
}
void PezRenderOpenGL() {
pezCheck(OpenGLError);
PezConfig cfg = PezGetConfig();
// Blur and brighten the density map:
bool BlurAndBrighten = true;
if (BlurAndBrighten) {
glDisable(GL_BLEND);
glBindFramebuffer(GL_FRAMEBUFFER, Surfaces.BlurredDensity.FboHandle);
glViewport(0, 0, Slabs.Density.Ping.Width, Slabs.Density.Ping.Height);
glBindVertexArray(Vaos.FullscreenQuad);
glBindTexture(GL_TEXTURE_3D, Slabs.Density.Ping.ColorTexture);
glUseProgram(BlurProgram);
SetUniform("DensityScale", 5.0f);
SetUniform("StepSize", sqrtf(2.0) / float(ViewSamples));
SetUniform("InverseSize", recipPerElem(Vector3(float(GridWidth), float(GridHeight), float(GridDepth))));
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, GridDepth);
}
pezCheck(OpenGLError);
// Generate the light cache:
bool CacheLights = true;
if (CacheLights) {
glDisable(GL_BLEND);
glBindFramebuffer(GL_FRAMEBUFFER, Surfaces.LightCache.FboHandle);
glViewport(0, 0, Surfaces.LightCache.Width, Surfaces.LightCache.Height);
glBindVertexArray(Vaos.FullscreenQuad);
glBindTexture(GL_TEXTURE_3D, Surfaces.BlurredDensity.ColorTexture);
glUseProgram(LightProgram);
SetUniform("LightStep", sqrtf(2.0) / float(LightSamples));
SetUniform("LightSamples", LightSamples);
SetUniform("InverseSize", recipPerElem(Vector3(float(GridWidth), float(GridHeight), float(GridDepth))));
glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, GridDepth);
}
// Perform raycasting:
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, cfg.Width, cfg.Height);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_BLEND);
glBindVertexArray(Vaos.CubeCenter);
glActiveTexture(GL_TEXTURE0);
if (BlurAndBrighten) {
glBindTexture(GL_TEXTURE_3D, Surfaces.BlurredDensity.ColorTexture);
} else {
glBindTexture(GL_TEXTURE_3D, Slabs.Density.Ping.ColorTexture);
}
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_3D, Surfaces.LightCache.ColorTexture);
glUseProgram(RaycastProgram);
SetUniform("ModelviewProjection", Matrices.ModelviewProjection);
SetUniform("Modelview", Matrices.Modelview);
SetUniform("ViewMatrix", Matrices.View);
SetUniform("ProjectionMatrix", Matrices.Projection);
SetUniform("ViewSamples", ViewSamples);
SetUniform("EyePosition", EyePosition);
SetUniform("Density", 0);
SetUniform("LightCache", 1);
SetUniform("RayOrigin", Vector4(transpose(Matrices.Modelview) * EyePosition).getXYZ());
SetUniform("FocalLength", 1.0f / tanf(FieldOfView / 2.0f));
SetUniform("WindowSize", float(cfg.Width), float(cfg.Height));
SetUniform("StepSize", sqrtf(2.0) / float(ViewSamples));
glDrawArrays(GL_POINTS, 0, 1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_3D, 0);
glActiveTexture(GL_TEXTURE0);
pezCheck(OpenGLError);
}
void PezUpdate(float seconds) {
pezCheck(OpenGLError);
PezConfig cfg = PezGetConfig();
float dt = seconds * 0.0001f;
Vector3 up(1, 0, 0); Point3 target(0);
Matrices.View = Matrix4::lookAt(EyePosition, target, up);
Matrix4 modelMatrix = Matrix4::identity();
modelMatrix *= Matrix4::rotationX(ThetaX);
modelMatrix *= Matrix4::rotationY(ThetaY);
Matrices.Modelview = Matrices.View * modelMatrix;
Matrices.Projection = Matrix4::perspective(
FieldOfView,
float(cfg.Width) / cfg.Height, // Aspect Ratio
0.0f, // Near Plane
1.0f); // Far Plane
Matrices.ModelviewProjection = Matrices.Projection * Matrices.Modelview;
float fips = 1.0f / dt;
float alpha = 0.05f;
if (Fips < 0) {
Fips++;
} else if(Fips == 0) {
Fips = fips;
} else {
Fips = fips * alpha + Fips * (1.0f - alpha);
}
if (SimulateFluid) {
glBindVertexArray(Vaos.FullscreenQuad);
glViewport(0, 0, GridWidth, GridHeight);
Advect(Slabs.Velocity.Ping, Slabs.Velocity.Ping, Surfaces.Obstacles, Slabs.Velocity.Pong, VelocityDissipation);
SwapSurfaces(&Slabs.Velocity);
Advect(Slabs.Velocity.Ping, Slabs.Temperature.Ping, Surfaces.Obstacles, Slabs.Temperature.Pong, TemperatureDissipation);
SwapSurfaces(&Slabs.Temperature);
Advect(Slabs.Velocity.Ping, Slabs.Density.Ping, Surfaces.Obstacles, Slabs.Density.Pong, DensityDissipation);
SwapSurfaces(&Slabs.Density);
ApplyBuoyancy(Slabs.Velocity.Ping, Slabs.Temperature.Ping, Slabs.Density.Ping, Slabs.Velocity.Pong);
SwapSurfaces(&Slabs.Velocity);
ApplyImpulse(Slabs.Temperature.Ping, ImpulsePosition, ImpulseTemperature);
ApplyImpulse(Slabs.Density.Ping, ImpulsePosition, ImpulseDensity);
ComputeDivergence(Slabs.Velocity.Ping, Surfaces.Obstacles, Surfaces.Divergence);
ClearSurface(Slabs.Pressure.Ping, 0);
for (int i = 0; i < NumJacobiIterations; ++i) {
Jacobi(Slabs.Pressure.Ping, Surfaces.Divergence, Surfaces.Obstacles, Slabs.Pressure.Pong);
SwapSurfaces(&Slabs.Pressure);
}
SubtractGradient(Slabs.Velocity.Ping, Slabs.Pressure.Ping, Surfaces.Obstacles, Slabs.Velocity.Pong);
SwapSurfaces(&Slabs.Velocity);
}
pezCheck(OpenGLError);
}
void PezHandleMouse(int x, int y, int action)
{
static bool MouseDown = false;
static int StartX, StartY;
static const float Speed = 0.005f;
if (action == PEZ_DOWN) {
StartX = x;
StartY = y;
MouseDown = true;
} else if (MouseDown && action == PEZ_MOVE) {
ThetaX = DefaultThetaX + Speed * (x - StartX);
ThetaY = DefaultThetaY + Speed * (y - StartY);
} else if (action == PEZ_UP) {
MouseDown = false;
}
}
static void HandleErrorGLFW(int code, const char *errordesc) {
printf("GLFW error %d : %s\n", code, errordesc);
assert(false);
exit(EXIT_FAILURE);
}
static void HandleKeyInputGLFW(GLFWwindow *window, int key, int scancode, int action, int modifierFlags) {
context_t *ctx = &GlobalContext;
if(action == GLFW_RELEASE) {
switch(key) {
case GLFW_KEY_ESCAPE:
ctx->StopRequested = true;
break;
case GLFW_KEY_P:
case GLFW_KEY_SPACE:
SimulateFluid = !SimulateFluid;
break;
default:
break;
}
}
// handle key press stuff???
}
static void HandleMouseMoveGLFW(GLFWwindow *window, double px, double py) {
context_t *ctx = &GlobalContext;
ctx->MouseState.X = (float)px;
ctx->MouseState.Y = (float)py;
//printf("Mouse moved to %f x %f\n", px, py);
PezHandleMouse((int)ctx->MouseState.X, (int)ctx->MouseState.Y, PEZ_MOVE);
}
static void HandleMouseButtonInputGLFW(GLFWwindow *window, int button, int action, int modifiers) {
context_t *ctx = &GlobalContext;
//printf("Mouse button '%d' is %s at %f x %f\n", button,
//((action == GLFW_PRESS) ? "DOWN" : "UP"),
//ctx->MouseState.X, ctx->MouseState.Y);
int pezMouseAction = 0;
if(action == GLFW_PRESS) {
pezMouseAction = PEZ_DOWN;
} else if(action == GLFW_RELEASE) {
pezMouseAction = PEZ_UP;
}
PezHandleMouse((int)ctx->MouseState.X, (int)ctx->MouseState.Y, pezMouseAction);
}
static void HandleWindowResizeGLFW(GLFWwindow *window, int width, int height) {
context_t *ctx = &GlobalContext;
printf("Main window resized to %d x %d\n", width, height);
ctx->WindowWasResized = true;
}
static void HandleCursorEnterGLFW(GLFWwindow *window, int entered) {
context_t *ctx = &GlobalContext;
if(entered) {
printf("Mouse ENTERED!\n");
} else {
// release mouse
printf("Mouse EXITED!\n");
}
}
static void InitRendererOpenGL(void) {
context_t *ctx = &GlobalContext;
// make the context "current"
glfwMakeContextCurrent(ctx->MainWindow);
// clear any opengl error state
glGetError();
// Initialize GLEW - the OpenGL Extension Wrangler
glewExperimental = GL_TRUE;
GLenum result = glewInit();
if (result != GLEW_OK) {
printf("ERROR: Failed to initialize GLEW: %s\n", glewGetErrorString(result));
exit(EXIT_FAILURE);
}
// clear any opengl error state
glGetError();
// Init shader library
bstring name = bfromcstr(PezGetConfig().Title);
pezSwInit("");
pezSwAddPath("./", ".glsl");
pezSwAddPath("../", ".glsl");
char qualified_path[128];
strcpy(qualified_path, pezResourcePath());
strcpy(qualified_path, "/");
pezSwAddPath(qualified_path, ".glsl");
pezSwAddDirective("*", "#version 400");
pezPrintString("OpenGL Version: %s\n", glGetString(GL_VERSION));
PezInitialize();
glfwSwapInterval(0);
}
static void FinalizeFrameOpenGL(void) {
context_t *ctx = &GlobalContext;
glfwSwapBuffers(ctx->MainWindow);
}
int main(int argc, char *argv[]) {
glfwSetErrorCallback(HandleErrorGLFW);
context_t *ctx = &GlobalContext;
if(!glfwInit()) {
printf("Failed to initialize GLFW\n");
return(EXIT_FAILURE);
}
GLFWmonitor *monitor = glfwGetPrimaryMonitor();
const GLFWvidmode *vidmode = glfwGetVideoMode(monitor);
printf("Current video mode : %dx%d @ %d Hz\n", vidmode->width, vidmode->height, vidmode->refreshRate);
if(ctx->RendererType == Renderer_VULKAN) {
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
} else if(ctx->RendererType == Renderer_OPENGL) {
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
// Nothing in this code prevents using a core profile, but note that the shaders require a 4.0+ context
//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
if(PezGetConfig().Multisampling) {
glfwWindowHint(GLFW_SAMPLES, 4);
}
} else {
printf("ERROR - Unknown renderer type : %d\n", ctx->RendererType);
assert(false);
return(EXIT_FAILURE);
}
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
do {
ctx->MainWindow = glfwCreateWindow(PezGetConfig().Width, PezGetConfig().Height, "vkFluid", NULL, NULL);
if(!ctx->MainWindow) {
printf("Failed to create GLFW window!\n");
return(EXIT_FAILURE);
}
glfwSetKeyCallback(ctx->MainWindow, HandleKeyInputGLFW);
glfwSetCursorEnterCallback(ctx->MainWindow, HandleCursorEnterGLFW);
glfwSetMouseButtonCallback(ctx->MainWindow, HandleMouseButtonInputGLFW);
glfwSetCursorPosCallback(ctx->MainWindow, HandleMouseMoveGLFW);
glfwSetWindowSizeCallback(ctx->MainWindow, HandleWindowResizeGLFW);
renderer_t renderer = {};
if(ctx->RendererType == Renderer_OPENGL) {
renderer.Initialize = InitRendererOpenGL;
renderer.Update = PezUpdate;
renderer.RenderFrame = PezRenderOpenGL;
renderer.FinishFrame = FinalizeFrameOpenGL;
}
else if (ctx->RendererType == Renderer_VULKAN) {
// TODO(BH): Vulkan renderer stuff...
//renderer.Init = InitRendererVulkan;
//renderer.Update = UpdateVulkan;
//renderer.Render = RenderVulkan;
//renderer.FinalizeFrame = FinalizeFrameVulkan;
printf("ERROR: Vulkan renderer not yet implemented!\n");
assert(false);
}
else {
printf("ERROR: Unknown renderer type '%d'\n", ctx->RendererType);
assert(false);
}
renderer.Initialize();
double PrevTime = glfwGetTime();
ctx->FrameStats.StartTime = PrevTime;
ctx->StopRequested = false;
while(!ctx->StopRequested && !glfwWindowShouldClose(ctx->MainWindow)) {
glfwPollEvents();
double CurrentTime = glfwGetTime();
double DeltaTime = CurrentTime - PrevTime;
PrevTime = CurrentTime;
renderer.Update((float)DeltaTime);
renderer.RenderFrame();
renderer.FinishFrame();
if(++ctx->FrameStats.FrameCount > 100) {
ctx->FrameStats.FramesPerSecond = (float)ctx->FrameStats.FrameCount / (CurrentTime - ctx->FrameStats.StartTime);
ctx->FrameStats.FrameCount = 0;
ctx->FrameStats.StartTime = CurrentTime;
printf("FPS last 100 frames: %0.3f\n", ctx->FrameStats.FramesPerSecond);
}
}
pezSwShutdown();
glfwTerminate();
} while(false);
return(EXIT_SUCCESS);
}
<file_sep>/README.md
Simple 3D fluid simulation done purely in OpenGL by ping-ponging a layered framebuffer object / 3D texture.
At every frame, a deep shadow map is regenerated and a fragment shader performs raycasts against the 3D texture.
This code has been tested on CentOS 6 and RHEL 6, using a decent NVIDIA card and driver. I probably won't have time to help you if you send me "it won't build on my platform" questions, but please feel free to fork and make pull requests.
You can re-use this code in any way, but I'd like you to give me attribution. ([CC BY 3.0](http://creativecommons.org/licenses/by/3.0/))<file_sep>/CMakeLists.txt
cmake_minimum_required (VERSION 3.7)
if(POLICY CMP0015)
cmake_policy(SET CMP0015 NEW)
endif(POLICY CMP0015)
project (vkfluid)
set(PROGRAM_NAME vkfluid)
set(THIRDPARTY_DIR "${CMAKE_SOURCE_DIR}/ThirdParty")
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/CMakeModules;${CMAKE_MODULE_PATH}")
include(BHutils)
OPTION(VKFLUID_FULL_COMPILER_WARNINGS "Set to ON to enable full/verbose compiler warnings" OFF)
#FIXME(BH): Disable in optimized builds
ADD_DEFINITIONS(-DVKFLUID_LOGGING_ENABLED)
#FIXME(BH): Only for debug builds
ADD_DEFINITIONS(-DVKFLUID_WANT_ASSERTIONS)
ADD_DEFINITIONS(-DVKFLUID_DEBUG)
message(STATUS "GLFW3_DIR = ${GLFW3_DIR}")
OPTION(GLFW3_USE_STATIC "Set to ON to use GLFW static libs" OFF)
SET(GLFW3_USE_STATIC YES)
find_package(GLFW3 REQUIRED)
IF(GLFW3_USE_STATIC)
ADD_DEFINITIONS(-DGLFW3_USE_STATIC)
ENDIF()
message(STATUS "GLFW3_INCLUDE_DIR = '${GLFW3_INCLUDE_DIR}'")
INCLUDE_DIRECTORIES(${GLFW3_INCLUDE_DIR})
list(APPEND Invaders_LIBRARIES "${GLFW3_LIBRARY}")
file(GLOB VKFLUID_HEADERS *.h *.inl *.hpp *.hxx *.hh)
file(GLOB VKFLUID_SOURCES *.cpp *.c *.cc *.cxx)
IF(WIN32)
add_definitions(-DVKFLUID_WIN32)
ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS)
ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE)
ADD_DEFINITIONS(-D_WINDOWS)
ADD_DEFINITIONS(-D_WIN32)
ADD_DEFINITIONS(-DGLFW_EXPOSE_NATIVE_WIN32)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd47190 /wd4191")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
# OPTION(MSVC_USE_STATIC_RUNTIME "Use the static C runtime library" OFF)
# if(MSVC_USE_STATIC_RUNTIME)
# # Force static runtime libraries
# FOREACH(flag
# CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO
# CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_DEBUG_INIT
# CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO
# CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_DEBUG_INIT)
# STRING(REPLACE "/MD" "/MT" "${flag}" "${${flag}}")
# SET("${flag}" "${${flag}}")
# ENDFOREACH()
# endif()
# TODO(BH): Disable RTTI
OPTION(MSVC_ENABLE_CXX_EXCEPTIONS "Enable C++ exception handling" OFF)
if(NOT MSVC_ENABLE_CXX_EXCEPTIONS)
FOREACH(flag
CMAKE_CXX_FLAGS
CMAKE_C_FLAGS_RELEASE CMAKE_C_FLAGS_RELWITHDEBINFO
CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_DEBUG_INIT
CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_RELWITHDEBINFO
CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_DEBUG_INIT)
STRING(REPLACE "/EHsc" " " "${flag}" "${${flag}}")
SET("${flag}" "${${flag}}")
ENDFOREACH()
endif()
if(CMAKE_CXX_FLAGS MATCHES "/GR ")
string(REPLACE "/GR" "/GR-" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
message(STATUS "CMAKE_CXX_FLAGS matches /GR before end of string -- replaced...")
message(STATUS "")
endif()
if(CMAKE_CXX_FLAGS MATCHES "/EHsc ")
string(REPLACE "/EHsc" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
message(STATUS "CMAKE_CXX_FLAGS matches /EHsc before end of string -- replaced...")
message(STATUS "")
endif()
if(CMAKE_CXX_FLAGS MATCHES "/EHsc$")
string(REPLACE "/EHsc" " " CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
message(STATUS "CMAKE_CXX_FLAGS matches /EHsc at end of string -- replaced...")
message(STATUS "")
endif()
message(STATUS "CMAKE_CXX_FLAGS after possible REPLACE operation:")
message(STATUS "CMAKE_CXX_FLAGS='${CMAKE_CXX_FLAGS}'")
message(STATUS "")
# SET(EXECUTABLE_FLAGS WIN32)
SET(PLATFORM_LIBRARIES shell32.lib user32.lib imm32.lib gdi32.lib winmm.lib opengl32.lib mincore.lib version.lib)
elseif(UNIX AND NOT APPLE)
SET(EXECUTABLE_FLAGS "")
SET(PLATFORM_LIBRARIES pthread dl X11 Xrandr Xxf86vm Xcursor Xinerama) # Xm Xmu Xmuu )
add_definitions(-DVKFLUID_LINUX)
# ADD_DEFINITIONS(-Wno-missing-field-initializers)
# ADD_DEFINITIONS(-Wno-missing-braces)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-field-initializers")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-braces")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-rtti")
# Debug flags
if(VKFLUID_FULL_COMPILER_WARNINGS)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall")
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wextra -Wundef")
endif(CMAKE_COMPILER_IS_GNUCXX)
endif()
ENDIF()
find_package(OpenGL REQUIRED)
IF(${OPENGL_FOUND} MATCHES "TRUE")
INCLUDE_DIRECTORIES(${OPENGL_INCLUDE_DIR})
message(STATUS "OPENGL_INCLUDE_DIR = ${OPENGL_INCLUDE_DIR}")
ENDIF()
OPTION(GLEW_USE_STATIC "Set to ON to use GLEW static libs" OFF)
if(WIN32)
SET(GLEW_DIR "${THIRDPARTY_DIR}/glew/msvc2015-win64")
set(GLEW_USE_STATIC YES)
else(UNIX AND NOT APPLE)
#set(GLEW_USE_STATIC NO)
endif()
message(STATUS "GLEW_DIR = ${GLEW_DIR}")
find_package(GLEW REQUIRED)
include_directories(${GLEW_INCLUDE_DIR})
list(APPEND Invaders_LIBRARIES "${GLEW_LIBRARY}")
message(STATUS "GLEW_INCLUDE_DIR = ${GLEW_INCLUDE_DIR}")
message(STATUS "GLEW_LIBRARY = ${GLEW_LIBRARY}")
# Use FindVulkan module added with CMAKE 3.7
# if (NOT CMAKE_VERSION VERSION_LESS 3.7.0)
message(STATUS "Using module to find Vulkan")
find_package(Vulkan REQUIRED)
IF (NOT Vulkan_FOUND)
message(FATAL_ERROR "Could not find Vulkan library!")
ELSE()
message(STATUS ${Vulkan_LIBRARY})
include_directories(${Vulkan_INCLUDE_DIR})
ENDIF()
# include_directories($ENV{VULKAN_SDK}/include)
IF(WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVK_USE_PLATFORM_WIN32_KHR")
ELSEIF(UNIX AND NOT WIN32 AND NOT APPLE)
find_package(XCB REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVK_USE_PLATFORM_XCB_KHR")
ENDIF()
# Set preprocessor defines
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DNOMINMAX -D_USE_MATH_DEFINES")
# Clang specific stuff
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-switch-enum")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(${PROGRAM_NAME} ${EXECUTABLE_FLAGS}
${VKFLUID_SOURCES}
${VKFLUID_HEADERS}
)
target_link_libraries(${PROGRAM_NAME}
${GLFW3_LIBRARY}
${OPENGL_LIBRARY}
${GLEW_LIBRARY}
${Vulkan_LIBRARY}
${PLATFORM_LIBRARIES}
)
<file_sep>/build.linux
#!/bin/sh
make --no-print-directory -j`nproc` -C build/
<file_sep>/CMakeModules/FindGLFW3.cmake
# Locate GLFW3 library
# This module defines
# GLFW3_FOUND, if false, do not try to link to Lua
# GLFW3_LIBRARIES
# GLFW3_INCLUDE_DIR, where to find glfw3.h
# Set GLFW3_USE_STATIC=YES to link against the static version of GLFW
FIND_PATH(GLFW3_INCLUDE_DIR GLFW/glfw3.h
HINTS
$ENV{GLFW3_DIR}
${GLFW3_DIR}
PATH_SUFFIXES
include
# include/GLFW
# include/GLFW3
# include/glfw3
# include/glfw
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw # Fink
/opt/local # DarwinPorts
/opt/csw # Blastwave
/opt
)
FIND_LIBRARY(GLFW3_LIBRARY_RELEASE
NAMES libglfw.so glfw.dll glfw GLFW glfw3 GLFW3
HINTS
$ENV{GLFW3_DIR}
${GLFW3_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
FIND_LIBRARY(GLFW3_LIBRARY_DEBUG
NAMES libglfwd.so glfwd.dll glfwd GLFWd glfw3d GLFW3d
HINTS
$ENV{GLFW3_DIR}
${GLFW3_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
FIND_LIBRARY(GLFW3_STATIC_LIBRARY_RELEASE
NAMES libglfw3.a glfw3s.lib glfw3.lib glfw3 glfw3s glfws glfw
HINTS
$ENV{GLFW3_DIR}
${GLFW3_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
FIND_LIBRARY(GLFW3_STATIC_LIBRARY_DEBUG
NAMES libglfw3d.a glfw3sd.lib glfw3d.lib glfw3d glfw3sd glfwsd glfwd
HINTS
$ENV{GLFW3_DIR}
${GLFW3_DIR}
PATH_SUFFIXES lib64 lib
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local
/usr
/sw
/opt/local
/opt/csw
/opt
)
set(GLFW3_FOUND FALSE)
if(GLFW3_INCLUDE_DIR)
if(GLFW3_USE_STATIC)
if(GLFW3_STATIC_LIBRARY_RELEASE AND GLFW3_STATIC_LIBRARY_DEBUG)
SET(GLFW3_FOUND TRUE)
SET(GLFW3_LIBRARY debug ${GLFW3_STATIC_LIBRARY_DEBUG} optimized ${GLFW3_STATIC_LIBRARY_RELEASE})
elseif(GLFW3_STATIC_LIBRARY_RELEASE)
SET(GLFW3_FOUND TRUE)
SET(GLFW3_LIBRARY ${GLFW3_STATIC_LIBRARY_RELEASE})
endif()
else()#!GLFW3_USE_STATIC
if(GLFW3_LIBRARY_RELEASE AND GLFW3_LIBRARY_DEBUG)
SET(GLFW3_FOUND TRUE)
SET(GLFW3_LIBRARY debug ${GLFW3_LIBRARY_DEBUG} optimized ${GLFW3_LIBRARY_RELEASE})
elseif(GLFW3_LIBRARY_RELEASE)
SET(GLFW3_FOUND TRUE)
SET(GLFW3_LIBRARY ${GLFW3_LIBRARY_RELEASE})
endif()
endif()#GLFW3_USE_STATIC
endif()#GLFW3_INCLUDE_DIR
#INCLUDE(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set GLFW3_FOUND to TRUE if
# all listed variables are TRUE
#FIND_PACKAGE_HANDLE_STANDARD_ARGS(GLFW3 DEFAULT_MSG GLFW3_LIBRARY GLFW3_INCLUDE_DIR)
# MARK_AS_ADVANCED(GLFW3_INCLUDE_DIR GLFW3_LIBRARY)
| 775d6205f706fb10ee5de50c24341b4a0d2aa062 | [
"CMake",
"Markdown",
"Makefile",
"C++",
"Shell"
] | 9 | C++ | BrandonTheHamm/fluidsim | 2b86db39dd5e34573e43ad05505da1b4093edf8e | 54c149470dcc6e11df261536e087002e5b0babf5 |
refs/heads/main | <file_sep>import './footer.css';
import React from 'react';
export const Footer = () => {
return (
<footer className='footer'><img src="./podcast-player/listen-notes.png" /></footer>
);
};
<file_sep>import './list.css';
import React from 'react';
import { ResultItem } from './item';
export const ResultList = ({ podcasts, setSelectedPodcast }) => (
<ul className='result-list'>
{
podcasts.map(podcast =>
<ResultItem key={podcast.id} podcast={podcast} setSelectedPodcast={setSelectedPodcast} />)
}
</ul>
);
<file_sep>export const truncateString = (str, len) => {
if (str.length <= len) {
return str;
}
return str.slice(0, len - 3) + '...';
}
<file_sep>import React, {useState} from 'react';
import Search from './screens/search';
import Podcast from './screens/podcast';
import { Footer, Header, Main } from './components/layout';
const App = () => {
const [selectedPodcast, setSelectedPodcast] = useState();
return (
<>
<Header />
<Main>
{ selectedPodcast
? <Podcast id={selectedPodcast} setSelectedPodcast={setSelectedPodcast} />
: <Search setSelectedPodcast={setSelectedPodcast} />
}
</Main>
<Footer />
</>
)
}
export default App;
<file_sep>import './search-form.css';
import React, { useState } from 'react';
export const SearchForm = ({ handleKeyPress }) => {
const [searchTerm, setSearchTerm] = useState('');
return (
<form>
<input
className='search-box'
type='text'
placeholder='Search for a podcast'
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
onKeyPress={e => handleKeyPress(e)}
/>
</form>
)};
<file_sep>import './player.css';
import React, { useRef, useState } from 'react';
const Player = ({ podcast }) => {
const [playing, setPlaying] = useState(false);
const [progress, setProgress] = useState(0);
const player = useRef();
let interval;
const togglePlaying = () => {
setPlaying(() => {
if (playing) {
player.current.pause();
clearInterval(interval);
} else {
player.current.play();
interval = checkProgress();
}
return !playing;
})
}
const checkProgress = () => {
return setInterval(() => {
setProgress((player?.current?.currentTime / podcast?.audio_length_sec) * 100);
}, 1000);
}
return (
<div className='audio-player'>
<audio
ref={player}
src={podcast?.audio}
>
Your browser does not support the
<code>audio</code> element.
</audio>
<div className="podcast-details">
<h3>{podcast?.title}</h3>
{podcast?.description && <div dangerouslySetInnerHTML={{__html: podcast.description}} />}
</div>
<div className="progress">
<progress className="progress-bar" value={progress} min="0" max="100" />
</div>
<div className="controls">
<button className='shuffle-button' type="button" onClick={() => player.current.currentTime -= 30.0}>
- 30 secs
</button>
<button className='play-button' type="button" onClick={togglePlaying}>
{playing ? 'Pause' : 'Play'}
</button>
<button className='shuffle-button' type="button" onClick={() => player.current.currentTime += 30.0}>
+ 30 secs
</button>
</div>
</div>
)
}
export default Player;
<file_sep>import './item.css';
import React from 'react';
import { truncateString } from '../../utils/truncate-string';
export const ResultItem = ({ podcast, setSelectedPodcast }) => (
<li
className='result-item'
onClick={() => setSelectedPodcast(podcast.id)}
key={podcast.id}
>
<img className='podcast-thumbnail' src={podcast.thumbnail} />
<div className='podcast-details'>
<h3 className='podcast-title'>{podcast.title_original}</h3>
<div className='podcast-description'>
{truncateString(podcast.description_original, 250)}
</div>
<div class='podcast-meta'>
<span>Published by: {podcast.publisher_original} | </span>
{podcast.explicit_content && <span>Explicit | </span>}
<span>Last updated: {new Date(podcast.latest_pub_date_ms).toLocaleDateString()}</span>
</div>
</div>
</li>
);
<file_sep># Podcast Player in React
- [Create React App](https://reactjs.org/docs/create-a-new-react-app.html#create-react-app)
- [Listen Notes API documentation](https://www.listennotes.com/api/)
- [Powered by Listen Notes logo](https://www.dropbox.com/sh/259hp0metmemgbs/AACsZHZa1xhq7OkrycHmBK27a?dl=0) (required by Ts & Cs)
- [HTML5 Audio Element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio)
- [Styling](https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery/Video_player_styling_basics)
- [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)
- [Env vars in Create React App](https://create-react-app.dev/docs/adding-custom-environment-variables/)
- [Deployment](https://create-react-app.dev/docs/deployment/)
<file_sep>import './search.css';
import React, { useState } from 'react';
import { SearchForm } from '../components/search-form';
import { ResultList } from '../components/results/list';
const listenNotesApiUrl = 'https://listen-api.listennotes.com/api/v2';
const Search = ({ setSelectedPodcast }) => {
const [podcasts, setPodcasts] = useState([]);
const getPodcasts = async (e) => {
e.preventDefault();
const options = {
headers: {
'X-ListenAPI-Key': process.env.REACT_APP_LISTEN_NOTES_API_KEY,
}
};
const result = await fetch(`${listenNotesApiUrl}/search?q=${e.target.value}&sort_by_date=0&type=podcast`, options);
const parsed = await result.json();
setPodcasts(parsed.results);
}
const handleKeyPress = e => {
if(e.key === 'Enter'){
e.preventDefault();
getPodcasts(e);
}
}
return (!podcasts.length
? <>
<h3>Welcome!</h3>
<h1>Explore top podcasts</h1>
<SearchForm handleKeyPress={handleKeyPress} />
</>
: <>
<div className="info">
<button onClick={() => setPodcasts([])}>Back</button>
<h1>Results ({podcasts.length})</h1>
</div>
<ResultList setSelectedPodcast={setSelectedPodcast} podcasts={podcasts} />
</>
)
}
export default Search;
| 4c0ced6a979e82a7038afa22c7e1584134418de1 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | jjmax75/podcast-player | c7d1d9341b5047591214cd34f4a2ac46330b0ca1 | eff53e07b1d9fca02cc6fb83dbeec02b0e07a025 |
refs/heads/master | <file_sep>/*
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org/
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
var Promise = require("bluebird");
// Do not silently capture errors
Promise.onPossiblyUnhandledRejection(function(error){
throw error;
});
module.exports = function(elasticSearchUrl, elasticConfig, core, log) {
var _exports = {};
var sdhData = Promise.promisifyAll(core.data);
//TODO: just for testing
var elasticsearch = require('elasticsearch');
var elasticClient = new elasticsearch.Client({
host: elasticSearchUrl,
log: 'debug',
defer: function () {
return Promise.defer();
}
});
/**
* Store a document in elastic search
* @param index Index where to store the document
* @param type Type of the docuement
* @param data Object containing the data to store as a document
* @param params Parameters of the "data" to store
* @param options Extra options such as transformations
* @returns {*}
*/
var addDocument = function(index, type, data, params, options) {
if(!options) {
options = {};
}
if(!options.trans) {
options.trans = {}; // Transformations
}
var body = {};
for(var param in data) {
if(params.indexOf(param) != -1) {
var name = param;
var value = data[param];
if(options.trans[param]) { //Transform the parameter
var trans = options.trans[param];
if(trans.name) {
name = trans.name;
}
}
body[type + "_" + name] = value;
}
}
return elasticClient.index({
index: index,
type: type,
body: body
});
};
var addAll = function(list, index, type, params, options) {
var prom = list.map(function(data) {
return addDocument(index, type, data, params, options);
});
return Promise.all(prom);
};
var addAllObjects = function(map, index, type, params, options) {
var proms = [];
for(var key in map) {
if(map.hasOwnProperty(key)) {
var data = map[key];
proms.push(addDocument(index, type, data, params, options));
}
}
return Promise.all(proms);
};
var createMapping = function(index, type, props) {
var properties = {};
for(var name in props) {
if(props.hasOwnProperty(name)) {
var p = props[name];
properties[type + "_" + name] = {
type: (p.type ? p.type : "string"),
analyzer: (p.analyzer ? p.analyzer : "simple")
}
}
}
return elasticClient.indices.putMapping({
index: index,
type: type,
body: {
properties: properties
}
});
};
var makeMultiMatchQuery = function(index, fields, text, options) {
if(!options) options = {};
return elasticClient.search({
index: index,
body: {
query: {
"multi_match": {
"query": text,
"type": "best_fields",
"fields": fields,
"tie_breaker": 0.3,
"fuzziness": "AUTO"
}
},
"size": (options.size ? options.size : 10),
"from": (options.from ? options.from : 0),
"sort":{
"_score":{
"order":"desc"
}
}
}
}).then(function(result) {
return result.hits.hits;
}).catch(function(e) {
log.error(e);
return null;
});
};
for(var i = 0; i < elasticConfig.length; i++) {
var index = elasticConfig[i];
// Create index mappings operations
for(var m = 0; m < index.mappings.length; m++) {
var mapping = index.mappings[m];
for(var o = 0; o < mapping.operations.length; o++) {
var operation = mapping.operations[o];
//Add mapping class to search parameters
var searchParams = [];
for(var s = 0; s < operation.search.length; s++) {
searchParams.push(mapping.class + "_" + operation.search[s]);
}
_exports[operation.name] = makeMultiMatchQuery.bind(undefined, index.index, searchParams);
}
}
// Create index general operations
for(o = 0; o < index.operations.length; o++) {
operation = index.operations[o];
_exports[operation.name] = makeMultiMatchQuery.bind(undefined, index.index, operation.search);
}
}
// ----------------------------------------------------------
// ------------------- PUBLIC METHODS -----------------------
// ----------------------------------------------------------
_exports.fillWithData = function() {
var promises = [];
for(var i = 0; i < elasticConfig.length; i++) {
var index = elasticConfig[i];
var promise;
// Delete index if exists
promise = elasticClient.indices.exists({
index: index.index
}).then(function(index, exists) {
if(exists) {
return elasticClient.indices.delete({
index: index.index
});
}
}.bind(null, index)).then(function(index) {
return elasticClient.indices.create({
index: index.index
});
}.bind(null, index));
// Create index mappings
promise = promise.then(function() {
var mappingProms = [];
for(var m = 0; m < index.mappings.length; m++) {
var mapping = index.mappings[m];
mappingProms.push(createMapping(index.index, mapping.class, mapping.attributes));
}
return Promise.all(mappingProms);
}.bind(null, index));
// Fill with data
promise = promise.then(function(index) {
var fillDataProms = [];
for(var m = 0; m < index.mappings.length; m++) {
var mapping = index.mappings[m];
var dataMethod;
// Check that the method provided exists in core.data and promisify it
if(typeof core.data[mapping.data.method] === 'function') {
dataMethod = Promise.promisify(core.data[mapping.data.method])
}
// Call the method to retrieve the data and then add it to elestic search
var prom = dataMethod().then(function(index, mapping, data) {
return addAll(data, index.index, mapping.class, mapping.data.attributes, mapping.data.config);
}.bind(null, index, mapping));
fillDataProms.push(prom);
}
return Promise.all(fillDataProms);
}.bind(null, index));
promises.push(promise);
}
return Promise.all(promises);
};
return _exports;
};<file_sep>/*
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org/
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';
var Promise = require("bluebird");
var directives = {};
//TODO: export this method to the core root
module.exports = function(log) {
var _exports = {};
var isInteger = function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
/**
*
* @param pos The number of the capture group (starting from cero)
* @param replaceMethod Optional. Regexp to find a value to replace or a function to execute.
* @param replaceWith Optional. The value to replace with.
* @constructor
*/
var RgxSubstr = function RgxSubstr(pos, replaceMethod, replaceWith) {
this.pos = pos;
if(replaceMethod instanceof RegExp && replaceWith) {
this.replaceRegexp = replaceRegexp;
this.replaceWith = replaceWith;
} else if (typeof replaceMethod === 'function') {
this.replaceFunction = replaceMethod;
}
}
RgxSubstr.prototype.getValueInMatch = function(rgxResult, extraInfo) {
var value = rgxResult[this.pos + 1];
if(this.replaceRegexp) {
return (value + "").replace(this.replaceRegexp, this.replaceWith);
} else if(this.replaceFunction) {
return this.replaceFunction(value, extraInfo);
} else {
return value;
}
}
_exports.RgxSubstr = RgxSubstr;
_exports.registerDirective = function(pattern, operation, mappings) {
try {
var regex = (pattern instanceof RegExp ? pattern : new RegExp(pattern));
var regexStr = regex.toString();
} catch(e) {
log.error("Invalid RegExp for pattern: " + e);
return false;
}
// Check that the pattern does not exist
if(directives[regexStr]) {
return false;
}
if(typeof operation !== 'function') {
log.error("Invalid operation for directive");
return false;
}
// Add the directive to the list
try {
directives[regexStr] = {
regex: regex,
operation: operation,
mappings: mappings
}
} catch(e) {
log.error("Invalid RegExp for pattern: " + e);
return false;
}
};
var replaceMappings = function(mappings, matches, extraInfo) {
var newObj = mappings;
if (mappings && typeof mappings === 'object') {
newObj = mappings instanceof Array ? [] : {};
for (var i in mappings) {
if(mappings[i] instanceof RgxSubstr) {
newObj[i] = mappings[i].getValueInMatch(matches, extraInfo)
} else {
newObj[i] = replaceMappings(mappings[i], matches, extraInfo);
}
}
}
return newObj;
};
_exports.handleMessage = function(msg, cb, extraInfo) {
for(var regexStr in directives) {
var directive = directives[regexStr];
// Reset the lastIndex just in case we have been given a global regexp
directive.regex.lastIndex = 0;
// Execute the regexp and create the arguments array for the operation given the mappings
var substrings = directive.regex.exec(msg) //The substrings starts from index 1, 0 is the matched string
if(substrings) {
var mappings = directive.mappings;
var operationArgs = [ cb ];
if(mappings) {
operationArgs = operationArgs.concat(replaceMappings(mappings, substrings, extraInfo));
}
// Execute operation after all the promisses (if any) have been fullfilled
Promise.map(operationArgs, function(arg) {
if(typeof arg === 'object') {
return Promise.props(arg); //If is a map object, make sure all the properties have been fullfilled
} else {
return arg;
}
}).then(function(argValues) {
directive.operation.apply(null, argValues);
});
return true;
}
}
return false;
};
return _exports;
}<file_sep>/*
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org/
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';
var Promise = require("bluebird");
var request = require("request");
// Do not silently capture errors
Promise.onPossiblyUnhandledRejection(function(error){
throw error;
});
module.exports = function(core, log) {
//TODO: adapt all methods to receive parameters instead of a msg and then try to obtain the parameters from it
/* PRIVATE */
var helpme = function helpme(callback) { //TODO: move this method to the interface
var data = [], corePatterns = {};
for (var pat in corePatterns) {
data.push(
{
title: pat,
text: corePatterns[pat].description,
'thumb': "https://pixabay.com/static/uploads/photo/2013/07/12/18/09/help-153094_960_720.png",
'link': "http://botEndpointOrSomethingSimilar/api/resource/elelele"
}
);
}
callback ({
'title': "Help Information",
'description': "This is the core bot basic methods help information",
'data': data
});
};
var metric = function metric(callback, mid, options) {
var getSDHMetricInfo = Promise.promisify(core.data.getSDHMetricInfo);
var getSDHMetric = Promise.promisify(core.data.getSDHMetric);
try {
var params = {};
if(options.aggr) {
params['aggr'] = options.aggr;
}
if(options.max) {
params['max'] = options.max;
} else if(options.format !== 'image') {
params['max'] = 1;
}
if(options.from) {
var from = Date.create(options.from);
if(from.isValid()) {
params['from'] = from.format("{yyyy}-{MM}-{dd}");
} else {
throw new core.errors.InvalidArgument("'"+options.from+"' is an invalid date");
}
}
if(options.to) {
var to = Date.create(options.to);
if(to.isValid()) {
params['to'] = to.format("{yyyy}-{MM}-{dd}");
} else {
throw new core.errors.InvalidArgument("'"+options.to+"' is an invalid date");
}
}
// It to is < than from, swap them
if(params['from'] && params['to'] && params['to'] < params['from']) {
var tmp = params['from'];
params['from'] = params['to'];
params['to'] = tmp;
}
getSDHMetricInfo(mid).then(function(metricInfo) {
if(options.aggr && !(options.aggr in metricInfo.aggr)) {
throw new core.errors.InvalidArgument("Aggregator " + options.aggr + " can't be used with metric " + metricInfo.id);
}
if(options.param) {
if(metricInfo.params.length === 0 || metricInfo.params[0] == null) {
throw new core.errors.InvalidArgument("Metric not found. The given metric does not require parameters.")
}
if(options.param.substr(0, 6) === "sdhid:") { //The id of the user has been specified from the interface
if(metricInfo.params.indexOf("uid") === -1) {
throw new core.errors.InvalidArgument("Metric not found. The given metric does not require uid parameter.")
}
params['uid'] = options.param.substring(6);
} else { // Try to find out the parameter of the metric
var expectedParamType = metricInfo.params[0];
var searchMethod, searchType;
switch (expectedParamType) {
case 'uid': searchMethod = core.search.users; searchType = "user"; break;
case 'prid': searchMethod = core.search.products; searchType = "product"; break;
case 'pjid': searchMethod = core.search.projects; searchType = "project"; break;
case 'rid': searchMethod = core.search.repositories; searchType = "repository"; break;
default:
throw new core.errors.InvalidArgument("I don't know the type of paremeter for the metric");
}
// Find in the search engine the entity that fits best with the text correspondin to the parameter
return searchMethod(options.param).then(function(results) {
if(results && results.length > 0) {
var type = results[0]._type;
params[expectedParamType] = results[0]._source[type+"_id"];
} else {
throw new core.errors.InvalidArgument("Couldn't find any information about "+searchType+" '" + options.param + "'");
}
})
}
}
}).then(function() {
if(options.format === 'image') { // Return an image
var chartRequestParams = {
"chart": "LinesChart",
"metrics": [{
"id": mid
}],
"configuration": {
"height": 300,
"area": true,
"xlabel": '',
"ylabel": '',
},
"width": 700
}
for(var param in params) {
chartRequestParams.metrics[0][param] = params[param];
}
core.data.getMetricsChart(chartRequestParams, callback);
} else { // Return a text representation
getSDHMetric(mid, params).asCallback(callback);
}
}).catch(function(e) {
callback(e);
})
} catch(e) {
callback(e);
}
};
var getMetricsAbout = function getMetricsAbout(callback, text) {
var getSDHMetricInfo = Promise.promisify(core.data.getSDHMetricInfo);
core.search.metrics(text).then(function(results) {
var metrics = results.map(function(entry) {
var id = entry._source.metric_id;
return getSDHMetricInfo(id); //TODO: reflect?
});
Promise.all(metrics).asCallback(callback);
});
};
var view = function view(callback, vid, options) {
var getSDHViewInfo = Promise.promisify(core.data.getSDHViewInfo);
var getSDHView = Promise.promisify(core.data.getSDHView);
try {
var params = {};
if(options.from) {
var from = Date.create(options.from);
if(from.isValid()) {
params['from'] = from.format("{yyyy}-{MM}-{dd}");
} else {
throw new core.errors.InvalidArgument("'"+options.from+"' is an invalid date");
}
}
if(options.to) {
var to = Date.create(options.to);
if(to.isValid()) {
params['to'] = to.format("{yyyy}-{MM}-{dd}");
} else {
throw new core.errors.InvalidArgument("'"+options.to+"' is an invalid date");
}
}
getSDHViewInfo(vid).then(function(viewInfo) {
if(options.param) {
if(viewInfo.params.length === 0 || viewInfo.params[0] == null) {
throw new core.errors.InvalidArgument("Metric not found. The given metric does not require parameters.")
}
if(options.param.substr(0, 6) === "sdhid:") { //The id of the user has been specified from the interface
if(viewInfo.params.indexOf("uid") === -1) {
throw new core.errors.InvalidArgument("Metric not found. The given metric does not require uid parameter.")
}
params['uid'] = options.param.substring(6);
} else { // Try to find out the parameter of the view
var expectedParamType = viewInfo.params[0];
var searchMethod;
switch (expectedParamType) {
case 'uid': searchMethod = core.search.users; break;
case 'prid': searchMethod = core.search.products; break;
case 'pjid': searchMethod = core.search.projects; break;
case 'rid': searchMethod = core.search.repositories; break;
default:
throw new core.errors.InvalidArgument("I don't know the type of paremeter for the view");
}
// Find in the search engine the entity that fits best with the text correspondin to the parameter
return searchMethod(options.param).then(function(results) {
if(results && results.length > 0) {
var type = results[0]._type;
params[expectedParamType] = results[0]._source[type+"_id"];
} else {
throw new core.errors.InvalidArgument("Couldn't find any information about "+searchType+" '" + options.param + "'");
}
})
}
}
}).then(function() {
getSDHView(vid, params).asCallback(callback);
}).catch(function(e) {
callback(e);
})
} catch(e) {
callback(e);
}
};
var getViewsAbout = function getViewsAbout(callback, text) {
var getSDHViewInfo = Promise.promisify(core.data.getSDHViewInfo);
core.search.views(text).then(function(results) {
var views = results.map(function(entry) {
var id = entry._source.view_id;
return getSDHViewInfo(id); //TODO: reflect?
});
Promise.all(views).asCallback(callback);
});
};
var product = function product(callback, text) {
var returnData = function(data) {
if(!data) {
callback (new core.errors.InvalidArgument("I could not find product \"" + text + "\""));
} else {
callback (null, data);
}
};
core.search.products(text).then(function(results) {
var products = results.map(function(entry) {
return sdhProductsByID[entry._source.product_id];
});
callback (null, returnData(products[0]));
});
};
var project = function project(callback, text) {
var returnData = function(data) {
if(!data) {
callback (new core.errors.InvalidArgument("I could not find project \"" + text + "\""));
} else {
callback (null, data);
}
};
core.search.projects(text).then(function(results) {
var projects = results.map(function(entry) {
return sdhProjectsByID[entry._source.project_id];
});
callback (null, returnData(projects[0]));
});
};
var repo = function repo(callback, text) {
var returnData = function(data) {
if(!data) {
callback (new core.errors.InvalidArgument("I could not find repository \"" + text + "\""));
} else {
callback (null, data);
}
};
core.search.repositories(text).then(function(results) {
var repositories = results.map(function(entry) {
return sdhReposByID[entry._source.repo_id];
});
callback (null, returnData(repositories[0]));
});
};
var member = function member(callback, text) {
var returnData = function(data) {
if(!data) {
callback (new core.errors.InvalidArgument("I could not find member \"" + text + "\""));
} else {
callback (null, data);
}
};
if(text.substr(0, 6) === "sdhid:") {
var sdhId = text.substring(6);
returnData(sdhUsersByID[sdhId]);
} else {
core.search.users(text).then(function(results) {
var users = results.map(function(entry) {
return sdhUsersByID[entry._source.user_id];
});
returnData(users[0]);
});
}
};
var allMetrics = function allMetrics(callback) {
core.data.getSDHMetrics(callback);
};
var allViews = function allViews(callback) {
core.data.getSDHViews(callback);
};
var allOrgs = function allOrgs(callback) {
core.data.getSDHOrganizations(callback);
};
var allProducts = function allProducts(callback) {
core.data.getSDHProducts(callback);
};
var allProjects = function allProjects(callback) {
core.data.getSDHProjects(callback);
};
var allRepos = function allRepos(callback) {
core.data.getSDHRepositories(callback);
};
var allMembers = function allMembers(callback) {
core.data.getSDHMembers(callback);
};
return {
helpme: helpme,
allMetrics: allMetrics,
getMetricsAbout: getMetricsAbout,
allViews: allViews,
getViewsAbout: getViewsAbout,
allOrgs: allOrgs,
allProducts: allProducts,
allProjects: allProjects,
allMembers: allMembers,
allRepos: allRepos,
product: product,
project: project,
member: member,
repo: repo,
metric: metric,
view: view
};
}
<file_sep># SDH-CORE-BOT
[](http://www.apache.org/licenses/LICENSE-2.0.txt)
[](https://badge.fury.io/js/sdh-core-bot)
This is the Smart Developer Hub Core Bot.
Smart Developer Hub project.
For more information, please visit the [Smart Developer Hub website](http://www.smartdeveloperhub.org/).
SDH-CORE-BOT is distributed under the Apache License, version 2.0.
## Installation
```
npm install sdh-core-bot
```
## Configuration
To configure the data stored in Elastic Search and the methods provided in core.search configure the file "elasticConfig.json".
```
[
{
"index": "entities", // Name of the index
"mappings": [ // Elastic search mappings
{
"class": "repo", // Document type
"attributes": {
"id": {
"type": "string", // Type of the data
"analyzer": "simple" // Analyzer of Elastic Search to use
},
/* more */
},
"data": { // What data to store in Elastic Search
"method": "getSDHRepositories", // Method in core.data to call (without arguments) to obtain the data
"attributes": ["rid", "name"], // Attributes of the array of objects returned by the method to store in ES
"config": {
"trans":{ // Apply a transformation to the data to store
"rid":{ // The transformation applies to the "rid" parameter
"name":"id" // The transformation changes the name of the parameter ("rid") to "id"
}
}
}
},
"operations": [ // Search operations exported to core.search
{
"name": "repositories", // Export an operation called core.search.repositories
"search": ["id^2", "name"] // Search using parameters id and name, give double weight to id
},
/* more */
]
},
],
"operations": [ //Same as inside he mappings, but in this case search should be "<class>_<attribute>"
{
"name": "general", // Operation called core.search.general
"search": ["org_id", "product_*"] // Search in org's id parameter and all the parameters of product
},
/* more /*
]
},
/* more */
]
``` | 86e285bef70846f99df847bf0109d6688470ba5e | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | SmartDeveloperHub/sdh-core-bot | a16dad35b0ad16a2ba2613a5b6ad607c8b935132 | aed2bdd1548e33e37d612a833f253acb0e85fede |
refs/heads/master | <repo_name>nambirajanraj/MovieCruiser<file_sep>/Frontend/src/app/modules/movie/movie.module.ts
import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import {MovieRouterModule} from '../movie/movie.router.module';
import { ThumbnailComponent } from './components/thumbnail/thumbnail.component';
import { HttpClientModule } from '@angular/common/http';
import {MovieService} from './movie.service';
import { ContainerComponent } from './components/container/container.component';
import { WatchListComponent } from './components/watch-list/watch-list.component';
import { TmdbContainerComponent } from './components/tmdb-container/tmdb-container.component';
import { MovieDialogComponent } from './components/movie-dialog/movie-dialog.component';
import { SearchMovieComponent } from './components/search/search.component';
import { SharedModule } from '../shared/shared.module';
import {TokenInterceptorService} from './token-interceptor.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
declarations: [ThumbnailComponent,SearchMovieComponent, ContainerComponent, WatchListComponent, TmdbContainerComponent, MovieDialogComponent],
imports: [
CommonModule,
HttpClientModule,
MovieRouterModule,
SharedModule
],
providers:[MovieService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi: true
}
],
entryComponents:[MovieDialogComponent],
exports:[ThumbnailComponent, ContainerComponent,SearchMovieComponent, WatchListComponent, TmdbContainerComponent, MovieDialogComponent]
})
export class MovieModule { }
<file_sep>/MovieCruiserAuthenticationService/src/main/java/com/stackroute/moviecruiser/repository/UserRepository.java
package com.stackroute.moviecruiser.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.stackroute.moviecruiser.model.User;
@Repository
public interface UserRepository extends JpaRepository<User, String>{
User findByUserIdAndPassword(String userId,String password);
}
<file_sep>/MovieCrusierService/src/main/java/com/stackroute/moviecrusierserverapp/controller/MovieController.java
package com.stackroute.moviecrusierserverapp.controller;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.stackroute.moviecrusierserverapp.domain.Movie;
import com.stackroute.moviecrusierserverapp.exception.MovieAlreadyExistsException;
import com.stackroute.moviecrusierserverapp.exception.MovieNotFoundException;
import com.stackroute.moviecrusierserverapp.service.MovieService;
import io.jsonwebtoken.Jwts;
@RestController
@RequestMapping(path="/api/movieservice")
@CrossOrigin
public class MovieController {
private MovieService movieService;
@Autowired
public MovieController(MovieService movieService) {
super();
this.movieService = movieService;
}
@PostMapping
public ResponseEntity<?> saveNewMovie(@RequestBody final Movie movie, final ServletRequest req, final ServletResponse res) {
ResponseEntity<?> responseEntity;
try {
final HttpServletRequest request=(HttpServletRequest)req;
final String authHeader=request.getHeader("authorization");
final String token=authHeader.substring(7);
final String userId=Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody().getSubject();
movie.setUserId(userId);
this.movieService.saveMovie(movie);
responseEntity = new ResponseEntity<Movie>(movie, HttpStatus.CREATED);
} catch (MovieAlreadyExistsException e) {
// TODO Auto-generated catch block
responseEntity = new ResponseEntity<String>("{ \"message\": \"" + e.getMessage() + "\"}", HttpStatus.CONFLICT);
}
return responseEntity;
}
@PutMapping(path="/{id}")
public ResponseEntity<?> updateMovie(@PathVariable("id") final Integer id, @RequestBody Movie movie) {
ResponseEntity<?> responseEntity;
try {
final Movie fetchedMovie = movieService.updateMovie(movie);
responseEntity = new ResponseEntity<Movie>(fetchedMovie, HttpStatus.OK);
}
catch (MovieNotFoundException e) {
responseEntity = new ResponseEntity<String>("{ \"message\": \"" + e.getMessage() + "\"}", HttpStatus.NOT_FOUND);
}
return responseEntity;
}
@DeleteMapping(path = "/{id}")
public ResponseEntity<?> deleteMovieById(@PathVariable("id") final int id) {
ResponseEntity<?> responseEntity;
try {
movieService.deleteMovieById(id);
responseEntity = new ResponseEntity<String>("Movie deleted successfully", HttpStatus.OK);
}
catch (MovieNotFoundException e) {
responseEntity = new ResponseEntity<String>("{ \"message\": \"" + e.getMessage() + "\"}", HttpStatus.NOT_FOUND);
}
return responseEntity;
}
@GetMapping(path = "/{id}")
public ResponseEntity<?> fetchMovieById(@PathVariable("id") final int id) {
ResponseEntity<?> responseEntity;
Movie movie=null;
try {
movie = movieService.getMovieById(id);
responseEntity = new ResponseEntity<Movie>(movie, HttpStatus.OK);
}
catch (MovieNotFoundException e) {
responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.NOT_FOUND);
}
return responseEntity;
}
@GetMapping
public ResponseEntity<?> fetchAllMovies(final ServletRequest req, final ServletResponse res)
{
ResponseEntity<?> responseEntity;
final HttpServletRequest request=(HttpServletRequest)req;
final String authHeader=request.getHeader("authorization");
final String token=authHeader.split(" ")[1];
final String userId=Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody().getSubject();
final List<Movie> movieList=this.movieService.getMyMovies(userId);
responseEntity=new ResponseEntity<List<Movie>>(movieList,HttpStatus.OK);
return responseEntity;
}
}
<file_sep>/MovieCruiserAuthenticationService/src/main/java/com/stackroute/moviecruiser/service/SecurityTokenGenerator.java
package com.stackroute.moviecruiser.service;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.stackroute.moviecruiser.model.User;
public interface SecurityTokenGenerator {
Map<String,String> generateTokens(User user);
}
<file_sep>/MovieCrusierService/src/main/java/com/stackroute/moviecrusierserverapp/service/MovieService.java
package com.stackroute.moviecrusierserverapp.service;
import java.util.List;
import com.stackroute.moviecrusierserverapp.domain.Movie;
import com.stackroute.moviecrusierserverapp.exception.MovieAlreadyExistsException;
import com.stackroute.moviecrusierserverapp.exception.MovieNotFoundException;
public interface MovieService {
public Movie getMovieById(final Integer id) throws MovieNotFoundException;
public boolean saveMovie(final Movie movie)throws MovieAlreadyExistsException;
public Movie updateMovie(final Movie movie)throws MovieNotFoundException;
public List<Movie> getMyMovies(String userId);
public boolean deleteMovieById(final Integer id)throws MovieNotFoundException;
}
<file_sep>/MovieCruiserAuthenticationService/src/main/java/com/stackroute/moviecruiser/service/UserService.java
package com.stackroute.moviecruiser.service;
import com.stackroute.moviecruiser.exception.UserAlreadyExistException;
import com.stackroute.moviecruiser.exception.UserNotFoundException;
import com.stackroute.moviecruiser.model.User;
public interface UserService {
public boolean saveUser(User user)throws UserAlreadyExistException;
public User findByUserIdAndPassword(String userId,String password)throws UserNotFoundException;
}
<file_sep>/build.sh
#!/bin/bash
cd MovieCruiserAuthenticationService/
source ./env-variable.sh
mvn clean package
docker build -t user-app .
cd ..
cd MovieCrusierService/
source ./env-variable.sh
mvn clean package
docker build -t movie-app .
cd ..
<file_sep>/project.sh
cd MovieCruiserAuthenticationService
source ./env-variable.sh
cd ..
cd MovieCrusierService
source ./env-variable.sh
cd ..
| 35e9cfefb1dc5997f0a44769f11b2e42bbead358 | [
"Java",
"TypeScript",
"Shell"
] | 8 | TypeScript | nambirajanraj/MovieCruiser | c9217e0da9f9acf7dd3ba78f25745f59ceb26b1d | 662daec34f439b6dfb2ba7168e7fb7061501372f |
refs/heads/master | <repo_name>ixmedia/sequel_bulk_attributes<file_sep>/lib/sequel_bulk_attributes.rb
module Sequel
module Plugins
module BulkAttributes
def self.apply(model, opts={}, &block)
model.plugin(:instance_hooks)
end
module ClassMethods
private
def def_bulk_setter(opts, &block)
association_module_def(:"#{opts[:name]}=", opts, &block) unless opts[:read_only]
end
# Add a getter that checks the join table for matching records and
# a setter that deletes from or inserts into the join table.
def def_many_to_many(opts)
super
def_bulk_setter(opts) do |list|
cur = send(opts[:name])
if cur
cur.reject{ |v| v == "" }
end
instance_variable_set("@_#{opts[:name]}_add", list.reject{ |v| cur.detect{ |v1| v.to_i == v1.pk } }) if cur and list
instance_variable_set("@_#{opts[:name]}_remove", cur.reject{ |v| list.detect{ |v1| v.pk == v1.to_i } }) if cur and list
cur.replace(list)
name = "#{opts[:name]}".singularize
after_save_hook do
instance_variable_get("@_#{opts[:name]}_remove").each do |record|
send("remove_#{name}", record) if record
end
instance_variable_get("@_#{opts[:name]}_add").each do |record|
send("add_#{name}", record) if record && !record.empty?
end
end
end
end
# Add a getter that checks the association dataset and a setter
# that updates the associated table.
def def_one_to_many(opts)
super
def_bulk_setter(opts) do |list|
cur = send(opts[:name])
instance_variable_set("@_#{opts[:name]}_add", list.reject{ |v| cur.detect{ |v1| v.to_i == v1.pk } })
instance_variable_set("@_#{opts[:name]}_remove", cur.reject{ |v| list.detect{ |v1| v.pk == v1.to_i } })
cur.replace(list)
name = "#{opts[:name]}".singularize
after_save_hook do
instance_variable_get("@_#{opts[:name]}_remove").each do |record|
send("remove_#{name}", record) if record
end
instance_variable_get("@_#{opts[:name]}_add").each do |record|
send("add_#{name}", record) if record && !record.empty?
end
end
end
end
end
module InstanceMethods
end
module DatasetMethods
end
end
end
end
| 2a1d188aad07f65c82ddf46c2f356e6aa9c0bab7 | [
"Ruby"
] | 1 | Ruby | ixmedia/sequel_bulk_attributes | 9dde64f7fb2257a357c729f0ce5125f8589d4a1e | 04bd09c997ebe49a6b24a6cc87b13aaadce6f027 |
refs/heads/master | <repo_name>zuev720/ra-2.1<file_sep>/src/App.js
import arrayProjects from './components/Portfolio/arrayProjects.js';
import {Portfolio} from './components/Portfolio/Portfolio.jsx';
function App() {
return (
<Portfolio myWorks={arrayProjects}/>
);
}
export default App;
<file_sep>/src/components/Portfolio/ProjectList/ProjectList.jsx
import React from 'react';
import PropTypes from 'prop-types';
const shortid = require('shortid');
export function ProjectList(props) {
const filter = props.filter;
const myWorks = (filter === 'All') ? props.myWorks : props.myWorks.filter((elem) => elem.category === filter);
return (<div className={'ProjectList'}>{
myWorks.map((elem, index) => <img key={shortid.generate()} className={'work-image'} src={elem.img} alt={elem.category}/>)
}</div>);
}
ProjectList.protoTypes = {
filter: PropTypes.string.isRequired,
myWorks: PropTypes.array.isRequired,
};
<file_sep>/src/components/Portfolio/Portfolio.jsx
import {Component} from 'react';
import Toolbar from './ToolBar/Toolbar.jsx';
import {ProjectList} from './ProjectList/ProjectList.jsx';
import PropTypes from 'prop-types';
export class Portfolio extends Component {
constructor(props) {
super(props);
this.myWorks = props.myWorks;
this.state = { selected: 'All'};
this.filters = ['All', 'Websites', 'Flayers', 'Business Cards'];
this.onClick = this.onClick.bind(this);
}
onClick(evt) {
const filter = evt.currentTarget.textContent;
this.setState(() => ({selected: filter}));
}
render() {
return (
<div className={'Portfolio'}>
<Toolbar filters={this.filters} onClick={this.onClick} />
<ProjectList filter={this.state.selected} myWorks={this.myWorks} />
</div>
)
}
}
Portfolio.protoTypes = {
myWorks: PropTypes.array.isRequired,
state: PropTypes.object.isRequired,
filters: PropTypes.array.isRequired,
onClick: PropTypes.func.isRequired,
};
<file_sep>/src/components/Portfolio/ToolBar/Toolbar.jsx
import React from 'react';
import PropTypes from 'prop-types';
export default function Toolbar(props) {
const filters = props.filters;
const filterClick = props.onClick;
return (<div className="Toolbar">{
filters.map((elem, index) => {
return (
<button className={'button-filter'} key={index} onClick={filterClick}>{elem}</button>
)
})
}</div>);
}
Toolbar.protoTypes = {
filters: PropTypes.array.isRequired,
filterClick: PropTypes.func.isRequired,
};
| 64874103b6f27382428831087e7c5c55c2a6078f | [
"JavaScript"
] | 4 | JavaScript | zuev720/ra-2.1 | 656d58b591a5c4eeb2b082269f134c7a624316d4 | e5819d2ffe01c8bc786b0e490906f1dacf0e12fe |
refs/heads/master | <file_sep>var request = require('request');
function dumbfunc(error, response, result)
{
console.log(result);
}
request('http://google.com/', dumbfunc);
<file_sep>var http = require('http');
var fs = require('fs');
var port = process.env.PORT || 8080;
var server = http.createServer(function(request, response) {
try {
var file = fs.readFileSync("."+request.url+(request.url.charAt(request.url.length-1) == '/' ? "index.html" :""));
response.writeHead(200, {"Content-type": "text/html"});
response.end(file);
}catch (err)
{response.writeHead(404, {"Content-type":"text/html"});
response.end("404 Not Found");}
});
server.listen(port);
| d6214b1280de946d3bb4af1bff7ef6b8baa6ff2c | [
"JavaScript"
] | 2 | JavaScript | qiuqiuu/bitstarter | 40aa455d99befb86d815bc80552d9da385baa691 | ee0119a1eaa2672776b204ef3f7dfbad595a8dba |
refs/heads/master | <repo_name>benjiin/Trafficlight<file_sep>/Trafficlight/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trafficlight
{
class Program
{
static void Main(string[] args)
{
Crossroads crossroads = new Crossroads();
if (crossroads.SignalN.Color == Signal.GREEN)
{
Console.WriteLine("N: Green");
}
else if (crossroads.SignalN.Color == Signal.RED)
{
Console.WriteLine("N: Red");
}
if (crossroads.SignalS.Color == Signal.GREEN)
{
Console.WriteLine("S: Green");
}
else if (crossroads.SignalS.Color == Signal.RED)
{
Console.WriteLine("S: Red");
}
if (crossroads.SignalW.Color == Signal.GREEN)
{
Console.WriteLine("W: Green");
}
else if (crossroads.SignalW.Color == Signal.RED)
{
Console.WriteLine("W: Red");
}
if (crossroads.SignalO.Color == Signal.GREEN)
{
Console.WriteLine("O: Green");
}
else if (crossroads.SignalO.Color == Signal.RED)
{
Console.WriteLine("O: Red");
}
crossroads.Switch();
Console.WriteLine("-");
if (crossroads.SignalN.Color == Signal.GREEN)
{
Console.WriteLine("N: Green");
}
else if (crossroads.SignalN.Color == Signal.RED)
{
Console.WriteLine("N: Red");
}
if (crossroads.SignalS.Color == Signal.GREEN)
{
Console.WriteLine("S: Green");
}
else if (crossroads.SignalS.Color == Signal.RED)
{
Console.WriteLine("S: Red");
}
if (crossroads.SignalW.Color == Signal.GREEN)
{
Console.WriteLine("W: Green");
}
else if (crossroads.SignalW.Color == Signal.RED)
{
Console.WriteLine("W: Red");
}
if (crossroads.SignalO.Color == Signal.GREEN)
{
Console.WriteLine("O: Green");
}
else if (crossroads.SignalO.Color == Signal.RED)
{
Console.WriteLine("O: Red");
}
Console.ReadLine();
}
}
}
<file_sep>/Trafficlight/Crossroads.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trafficlight
{
class Crossroads
{
Signal SignalN = new Signal();
}
}
<file_sep>/Trafficlight/Signal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trafficlight
{
class Signal
{
string GREEN = "Green";
string Color = string.Empty;
public Signal()
{
this.Color = "Green";
}
}
}
| 970b9c94dfd850c3daf2b7c39871b6b12f892f8a | [
"C#"
] | 3 | C# | benjiin/Trafficlight | 5f8a29ee2c46ca26b9fc9873fb83864248275125 | 1063cd8ecfe7d5d8a2453cc88c69cca0d99a2a6b |
refs/heads/master | <repo_name>kimizatt/react-1-afternoon<file_sep>/src/components/Topics/FilterString.js
import React, {Component} from 'react';
export default class FilterString extends Component {
constructor () {
super()
this.state = {
items: ['dog', 'apples', 'tree', 'ant', 'donut', 'dragon', 'timer', 'kite'],
userInput: '',
filteredItems: []
}
}
handleChange(val) {
this.setState ({userInput: val})
}
filterItems(userInput) {
let items = this.state.items
let filteredItems = []
for(let i = 0; i<items.length; i++) {
if(items[i].includes(userInput) ) {
filteredItems.push(items[i])
}
}
this.setState({filteredItems: filteredItems})
}
render() {
return (
<div className="puzzleBox filterStringPB">
<h4>Filter String</h4>
<span className="puzzleText"> Name: {JSON.stringify(this.state.items, null, 10)}</span>
<input className="inputLine" onChange = {(e) => this.handleChange(e.target.value)} />
<button className= "confirmationButton" onClick={() => this.filterItems(this.state.userInput) }> Filter </button>
<span className= "resultBox FilterStringRB"> Filtered Names: {JSON.stringify(this.state.filteredItems)}</span>
</div>
)
}
}<file_sep>/src/App.js
import React, { Component } from 'react';
import './index.css';
// import TopicBrowser from './components/TopicBrowser/TopicBrowser'
//Topics
import EvenAndOdd from '../src/components/Topics/EvenAndOdd'
import FilterObject from '../src/components/Topics/FilterObject'
import FilterString from '../src/components/Topics/FilterString'
import Palindrome from '../src/components/Topics/Palindrome'
import Sum from '../src/components/Topics/Sum'
class App extends Component {
render() {
return (
<div>
<EvenAndOdd />
<FilterObject />
<FilterString />
<Palindrome />
<Sum />
</div>
)
}
}
export default App;
<file_sep>/src/components/Topics/FilterObject.js
import React, {Component} from 'react';
export default class FilterObject extends Component {
constructor() {
super()
this.state = {
person: [
{
name: 'Elizabeth',
age: 20,
hobby: 'Dancing'
},
{
name: 'Jane',
age: 22,
hairColor: 'blonde'
},
{
name: 'Lydia',
hobby: 'Flirting'
}
],
userInput: '',
filteredArray: []
}
}
handleChange(val) {
this.setState({ userInput: val});
}
filteredArray(prop) {
let person = this.state.person
let filteredArray = []
for(let i =0; i<person.length; i++) {
if(person[i].hasOwnProperty(prop)) {
filteredArray.push(person[i])
}
}
this.setState({ filteredArray: filteredArray})
}
render() {
return (
<div className="puzzleBox filterObjectPB">
<h4>Filter Object</h4>
<span className="puzzleText">Original: { JSON.stringify(this.state.person, null, 10) }</span>
<input className = "inputLine" onChange={(e) => this.handleChange(e.target.value)}/>
<button className = "confirmationButton" onClick={() =>this.filteredArray(this.state.userInput) }>Filter</button>
<span className="resultsBox filterObjectRB">Filtered: { JSON.stringify(this.state.filteredArray, null, 10)} </span>
</div>
)
}
} | 6f0d9087a603b5c2a7a5c68c454366b4e579c2b4 | [
"JavaScript"
] | 3 | JavaScript | kimizatt/react-1-afternoon | 4b63e39a50f7f521562f3bea1b65350cf5250b4d | 35e12349bd04ceda0a963b08a1ef3ce9853a3638 |
refs/heads/master | <file_sep>"""
A data preprocesser.
TODO Fix error on dtype conversion
"""
import numpy as np
import tensorflow as tf
def normalize(data, old_min=0, old_max=255):
"""
Transform data with range [old_min, old_max] to [0, 1].
"""
return np.divide((data - old_min), (old_max-old_min), dtype=np.float)
def grayscale(data, axis):
"""
Transform and RGB image to grayscale image.
"""
return int(np.mean(data, axis=axis))
def augment(image):
"""
Perform data augmentation on given image.
TODO Randomize augmentation more by using random combinations.
"""
augmented_images = [ image ]
# Rotation
rotation_angle = np.random.random() / 9
augmented_images.append(tf.image.rot90(image, k=rotation_angle))
augmented_images.append(tf.image.rot90(image, k=-1 * rotation_angle))
# Brightness
delta = np.random.random() / 2
augmented_images.append(tf.image.adjust_brightness(image, delta=delta))
augmented_images.append(tf.image.adjust_brightness(image, delta=-1 * delta))
# TODO Contrast, Hue, Gamma, Saturation
# Crop
central_frac = np.random.random() / 10
tf.image.central_crop(image, central_fraction=central_frac)
return augmented_images
<file_sep>"""
Defines operations to reshape data to use it in the model.
"""
def int_to_onehot(int_label, label_size=10, dtype=np.uint8):
"""
Reshape integer labels to one-hot vectors.
"""
onehot_label = np.zeros(label_size, dtype=dtype)
onehot_label[int_label] = 1
return onehot_label
def reshape_image(image):
"""
Reshape 2D image (height, width) to 3D image (height, width, channel).
"""
return np.expand_dims(image, axis=2)
<file_sep>"""
A Tensorflow data loader for images and labels compressed in gzip format.
"""
import gzip
import numpy as np
import tensorflow as tf
class DataLoader:
"""
A loader for a gzipped file to prepare data for preprocessing.
"""
def __init__(self,
n_images,
image_h=28,
image_w=28,
n_channels=1,
pixel_depth=255):
"""
:param n_images: Number of images in the compressed file.
:param image_h: The height of the image in the compressed file.
:param image_w: The width of the image in the compressed file.
:param n_channels: The number of channels of the image in the compressed
file.
"""
self.N_IMAGES = n_images
self.IMAGE_H = image_h
self.IMAGE_W = image_w
self.N_CHANNELS = n_channels
self.PIXEL_DEPTH = pixel_depth
def extract_data(self, filename):
"""
Extract file with given filename and return extracted data.
:param filename: Name of the file with gzip format containing images.
The filename should include the extension.
:returns: A list of 4D tensors (image_id, image_h, image_w, n_channels).
"""
HEADER_SIZE = 16
print ('[extract_data] Extracting gzipped data from ', filename)
with gzip.open(filename) as bytestream:
bytestream.read(HEADER_SIZE)
buf = bytestream.read(self.IMAGE_H * self.IMAGE_W * self.N_IMAGES)
data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
data = data.reshape(self.N_IMAGES, self.IMAGE_H,
self.IMAGE_W, self.N_CHANNELS)
print ('[extract_data] Finished extraction of ', filename)
return data
def extract_label(self, filename):
"""
Extract the labels into a vector of np.int64 label ids.
:param filename: Name of the file with gzip format containing labels.
The filename should include the extension.
"""
HEADER_SIZE = 8
print ('[extract_label] Extracting gzipped data from ', filename)
with gzip.open(filename=filename) as bytestream:
bytestream.read(HEADER_SIZE)
buf = bytestream.read(1 * self.N_IMAGES)
# type cast from uint8 to np.int64 to work in tensorflow framework
labels = np.frombuffer(buffer=buf, dtype=np.uint8).astype(np.int64)
print ('[extract_label] Finished extraction of ', filename)
return labels
class MNISTDataLoader(DataLoader):
"""
A data loader for MNIST dataset by <NAME>.
http://yann.lecun.com/exdb/mnist/
"""
def __init__(self, n_images):
"""
:param n_images: Number of images in the compressed file.
"""
super().__init__(n_images=n_images,
image_h=28,
image_w=28,
n_channels=1,
pixel_depth=255)
<file_sep>#! /usr/bin/env python3
"""
A sample code to display how each module can be used.
"""
from data_loader import MNISTDataLoader
def main():
loader = MNISTDataLoader(1)
data = loader.extract_data('data/mnist/train-images-idx3-ubyte.gz')
data = loader.rescale_data(data)
labels = loader.extract_label('data/mnist/train-labels-idx1-ubyte.gz')
if __name__ == '__main__':
main()
| 008934955d2f1c9b48cbe9280c8cecac84cd359d | [
"Python"
] | 4 | Python | seungjaeryanlee/tensorflow-study | 5dff398b74d29297e0ee86f36bbb44b2030af682 | 3395e2c96f544b036cf2d74e8eb5cdb9bdb34d69 |
refs/heads/master | <repo_name>thangout/cancer-platform<file_sep>/src/views/Login.jsx
import React, { Component } from 'react';
// import logo from './logo.svg';
import '../App.css';
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import TextField from 'material-ui/TextField';
import AppBar from 'material-ui/AppBar';
import Paper from 'material-ui/Paper';
const style = {
height: 350,
width: 400,
margin: 20,
textAlign: 'center',
display: 'inline-block',
padding: 20 +'px',
paddingTop: 40 +'px',
};
class Login extends Component {
render() {
return (
<MuiThemeProvider>
<div className="App">
<AppBar
title="SammenHoldet"
iconClassNameRight="muidocs-icon-navigation-expand-more"/>
<Paper style={style} zDepth={1}>
<h1>Login</h1>
<TextField
hintText="Name"
/><br />
<br />
<TextField type="<PASSWORD>"
hintText="<PASSWORD>"
/><br />
<br />
<RaisedButton label="Log in" href="./#/dash" />
<RaisedButton label="Register" href="./#/register" />
</Paper>
<p className="App-intro">
</p>
</div>
</MuiThemeProvider>
);
}
}
export default Login;
<file_sep>/src/views/Timeline.jsx
import React, { Component } from 'react';
// import logo from './logo.svg';
import '../App.css';
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import TextField from 'material-ui/TextField';
import AppBar from 'material-ui/AppBar';
import Paper from 'material-ui/Paper';
import Timeline from 'react-visjs-timeline'
import BigCalendar from 'react-big-calendar';
import 'react-big-calendar/lib/css/react-big-calendar.css'
import moment from 'moment';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
const style = {
height: 400,
width: 100 + '%',
margin: 20,
textAlign: 'center',
display: 'inline-block',
padding: 20 +'px',
};
const style2 = {
width: 100 + '%',
margin: 20,
textAlign: 'center',
display: 'inline-block',
padding: 20 +'px',
};
const options = {
width: '100%',
height: '200px',
stack: true,
showMajorLabels: true,
showCurrentTime: true,
zoomMin: 1000000,
type: 'background',
format: {
minorLabels: {
minute: 'h:mma',
hour: 'ha'
}
}
}
const items = [
{
start: new Date(2017,3, 20),
end: new Date(2017, 3 , 21), // end is optional
content: 'Fifth chemo therapy, http://cancer-donate.dk',
},
{
start: new Date(2017, 3, 1, 16, 0, 0, 0),
end: new Date(2017, 3 , 3, 17, 30, 0, 0), // end is optional
content: 'Chemo 4',
},
]
const events = [
{
start: new Date(2017, 2, 26, 10, 30, 0, 0),
end: new Date(2017, 2 , 26, 12, 30, 0, 0), // end is optional
title: 'First chemo',
desc: 'Walk a dog',
},
{
start: new Date(2017, 2, 27, 12, 0, 0, 0),
end: new Date(2017, 2 , 27, 13, 30, 0, 0), // end is optional
title: 'Lunch',
desc: 'Making pasta and pesto',
},
{
start: new Date(2017, 2, 31, 16, 0, 0, 0),
end: new Date(2017, 2 , 31, 17, 30, 0, 0), // end is optional
title: 'Shopping at Netto',
desc: 'Buy groceries at Netto',
},
{
start: new Date(2017, 3, 1, 9, 0, 0, 0),
end: new Date(2017, 3 , 1, 10, 30, 0, 0), // end is optional
title: 'Chemo 4',
desc: 'Buy groceries at Netto',
},
// {
// start: new Date(2017, 3, 31),
// end: new Date(2017, 3, 31), // end is optional
// title: 'Second chemo',
// },
]
BigCalendar.momentLocalizer(moment); // or globalizeLocalizer
class TimelineS extends Component {
render() {
return (
<MuiThemeProvider>
<div className="App">
<AppBar
title="SammenHoldet"
iconClassNameRight="muidocs-icon-navigation-expand-more"/>
<div className="container">
<Paper style={style} zDepth={1}>
<h1>Treatment overview</h1>
<Timeline
options={options}
items={items}
/>
<br/>
<FloatingActionButton>
<ContentAdd />
</FloatingActionButton>
</Paper>
<Paper style={style2} zDepth={1}>
<h1>Task overview</h1>
<BigCalendar
selectable
events={events}
defaultView='week'
defaultDate={new Date()}
/>
</Paper>
</div>
</div>
</MuiThemeProvider>
);
}
}
export default TimelineS;
<file_sep>/src/views/Register.jsx
import React, { Component } from 'react';
// import logo from './logo.svg';
import '../App.css';
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import TextField from 'material-ui/TextField';
import AppBar from 'material-ui/AppBar';
import Paper from 'material-ui/Paper';
import Toggle from 'material-ui/Toggle';
const style = {
width: 400,
margin: 20,
textAlign: 'center',
display: 'inline-block',
padding: 20 +'px',
paddingTop: 40 +'px',
};
const styles = {
block: {
maxWidth: 250,
},
toggle: {
marginBottom: 16,
},
thumbOff: {
backgroundColor: '#ffcccc',
},
trackOff: {
backgroundColor: '#ff9d9d',
},
thumbSwitched: {
backgroundColor: 'red',
},
trackSwitched: {
backgroundColor: '#ff9d9d',
},
labelStyle: {
color: 'red',
},
};
class Register extends Component {
render() {
return (
<MuiThemeProvider>
<div className="App">
<AppBar
title="SammenHoldet"
iconClassNameRight="muidocs-icon-navigation-expand-more"/>
<Paper style={style} zDepth={1}>
<h1>Register</h1>
<TextField
hintText="Name"
defaultValue=""
/><br />
<br />
<TextField
hintText="Last name"
defaultValue=""
/><br />
<br />
<TextField
hintText="Age"
defaultValue=""
/><br />
<br />
<Toggle
label="Have children"
style={styles.toggle}
/>
<Toggle
label="Live in a house"
style={styles.toggle}
/>
<Toggle
label="Own a pet"
style={styles.toggle}
/>
<RaisedButton label="Register " href="./#/dash" />
</Paper>
</div>
</MuiThemeProvider>
);
}
}
export default Register;
<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { Route, HashRouter } from 'react-router-dom'
import Login from './views/Login'
import Dashboard from './views/Dashboard'
import NewTask from './views/NewTask'
import NewTaskConfirm from './views/NewTaskConfirm'
import Timeline from './views/Timeline'
import Profile from './views/Profile'
import Register from './views/Register'
// ReactDOM.render(
// <App />,
// document.getElementById('root')
// );
ReactDOM.render((
<HashRouter>
<div>
<Route path="/" component={App}/>
{/* add the routes here */}
<Route path="/login" component={Login}/>
<Route path="/dash" component={Dashboard}/>
<Route path="/newtask" component={NewTask}/>
<Route path="/newtaskconfirm" component={NewTaskConfirm}/>
<Route path="/timeline" component={Timeline}/>
<Route path="/profile" component={Profile}/>
<Route path="/register" component={Register}/>
</div>
</HashRouter>
), document.getElementById('root'))
| fccfdd638b4ccc9995612715aa8b637b2bcb841d | [
"JavaScript"
] | 4 | JavaScript | thangout/cancer-platform | 97b854336b58a0ed74d8f4cb0480613b743e21b0 | 4bc484caf7a8e7e95f80333a627e778acf05dae4 |
refs/heads/master | <file_sep>SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE `guilds` (
`guild` BIGINT NOT NULL,
`mute_role` BIGINT DEFAULT NULL,
`modlog` BIGINT DEFAULT NULL,
`keeproles` BOOL DEFAULT false,
`on_join_channel` BIGINT DEFAULT NULL,
`on_leave_channel` BIGINT DEFAULT NULL,
`on_join_message` TEXT COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`on_leave_message` TEXT COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`color_on_join` BOOL DEFAULT false,
`on_delete_channel` BIGINT DEFAULT NULL,
`on_edit_channel` BIGINT DEFAULT NULL,
`on_delete_embed` BOOL DEFAULT false,
`on_edit_embed` BOOL DEFAULT false,
`on_edit_message` TEXT COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`on_delete_message` TEXT COLLATE utf8mb4_unicode_ci DEFAULT NULL,
--`on_bulk_delete` TEXT COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`automute` BOOL DEFAULT false,
`automute_limit` TINYINT DEFAULT 10,
`automute_time` TIME DEFAULT NULL,
`dailygachi` BIGINT DEFAULT NULL,
PRIMARY KEY (`guild`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `automute_whitelist` (
`role` BIGINT NOT NULL,
`guild` BIGINT NOT NULL,
PRIMARY KEY (`role`),
KEY (`guild`),
FOREIGN KEY (`role`) REFERENCES `roles` (`id`)
ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE `prefixes` (
`prefix` VARCHAR(30) COLLATE utf8mb4_unicode_ci DEFAULT "!" NOT NULL,
`guild` BIGINT NOT NULL,
PRIMARY KEY (`prefix`, `guild`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `colors` (
`id` BIGINT NOT NULL,
`name` VARCHAR(127) COLLATE utf8mb4_unicode_ci NOT NULL,
`value` MEDIUMINT UNSIGNED NOT NULL,
`lab_l` FLOAT NOT NULL,
`lab_a` FLOAT NOT NULL,
`lab_b` FLOAT NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`id`) REFERENCES `roles` (`id`)
ON DELETE CASCADE,
KEY (`value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `command_blacklist` (
`id` INT NOT NULL AUTO_INCREMENT,
`command` TEXT DEFAULT NULL,
`type` TINYINT NOT NULL,
`user` BIGINT DEFAULT NULL,
`role` BIGINT DEFAULT NULL,
`channel` BIGINT DEFAULT NULL,
`guild` BIGINT DEFAULT NULL,
PRIMARY KEY (`id`),
KEY (`user`),
KEY (`role`),
KEY (`guild`),
KEY (`channel`)
) ENGINE=MyISAM;
CREATE TABLE `bot_staff` (
`user` BIGINT NOT NULL,
`auth_level` TINYINT NOT NULL,
PRIMARY KEY `user_id` (`user`)
) ENGINE=MyISAM;
CREATE TABLE `banned_users` (
`user` BIGINT NOT NULL,
`reason` TEXT NOT NULL,
PRIMARY KEY `user_id` (`user`)
) ENGINE=InnoDB;
CREATE TABLE `guild_blacklist` (
`guild` BIGINT NOT NULL,
`reason` TEXT NOT NULL,
PRIMARY KEY (`guild`)
) ENGINE=InnoDB;
-- https://stackoverflow.com/a/8048494/6046713 restrict row count
CREATE TABLE `messages` (
`shard` SMALLINT DEFAULT NULL,
`guild` BIGINT DEFAULT NULL,
`channel` BIGINT DEFAULT NULL,
`user` VARCHAR(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` BIGINT NOT NULL,
`message` TEXT COLLATE utf8mb4_unicode_ci,
`message_id` BIGINT NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`attachment` TEXT COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`message_id`),
KEY (`guild`),
KEY (`channel`),
KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `polls` (
`guild` BIGINT NOT NULL,
`title` TEXT COLLATE utf8mb4_unicode_ci NOT NULL,
`strict` BOOL DEFAULT false,
`message` BIGINT NOT NULL,
`channel` BIGINT NOT NULL,
`expires_in` datetime DEFAULT NULL,
`ignore_on_dupe` BOOL DEFAULT false,
`multiple_votes` BOOL DEFAULT false,
`max_winners` SMALLINT UNSIGNED DEFAULT 1,
PRIMARY KEY `message_id` (`message`),
KEY (`guild`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `emotes` (
`name` TEXT COLLATE utf8mb4_unicode_ci NOT NULL,
`emote` VARCHAR(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`guild` BIGINT DEFAULT NULL,
PRIMARY KEY (`emote`),
KEY (`guild`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `pollEmotes` (
`poll_id` BIGINT NOT NULL,
`emote_id` VARCHAR(20) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`poll_id`,`emote_id`),
FOREIGN KEY (`poll_id`) REFERENCES `polls`(`message`)
ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`emote_id`) REFERENCES `emotes`(`emote`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `giveaways` (
`guild` BIGINT NOT NULL,
`title` TEXT COLLATE utf8mb4_unicode_ci NOT NULL,
`message` BIGINT NOT NULL,
`channel` BIGINT NOT NULL,
`winners` SMALLINT NOT NULL,
`expires_in` datetime DEFAULT NULL,
PRIMARY KEY `message_id` (`message`),
KEY (`guild`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `timeouts`(
`guild` BIGINT NOT NULL,
`user` BIGINT NOT NULL,
`reason` TEXT COLLATE utf8_unicode_ci NOT NULL,
`expires_on` datetime NOT NULL,
PRIMARY KEY (`user`, `guild`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `timeout_logs` (
`guild` BIGINT NOT NULL,
`user` BIGINT NOT NULL,
`reason` TEXT COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`guild`, `user`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `join_leave`(
`user_id` BIGINT NOT NULL,
`at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`guild` BIGINT NOT NULL,
`value` TINYINT NOT NULL,
PRIMARY KEY (`user`, `guild`)
) ENGINE=InnoDB;
CREATE TABLE `role_granting` (
`user_role` BIGINT NOT NULL,
`user` BIGINT NOT NULL,
`role` BIGINT NOT NULL,
`guild` BIGINT NOT NULL,
PRIMARY KEY (`user_role`, `role`, `user`),
KEY (`guild`),
FOREIGN KEY (`user_role`) REFERENCES `roles`(`id`)
ON DELETE CASCADE,
FOREIGN KEY (`role`) REFERENCES `roles`(`id`)
ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE `mention_stats`(
`guild` BIGINT NOT NULL,
`role` BIGINT NOT NULL,
`role_name` VARCHAR(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`amount` INT DEFAULT 1,
PRIMARY KEY (`guild`, `role`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `users` (
`id` BIGINT NOT NULL,
-- `username` VARCHAR(64) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `roles` (
`id` BIGINT NOT NULL,
`guild` BIGINT NOT NULL,
PRIMARY KEY (`id`),
KEY (`guild`)
) ENGINE=InnoDB;
CREATE TABLE `userRoles` (
`user` BIGINT NOT NULL,
`role` BIGINT NOT NULL,
PRIMARY KEY (`user`,`role`),
FOREIGN KEY (`role`) REFERENCES `roles`(`id`)
ON DELETE CASCADE
) ENGINE=InnoDB;
CREATE TABLE `automute_blacklist` (
`channel` BIGINT NOT NULL,
`guild` BIGINT NOT NULL,
PRIMARY KEY (`channel`),
KEY (`guild`)
) ENGINE=InnoDB;
CREATE TABLE `nn_text` (
`message` TEXT COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `last_seen_users` (
`user` BIGINT NOT NULL,
`username` VARCHAR(40) COLLATE utf8mb4_unicode_ci NOT NULL,
`guild` BIGINT DEFAULT 0,
`last_seen` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user`, `guild`),
KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `activity_log` (
`user` BIGINT NOT NULL,
game VARCHAR(128) COLLATE utf8mb4_unicode_ci NOT NULL,
time INT DEFAULT 0,
PRIMARY KEY (`user`, `game`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `command_stats` (
`parent` VARCHAR(40) COLLATE utf8_unicode_ci NOT NULL,
`cmd` VARCHAR(200) COLLATE utf8_unicode_ci DEFAULT 0,
`uses` BIGINT DEFAULT 0,
UNIQUE KEY (`parent`, `cmd`),
KEY (`uses`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `mute_roll_stats` (
`guild` BIGINT NOT NULL,
`user` BIGINT NOT NULL,
`wins` TINYINT UNSIGNED DEFAULT 0,
`games` TINYINT UNSIGNED DEFAULT 1,
`current_streak` TINYINT UNSIGNED DEFAULT 0,
`biggest_streak` TINYINT UNSIGNED DEFAULT 0,
PRIMARY KEY (`guild`, `user`),
KEY (`wins`),
KEY (`games`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `pokespawns` (
`guild` BIGINT NOT NULL,
`name` VARCHAR(20) COLLATE utf8_unicode_ci NOT NULL,
`count` MEDIUMINT UNSIGNED DEFAULT 1,
PRIMARY KEY (`guild`, `name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `todo` (
`time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`completed_at` TIMESTAMP NULL DEFAULT NULL,
`completed` BOOL DEFAULT FALSE,
`todo` TEXT COLLATE utf8mb4_unicode_ci,
`priority` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `temproles` (
`role` BIGINT NOT NULL,
`user` BIGINT NOT NULL,
`guild` BIGINT NOT NULL,
`expires_at` TIMESTAMP NOT NULL,
PRIMARY KEY (`role`, `user`)
) ENGINE=InnoDB;
CREATE TABLE `changelog` (
`id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`changes` TEXT COLLATE utf8mb4_unicode_ci,
`time` TIMESTAMP DEFAULT UTC_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
------------------------
-- UNDER CONSTRUCTION --
------------------------
<file_sep>"""
MIT License
Copyright (c) 2017 s0hvaperuna
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.
"""
import asyncio
import logging
import os
import random
import re
from collections import deque
from functools import partial
from math import floor
import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
from bot import player
from bot.bot import command, cooldown, group
from bot.converters import TimeDelta
from bot.downloader import Downloader
from bot.globals import ADD_AUTOPLAYLIST, DELETE_AUTOPLAYLIST
from bot.globals import Auth
from bot.player import get_track_pos, MusicPlayer
from bot.playlist import Playlist
from bot.song import Song
from utils.utilities import mean_volume, search, parse_seek, send_paged_message
try:
import aubio
except ImportError:
aubio = None
logger = logging.getLogger('audio')
terminal = logging.getLogger('terminal')
class MusicPlayder:
def __init__(self, bot, stop_state):
raise NotImplementedError('Deprecated')
self.play_next_song = asyncio.Event() # Trigger for next song
self.right_version = asyncio.Event() # Determines if right version be played
self.right_version_playing = asyncio.Event()
self.voice = None # Voice channel that this is connected to
self.current = None # Current song
self.channel = None # Channel where all the automated messages will be posted to
self.server = None
self.activity_check = None
self.gachi = bot.config.gachi
self.bot = bot
self.audio_player = None # Main audio loop. Gets set when summon is called in :create_audio_task:
self.volume = self.bot.config.default_volume
self.playlist = Playlist(bot, download=True)
self.autoplaylist = bot.config.autoplaylist
self.volume_multiplier = bot.config.volume_multiplier
self.messages = deque()
self.stop = stop_state
def is_playing(self):
if self.voice is None or self.current is None or self.player is None:
return False
return not self.player.is_done()
def reload_voice(self, voice_client):
self.voice = voice_client
if self.player:
self.player.player = voice_client.play_audio
self.player._resumed.clear()
self.player._connected.set()
async def websocket_check(self):
terminal.debug("Creating websocket check loop")
logger.debug("Creating websocket check loop")
while self.voice is not None:
try:
self.voice.ws.ensure_open()
assert self.voice.ws.open
except:
terminal.debug("Voice websocket is %s, reconnecting" % self.voice.ws.state_name)
logger.debug("Voice websocket is %s, reconnecting" % self.voice.ws.state_name)
await self.bot.reconnect_voice_client(self.voice.channel.server)
await asyncio.sleep(4)
finally:
await asyncio.sleep(1)
def create_audio_task(self):
self.audio_player = self.bot.loop.create_task(self.play_audio())
self.activity_check = self.bot.loop.create_task(self._activity_check())
# self.bot.loop.create_task(self.websocket_check())
@property
def player(self):
return self.current.player
def on_stop(self):
if self.right_version.is_set():
if self.current.seek:
return
elif not self.current.seek:
self.bot.loop.call_soon_threadsafe(self.right_version_playing.set)
return
elif self.current.seek:
return
self.bot.loop.create_task(self.delete_current())
self.bot.loop.call_soon_threadsafe(self.play_next_song.set)
self.playlist.on_stop()
async def delete_current(self):
if self.current is not None and self.bot.config.delete_after and not self.playlist.in_list(self.current.webpage_url):
await self.current.delete_file()
async def wait_for_right_version(self):
await self.right_version_playing.wait()
async def wait_for_not_empty(self):
await self.playlist.not_empty.wait()
async def set_mean_volume(self, file):
try:
db = await asyncio.wait_for(mean_volume(file, self.bot.loop, self.bot.threadpool,
duration=self.current.duration), timeout=20, loop=self.bot.loop)
if db is not None and abs(db) >= 0.1:
volume = self._get_volume_from_db(db)
self.current.player.volume = volume
except asyncio.TimeoutError:
logger.debug('Mean volume timed out')
except asyncio.CancelledError:
pass
async def _wait_for_next_song(self):
try:
await asyncio.wait_for(self.wait_for_not_empty(), 1, loop=self.bot.loop)
logger.debug('Play was called on empty playlist. Waiting for download')
self.current = await self.playlist.next_song()
if self.current is not None:
logger.debug(str(self.current.__dict__))
else:
logger.debug('Current is None')
except asyncio.TimeoutError:
logger.debug('Got TimeoutError. adding_songs = {}'.format(self.playlist.adding_songs))
if self.autoplaylist and not self.playlist.adding_songs:
song_ = await self.playlist.get_from_autoplaylist()
if song_ is None:
terminal.warning('None returned from get_from_autoplaylist. Waiting for next song')
return None
else:
self.current = song_
else:
try:
await asyncio.wait_for(self.wait_for_not_empty(), 5, loop=self.bot.loop)
except asyncio.TimeoutError:
return None
await self.playlist.not_empty.wait()
self.current = await self.playlist.next_song()
return self.current
def _get_volume_from_db(self, db):
rms = pow(10, db / 20) * 32767
return 1 / rms * self.volume_multiplier
async def _activity_check(self):
async def stop():
await self.stop(self)
self.voice = None
while True:
await asyncio.sleep(60)
if self.voice is None:
return await stop()
users = self.voice.channel.voice_members
users = list(filter(lambda x: not x.bot, users))
if not users:
await self.say('No voice activity. Disconnecting')
await stop()
return
async def play_audio(self):
while True:
self.play_next_song.clear()
if self.voice is None:
break
if self.current is None or not self.current.seek:
if self.playlist.peek() is None:
if self.autoplaylist:
self.current = await self.playlist.get_from_autoplaylist()
else:
continue
else:
self.current = await self.playlist.next_song()
if self.current is None:
continue
logger.debug('Next song is {}'.format(self.current))
logger.debug('Waiting for dl')
try:
await asyncio.wait_for(self.current.on_ready.wait(), timeout=6,
loop=self.bot.loop)
except asyncio.TimeoutError:
self.playlist.playlist.appendleft(self.current)
continue
logger.debug('Done waiting')
if not self.current.success:
terminal.error('Download unsuccessful')
continue
if self.current.filename is not None:
file = self.current.filename
elif self.current.url != 'None':
file = self.current.url
else:
terminal.error('No valid file to be played')
continue
logger.debug('Opening file with the name "{0}" and options "{1.before_options}" "{1.options}"'.format(file, self.current))
self.current.player = self.voice.create_ffmpeg_player(file,
after=self.on_stop,
before_options=self.current.before_options,
options=self.current.options)
if self.bot.config.auto_volume and not self.current.seek and isinstance(file, str) and not self.current.is_live:
volume_task = asyncio.ensure_future(self.set_mean_volume(file))
else:
volume_task = None
self.current.player.volume = self.volume
if not self.current.seek:
dur = get_track_pos(self.current.duration, 0)
s = 'Now playing **{0.title}** {1} with volume at {2:.0%}'.format(self.current, dur, self.current.player.volume)
if self.current.requested_by:
s += ' enqueued by %s' % self.current.requested_by
await self.say(s, self.current.duration)
logger.debug(self.player)
self.current.player.start()
logger.debug('Started player')
await self.change_status(self.current.title)
logger.debug('Downloading next')
await self.playlist.download_next()
if self.gachi and not self.current.seek and random.random() < 0.01:
await self.prepare_right_version()
self.current.seek = False
await self.play_next_song.wait()
if volume_task is not None:
volume_task.cancel()
volume_task = None
self.right_version_playing.clear()
async def prepare_right_version(self):
if self.gachi:
return
self.bot.loop.call_soon_threadsafe(self.right_version.set)
try:
await asyncio.wait_for(self.wait_for_right_version(), self.current.duration * 0.8)
except asyncio.TimeoutError:
pass
file = self._get_right_version()
if file is None:
return
vol = self._get_volume_from_db(await mean_volume(file, self.bot.loop, self.bot.threadpool, duration=self.current.duration))
self.current.player.stop()
self.current.player = self.voice.create_ffmpeg_player(file,
after=self.on_stop,
options=self.current.options)
self.current.player.volume = vol + 0.05
await self.change_status('Right version gachiGASM')
self.current.player.start()
self.right_version.clear()
@staticmethod
def _get_right_version():
path = os.path.join(os.getcwd(), 'data', 'audio', 'right_versions')
files = os.listdir(path)
return os.path.join(path, random.choice(files))
async def change_status(self, name):
if self.bot.config.now_playing:
await self.bot.change_presence(game=Game(name=name))
async def skip(self, author):
if self.is_playing():
if self.right_version.is_set():
self.bot.loop.call_soon_threadsafe(self.right_version_playing.set)
return
if self.right_version_playing.is_set():
author = author.mention
await ctx.send('FUCK YOU! %s' % author)
return
self.player.stop()
async def say(self, message, timeout=None, channel=None):
if channel is None:
channel = self.channel
return await self.bot.send_message(channel, message, delete_after=timeout)
class Audio:
def __init__(self, bot):
self.bot = bot
self.musicplayers = self.bot.playlists
self.downloader = Downloader()
def get_musicplayer(self, guild_id: int, is_on: bool=True):
"""
Gets the musicplayer for the guild if it exists
Args:
guild_id (int): id the the guild
is_on (bool):
If set on will only accept a musicplayer which has been initialized
and is ready to play without work. If it finds unsuitable target
it will destroy it and recursively call this function again
Returns:
MusicPlayer: If musicplayer was found
else None
"""
musicplayer = self.musicplayers.get(guild_id)
if musicplayer is None:
musicplayer = self.find_musicplayer_from_garbage(guild_id)
if is_on and musicplayer is not None and musicplayer.audio_player and musicplayer.audio_player.done():
musicplayer.selfdestruct()
MusicPlayer.__instances__.discard(musicplayer)
del musicplayer
self.get_musicplayer(guild_id)
return musicplayer
def find_musicplayer_from_garbage(self, guild_id):
for obj in MusicPlayer.get_instances():
if obj.channel.guild.id == guild_id:
self.musicplayers[guild_id] = obj
return obj
async def check_player(self, ctx):
musicplayer = self.get_musicplayer(ctx.guild.id)
if musicplayer is None:
terminal.error('Playlist not found even when voice is playing')
await ctx.send(f'No playlist found. Use {ctx.prefix}force_stop to reset voice state')
return musicplayer
@staticmethod
def parse_seek(string: str):
t = re.compile(r'(?P<days>\d+)*?(?:-)?(?P<hours>\d\d)?:?(?P<minutes>\d\d):(?P<seconds>\d\d)')
hours = '00'
minutes = '00'
seconds = '00'
ms = '00'
# If we have m or s 2 time in the string this doesn't work so
# we replace the ms with a to circumvent this.
string = string.replace('ms', 'a')
if 'h' in string:
hours = string.split('h')[0]
string = ''.join(string.split('h')[1:])
if 'm' in string:
minutes = string.split('m')[0].strip()
string = ''.join(string.split('m')[1:])
if 's' in string:
seconds = string.split('s')[0].strip()
string = ''.join(string.split('s')[1:])
if 'a' in string:
ms = string.split('a')[0].strip()
return '-ss {0}:{1}:{2}.{3}'.format(hours.zfill(2), minutes.zfill(2),
seconds.zfill(2), ms)
@staticmethod
def _seek_from_timestamp(timestamp):
m, s = divmod(timestamp, 60)
h, m = divmod(m, 60)
s, ms = divmod(s, 1)
h, m, s = str(int(h)), str(int(m)), str(int(s))
ms = str(round(ms, 3))[2:]
return {'h': h, 'm': m, 's': s, 'ms': ms}
@staticmethod
def _parse_filters(options: str, filter_name: str, value: str, remove=False):
logger.debug('Parsing filters: {0}, {1}, {2}'.format(options, filter_name, value))
if remove:
matches = re.findall(r'("|^|, )({}=.+?)(, |"|$)'.format(filter_name), options)
else:
matches = re.findall(r'(?: |"|^|,)({}=.+?)(?:, |"|$)'.format(filter_name), options)
logger.debug('Filter matches: {}'.format(matches))
if remove:
if not matches:
return options
matches = matches[0]
if matches.count(' ,') == 2:
options = options.replace(''.join(matches), ', ')
elif matches[0] == '"':
options = options.replace(''.join(matches[1]), '')
elif matches[2] == '"':
options = options.replace(''.join(matches[:2]), '')
else:
options = options.replace(''.join(matches), '')
if '-filter:a ""' in options:
options = options.replace('-filter:a ""', '')
return options
if matches:
return options.replace(matches[0].strip(), '{0}={1}'.format(filter_name, value))
else:
filt = '{0}={1}'.format(filter_name, value)
logger.debug('Filter value set to {}'.format(filt))
if '-filter:a "' in options:
bef_filt, aft_filt = options.split('-filter:a "', 2)
logger.debug('before and after filter. "{0}", "{1}"'.format(bef_filt, aft_filt))
options = '{0}-filter:a "{1}, {2}'.format(bef_filt, filt, aft_filt)
else:
options += ' -filter:a "{0}"'.format(filt)
return options
@staticmethod
async def check_voice(ctx, user_connected=True):
if ctx.voice_client is None:
await ctx.send('Not connected to a voice channel')
return False
if user_connected and not ctx.author.voice:
await ctx.send("You aren't connected to a voice channel")
return False
elif user_connected and ctx.author.voice.channel.id != ctx.voice_client.channel.id:
await ctx.send("You aren't connected to this bot's voice channel")
return False
return True
async def get_player_and_check(self, ctx, user_connected=True):
if not await self.check_player(ctx):
return
musicplayer = await self.check_player(ctx)
return musicplayer
@command(no_pm=True, aliases=['a'], ignore_extra=True)
@cooldown(1, 4, type=BucketType.guild)
async def again(self, ctx):
"""Queue the currently playing song to the end of the queue"""
await self._again(ctx)
@command(aliases=['q', 'queue_np'], no_pm=True, ignore_extra=True)
@cooldown(1, 3, type=BucketType.guild)
async def queue_now_playing(self, ctx):
"""Queue the currently playing song to the start of the queue"""
await self._again(ctx, True)
async def _again(self, ctx, priority=False):
"""
Args:
ctx: class Context
priority: If true song is added to the start of the playlist
Returns:
None
"""
if not await self.check_voice(ctx):
return
if not ctx.voice_client.is_playing():
return await ctx.send('Not playing anything')
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
await musicplayer.playlist.add_from_song(Song.from_song(musicplayer.current), priority,
channel=ctx.channel)
@commands.cooldown(2, 3, type=BucketType.guild)
@command(no_pm=True)
async def seek(self, ctx, *, where: str):
"""
If the video is cached you can seek it using this format h m s ms,
where at least one of them is required. Milliseconds must be zero padded
so to seek only one millisecond put 001ms. Otherwise the song will just
restart. e.g. 1h 4s and 2m1s3ms both should work.
"""
if not await self.check_voice(ctx):
return
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
current = musicplayer.current
if current is None or not ctx.voice_client.is_playing():
return await ctx.send('Not playing anything')
seek = parse_seek(where)
if seek is None:
return ctx.send('Invalid time string')
await self._seek(musicplayer, current, seek)
async def _seek(self, musicplayer, current, seek_dict, options=None,
speed=None):
"""
Args:
current: The song that we want to seek
seek_dict: A command that is passed to before_options
options: passed to create_ffmpeg_player options
Returns:
None
"""
if options is None:
options = current.options
logger.debug('Seeking with dict {0} and these options: before_options="{1}", options="{2}"'.format(seek_dict, current.before_options, options))
await current.validate_url(self.bot.aiohttp_client)
musicplayer.player.seek(current.filename, seek_dict, before_options=current.before_options, options=options, speed=speed)
async def _parse_play(self, string, ctx, metadata=None):
options = {}
filters = []
if metadata and 'filter' in metadata:
fltr = metadata['filter']
if isinstance(fltr, str):
filters.append(fltr)
else:
filters.extend(fltr)
song_name = string
if filters:
options['options'] = '-filter:a "{}"'.format(', '.join(filters))
if metadata is not None:
for key in options:
if key in metadata:
logger.debug('Setting metadata[{0}] to {1} from {2}'.format(key, options[key], metadata[key]))
metadata[key] = options[key]
else:
logger.debug('Added {0} with value {1} to metadata'.format(key, options[key]))
metadata[key] = options[key]
else:
metadata = options
if 'requested_by' not in metadata:
metadata['requested_by'] = ctx.author
logger.debug('Parse play returned {0}, {1}'.format(song_name, metadata))
return song_name, metadata
@command(enabled=False, hidden=True)
async def sfx(self, ctx):
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
musicplayer.player.source2 = player.FFmpegPCMAudio('file', reconnect=False)
@command(no_pm=True)
@commands.cooldown(1, 3, type=BucketType.user)
async def play(self, ctx, *, song_name: str):
"""Put a song in the playlist. If you put a link it will play that link and
if you put keywords it will search youtube for them"""
return await self.play_song(ctx, song_name)
async def play_song(self, ctx, song_name, priority=False, **metadata):
if not ctx.author.voice:
return await ctx.send('Not connected to a voice channel')
if ctx.voice_client and ctx.voice_client.channel.id != ctx.author.voice.channel.id:
return await ctx.send('Not connected to the same channel as the bot')
success = False
if ctx.voice_client is None:
success = await self._summon(ctx, create_task=False)
if not success:
terminal.debug('Failed to join vc')
return
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
song_name, metadata = await self._parse_play(song_name, ctx, metadata)
maxlen = -1 if ctx.author.id == self.bot.owner_id else 20
await musicplayer.playlist.add_song(song_name, maxlen=maxlen,
channel=ctx.message.channel,
priority=priority, **metadata)
if success:
musicplayer.start_playlist()
@command(no_pm=True, enabled=False, hidden=True)
async def play_playlist(self, ctx, *, musicplayer):
"""Queue a saved playlist"""
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
await musicplayer.playlist.add_from_playlist(musicplayer, ctx.message.channel)
async def _search(self, ctx, name):
vc = True if ctx.author.voice else False
if name.startswith('-yt '):
site = 'yt'
name = name.split('-yt ', 1)[1]
elif name.startswith('-sc '):
site = 'sc'
name = name.split('-sc ', 1)[1]
else:
site = 'yt'
if vc:
musicplayer = self.get_musicplayer(ctx.guild.id)
success = False
if not musicplayer:
success = await self._summon(ctx, create_task=False)
if not success:
terminal.debug('Failed to join vc')
return await ctx.send('Failed to join vc')
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
await musicplayer.playlist.search(name, ctx, site)
if success:
musicplayer.start_playlist()
else:
await search(name, ctx, site, self.downloader)
@command()
@commands.cooldown(1, 5, type=BucketType.user)
async def search(self, ctx, *, name):
"""Search for songs. Default site is youtube
Supported sites: -yt Youtube, -sc Soundcloud
To use a different site start the search with the site prefix
e.g. {prefix}{name} -sc a cool song"""
await self._search(ctx, name)
async def _summon(self, ctx, create_task=True, change_channel=False, channel=None):
if not ctx.author.voice:
await ctx.send("You aren't connected to a voice channel")
return False
if not channel:
channel = ctx.author.voice.channel
musicplayer = self.get_musicplayer(ctx.guild.id, is_on=False)
if musicplayer is None:
musicplayer = MusicPlayer(self.bot, self.disconnect_voice, channel=ctx.channel,
downloader=self.downloader)
self.musicplayers[ctx.guild.id] = musicplayer
else:
musicplayer.change_channel(ctx.channel)
if musicplayer.voice is None:
try:
musicplayer.voice = await channel.connect()
except (discord.HTTPException, asyncio.TimeoutError) as e:
await ctx.send(f'Failed to join vc because of an error\n{e}')
return False
if create_task:
musicplayer.start_playlist()
else:
try:
if channel.id != musicplayer.voice.channel.id:
if change_channel:
await musicplayer.voice.move_to(channel)
else:
await ctx.send("You aren't allowed to change channels")
elif not musicplayer.voice.is_connected():
await musicplayer.voice.channel.connect()
except (discord.HTTPException, asyncio.TimeoutError) as e:
await ctx.send(f'Failed to join vc because of an error\n{e}')
return False
return True
@command(no_pm=True, ignore_extra=True, aliases=['summon1'])
@cooldown(1, 3, type=BucketType.guild)
async def summon(self, ctx):
"""Summons the bot to join your voice channel."""
return await self._summon(ctx)
@command(no_pm=True, ignore_extra=True)
@cooldown(1, 3, type=BucketType.guild)
async def move(self, ctx, channel: discord.VoiceChannel=None):
"""Moves the bot to your current voice channel or the specified voice channel"""
return await self._summon(ctx, change_channel=True, channel=channel)
@cooldown(2, 5, BucketType.guild)
@command(ignore_extra=True, no_pm=True)
async def repeat(self, ctx, value: bool=None):
"""If set on the current song will repeat until this is set off"""
if not await self.check_voice(ctx):
return
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
if value is None:
musicplayer.repeat = not musicplayer.repeat
if musicplayer.repeat:
s = 'Repeat set on :recycle:'
else:
s = 'Repeat set off'
await ctx.send(s)
@cooldown(1, 5, BucketType.guild)
@command(ignore_extra=True, no_pm=True)
async def speed(self, ctx, value: str):
"""Change the speed of the currently playing song.
Values must be between 0.5 and 2"""
try:
v = float(value)
if v > 2 or v < 0.5:
return await ctx.send('Value must be between 0.5 and 2', delete_after=20)
except ValueError as e:
return await ctx.send('{0} is not a number\n{1}'.format(value, e), delete_after=20)
if not await self.check_voice(ctx):
return
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
current = musicplayer.current
if current is None:
return await ctx.send('Not playing anything right now', delete_after=20)
sec = musicplayer.duration
logger.debug('seeking with timestamp {}'.format(sec))
seek = self._seek_from_timestamp(sec)
options = self._parse_filters(current.options, 'atempo', value)
logger.debug('Filters parsed. Returned: {}'.format(options))
current.options = options
musicplayer._speed_mod = v
await self._seek(musicplayer, current, seek, options=options, speed=v)
@commands.cooldown(1, 5, BucketType.guild)
@command(ignore_extra=True, no_pm=True)
async def bass(self, ctx, value: int):
"""Add bass boost or decrease to a song.
Value can range between -60 and 60"""
if not (-60 <= value <= 60):
return await ctx.send('Value must be between -60 and 60', delete_after=20)
if not await self.check_voice(ctx):
return
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
current = musicplayer.current
if current is None:
return await ctx.send('Not playing anything right now', delete_after=20)
sec = musicplayer.duration
logger.debug('seeking with timestamp {}'.format(sec))
seek = self._seek_from_timestamp(sec)
value = 'g=%s' % value
options = self._parse_filters(current.options, 'bass', value)
logger.debug('Filters parsed. Returned: {}'.format(options))
current.options = options
await self._seek(musicplayer, current, seek, options=options)
@cooldown(1, 5, BucketType.guild)
@command(no_pm=True, ignore_extra=True)
async def stereo(self, ctx, mode='sine'):
"""Works almost the same way {prefix}play does
Default stereo type is sine.
All available modes are `sine`, `triangle`, `square`, `sawup`, `sawdown`, `left`, `right`, `off`
To set a different mode start your command parameters with -mode song_name
e.g. `{prefix}{name} -square stereo cancer music` would use the square mode
"""
if not await self.check_voice(ctx):
return
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
current = musicplayer.current
if current is None:
return await ctx.send('Not playing anything right now', delete_after=20)
mode = mode.lower()
modes = ("sine", "triangle", "square", "sawup", "sawdown", 'off', 'left', 'right')
if mode not in modes:
return await ctx.send('Incorrect mode specified')
sec = musicplayer.duration
logger.debug('seeking with timestamp {}'.format(sec))
seek = self._seek_from_timestamp(sec)
if mode in ('left', 'right'):
mode = 'FL-FR' if mode == 'right' else 'FR-FL'
options = self._parse_filters(current.options, 'channelmap', 'map={}'.format(mode))
else:
options = self._parse_filters(current.options, 'apulsator', 'mode={}'.format(mode), remove=(mode == 'off'))
current.options = options
await self._seek(musicplayer, current, seek, options=options)
@group(no_pm=True, invoke_without_command=True)
@cooldown(1, 4, type=BucketType.guild)
async def clear(self, ctx, *, items):
"""
Clear the selected indexes from the playlist.
"!clear all" empties the whole playlist
usage:
{prefix}{name} 1-4 7-9 5
would delete songs at positions 1 to 4, 5 and 7 to 9
"""
musicplayer = self.get_musicplayer(ctx.guild.id, False)
if not musicplayer:
return
if items != 'all':
indexes = items.split(' ')
index = []
for idx in indexes:
if '-' in idx:
idx = idx.split('-')
a = int(idx[0])
b = int(idx[1])
index += range(a - 1, b)
else:
index.append(int(idx) - 1)
else:
index = None
await musicplayer.playlist.clear(index, ctx.channel)
@clear.command(no_pm=True, name='from')
@cooldown(2, 5)
async def from_(self, ctx, *, user: discord.Member):
"""Clears all songs from the specified user"""
musicplayer = await self.get_player_and_check(ctx)
if not musicplayer:
return
def pred(song):
if song.requested_by and song.requested_by.id == user.id:
return True
return False
cleared = musicplayer.playlist.clear_by_predicate(pred)
await ctx.send(f'Cleared {cleared} songs from user {user}')
@clear.command(no_pm=True, aliases=['dur', 'duration', 'lt'])
@cooldown(2, 5)
async def longer_than(self, ctx, *, duration: TimeDelta):
"""Delete all songs from queue longer than specified duration
Duration is a time strin in the format of 1d 1h 1m 1s"""
musicplayer = await self.get_player_and_check(ctx)
if not musicplayer:
return
sec = duration.total_seconds()
def pred(song):
if song.duration > sec:
return True
return False
cleared = musicplayer.playlist.clear_by_predicate(pred)
await ctx.send(f'Cleared {cleared} songs longer than {duration}')
@clear.command(no_pm=True, name='name')
@cooldown(2, 4)
async def by_name(self, ctx, *, song_name):
"""Clear queue by song name. Regex can be used for this"""
musicplayer = await self.get_player_and_check(ctx)
if not musicplayer:
return
matches = set()
try:
r = re.compile(song_name, re.IGNORECASE)
except re.error as e:
await ctx.send('Failed to compile regex\n' + str(e))
return
# This needs to be run in executor in case someone decides to use
# an evil regex
def get_matches():
for song in musicplayer.playlist.playlist:
if not song.title:
continue
if r.search(song.title):
matches.add(song.title)
try:
await asyncio.wait_for(self.bot.loop.run_in_executor(self.bot.threadpool, get_matches),
timeout=1, loop=self.bot.loop)
except asyncio.TimeoutError:
logger.warning(f'{ctx.author} {ctx.author.id} timeouted regex. Used regex was {song_name}')
await ctx.send('Search timed out')
return
def pred(song):
return song.title in matches
cleared = musicplayer.playlist.clear_by_predicate(pred)
await ctx.send(f'Cleared {cleared} songs matching {song_name}')
@cooldown(2, 3, type=BucketType.guild)
@command(no_pm=True, aliases=['vol'])
async def volume(self, ctx, value: int=-1):
"""
Sets the volume of the currently playing song.
If no parameters are given it shows the current volume instead
Effective values are between 0 and 200
"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not await self.check_voice(ctx):
return
# If value is smaller than zero or it hasn't been given this shows the current volume
if value < 0:
await ctx.send('Volume is currently at {:.0%}'.format(musicplayer.current_volume))
return
musicplayer.current_volume = value / 100
await ctx.send('Set the volume to {:.0%}'.format(musicplayer.current_volume))
@commands.cooldown(2, 3, type=BucketType.guild)
@command(no_pm=True, aliases=['default_vol', 'd_vol'])
async def default_volume(self, ctx, value: int=-1):
"""
Sets the default volume of the player that will be used when song specific volume isn't set.
If no parameters are given it shows the current default volume instead
Effective values are between 0 and 200
"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not await self.check_voice(ctx):
return
# If value is smaller than zero or it hasn't been given this shows the current volume
if value < 0:
await ctx.send('Default volume is currently at {:.0%}'.format(musicplayer.volume))
return
musicplayer.volume = min(value / 100, 2)
await ctx.send('Set the default volume to {:.0%}'.format(musicplayer.volume))
@commands.cooldown(1, 4, type=BucketType.guild)
@command(no_pm=True, aliases=['np'])
async def playing(self, ctx):
"""Gets the currently playing song"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer or musicplayer.player is None or musicplayer.current is None:
await ctx.send('No songs currently in queue')
else:
tr_pos = get_track_pos(musicplayer.current.duration, musicplayer.duration)
await ctx.send(musicplayer.current.long_str + ' {0}'.format(tr_pos))
@cooldown(1, 3, type=BucketType.user)
@command(name='playnow', no_pm=True)
async def play_now(self, ctx, *, song_name: str):
"""
Sets a song to the priority queue which is played as soon as possible
after the other songs in that queue.
"""
musicplayer = self.get_musicplayer(ctx.guild.id)
success = False
if musicplayer is None or musicplayer.voice is None:
success = await self._summon(ctx, create_task=False)
if not success:
return
await self.play_song(ctx, song_name, priority=True)
if success:
musicplayer.start_playlist()
@cooldown(1, 3, type=BucketType.guild)
@command(no_pm=True, aliases=['p'])
async def pause(self, ctx):
"""Pauses the currently played song."""
musicplayer = self.get_musicplayer(ctx.guild.id)
if musicplayer:
musicplayer.pause()
@cooldown(1, 60, type=BucketType.guild)
@command(enabled=False, hidden=True)
async def save_playlist(self, ctx, *name):
if name:
name = ' '.join(name)
musicplayer = self.get_musicplayer(ctx.guild.id)
await musicplayer.playlist.current_to_file(name, ctx.message.channel)
@cooldown(1, 3, type=BucketType.guild)
@command(no_pm=True, aliases=['r'])
async def resume(self, ctx):
"""Resumes the currently played song."""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
musicplayer.resume()
@command(name='bpm', no_pm=True, ignore_extra=True)
@cooldown(1, 8, BucketType.guild)
async def bpm(self, ctx):
"""Gets the currently playing songs bpm using aubio"""
if not aubio:
return await ctx.send('BPM is not supported', delete_after=60)
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
song = musicplayer.current
if not musicplayer.is_playing() or not song:
return
if song.bpm:
return await ctx.send('BPM for {} is about **{}**'.format(song.title, round(song.bpm, 1)))
if song.duration == 0:
return await ctx.send('Cannot determine bpm because duration is 0', delete_after=90)
import subprocess
import shlex
file = song.filename
tempfile = os.path.join(os.getcwd(), 'data', 'temp', 'tempbpm.wav')
cmd = 'ffmpeg -i "{}" -f wav -t 00:10:00 -map_metadata -1 -loglevel warning pipe:1'.format(file)
args = shlex.split(cmd)
try:
p = subprocess.Popen(args, stdout=subprocess.PIPE)
except Exception:
terminal.exception('Failed to get bpm')
return await ctx.send('Error while getting bpm', delete_after=20)
from utils.utilities import write_wav
await self.bot.loop.run_in_executor(self.bot.threadpool, partial(write_wav, p.stdout, tempfile))
try:
win_s = 512 # fft size
hop_s = win_s // 2 # hop size
s = aubio.source(tempfile, 0, hop_s, 2)
samplerate = s.samplerate
o = aubio.tempo("default", win_s, hop_s, samplerate)
# tempo detection delay, in samples
# default to 4 blocks delay to catch up with
delay = 4. * hop_s
# list of beats, in samples
beats = []
# total number of frames read
total_frames = 0
while True:
samples, read = s()
is_beat = o(samples)
if is_beat:
this_beat = int(total_frames - delay + is_beat[0] * hop_s)
beats.append(this_beat)
total_frames += read
if read < hop_s:
break
bpm = len(beats) / song.duration * 60
song.bpm = bpm
return await ctx.send('BPM for {} is about **{}**'.format(song.title, round(bpm, 1)))
finally:
try:
s.close()
except:
pass
os.remove(tempfile)
@cooldown(1, 4, type=BucketType.guild)
@command(no_pm=True)
async def shuffle(self, ctx):
"""Shuffles the current playlist"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
await musicplayer.playlist.shuffle()
await ctx.send('Playlist shuffled')
async def shutdown(self):
self.clear_cache()
@staticmethod
async def close_player(musicplayer):
if musicplayer is None:
return
if musicplayer.player:
musicplayer.player.after = None
if musicplayer.is_playing():
musicplayer.stop()
try:
if musicplayer.audio_player is not None:
musicplayer.audio_player.cancel()
if musicplayer.voice is not None:
await musicplayer.voice.disconnect()
musicplayer.voice = None
except Exception:
terminal.exception('Error while stopping voice')
async def disconnect_voice(self, musicplayer):
try:
del self.musicplayers[musicplayer.channel.guild.id]
except:
pass
await self.close_player(musicplayer)
if not self.musicplayers:
await self.bot.change_presence(activity=discord.Activity(**self.bot.config.default_activity))
@command(no_pm=True, ignore_extra=True)
@cooldown(1, 6, BucketType.guild)
async def force_stop(self, ctx):
"""
Forces voice to be stopped no matter what state the bot is in
as long as it's connected to voice and the internal state is in sync.
Not meant to be used for normal disconnecting
"""
try:
res = await self.stop.callback(self, ctx)
except Exception as e:
print(e)
res = False
# Just to be sure, delete every single musicplayer related to this server
musicplayer = self.get_musicplayer(ctx.guild.id, False)
while musicplayer is not None:
try:
self.musicplayers.pop(ctx.guild.id)
except KeyError:
pass
MusicPlayer.__instances__.discard(musicplayer)
musicplayer.selfdestruct()
del musicplayer
musicplayer = self.get_musicplayer(ctx.guild.id, False)
del musicplayer
import gc
gc.collect()
if res is False:
if not ctx.voice_client:
return await ctx.send('Not connected to voice')
await ctx.voice_client.disconnect()
await ctx.send('Disconnected')
else:
await ctx.send('Disconnected')
@commands.cooldown(1, 6, BucketType.user)
@command(no_pm=True, aliases=['stop1'], ignore_extra=True)
async def stop(self, ctx):
"""Stops playing audio and leaves the voice channel.
This also clears the queue.
"""
musicplayer = self.get_musicplayer(ctx.guild.id, False)
if not musicplayer:
if ctx.guild.me.voice:
for client in self.bot.voice_clients:
if client.guild.id == ctx.guild.id:
await client.disconnect()
return
return False
await self.disconnect_voice(musicplayer)
if not self.musicplayers:
self.clear_cache()
@cooldown(1, 5, type=BucketType.user)
@command(no_pm=True, aliases=['skipsen', 'skipperino', 's'])
async def skip(self, ctx):
"""Skips the current song"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
if not await self.check_voice(ctx):
return
if not musicplayer.is_playing():
await ctx.send('Not playing any music right now...')
return
await musicplayer.skip(ctx.author, ctx.channel)
@cooldown(1, 5, type=BucketType.user)
@command(no_pm=True, aliases=['force_skipsen', 'force_skipperino', 'fs'])
async def force_skip(self, ctx):
"""Force skips this song no matter who queued it without requiring any votes
For public servers it's recommended you blacklist this from your server
and only give some people access to it"""
if not await self.check_voice(ctx):
return
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
if not musicplayer.is_playing():
await ctx.send('Not playing any music right now...')
return
await musicplayer.skip(None, ctx.channel)
@cooldown(1, 5, type=BucketType.guild)
@command(name='queue', no_pm=True, aliases=['playlist'])
async def playlist(self, ctx, page_index: int=0):
"""Get a list of the current queue in 10 song chunks
To skip to a certain page set the page_index arg"""
if not await self.check_voice(ctx, user_connected=False):
return
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
playlist = list(musicplayer.playlist.playlist) # good variable naming
if not playlist and musicplayer.current is None:
return await ctx.send('Nothing playing atm')
pages = []
for i in range(0, len(playlist), 10):
pages.append(playlist[i:i+10])
if not pages:
pages.append([])
def get_page(page, idx):
playlist = list(musicplayer.playlist.playlist) # good variable naming
if not playlist and musicplayer.current is None:
return 'Nothing playing atm'
dur = get_track_pos(musicplayer.current.duration, musicplayer.duration)
response = f'Currently playing **{musicplayer.current.title}** {dur}'
if musicplayer.current.requested_by:
response += f' enqueued by {musicplayer.current.requested_by}\n'
durations = self.song_durations(musicplayer, until=idx*10+10)
durations = durations[-10:]
for _idx, song_dur in enumerate(zip(page, durations)):
song, dur = song_dur
dur = int(dur)
response += '\n{0}. **{1.title}** {1.requested_by}'.format(_idx + 1 + 10*idx, song)
response += ' (ETA: {0[0]}m {0[1]}s)'.format(divmod(dur, 60))
return response
await send_paged_message(ctx, pages, starting_idx=page_index,
page_method=get_page)
@cooldown(1, 3, type=BucketType.guild)
@command(no_pm=True, aliases=['len'])
async def length(self, ctx):
"""Gets the length of the current queue"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
if musicplayer.current is None or not musicplayer.playlist.playlist:
return await ctx.send('No songs in queue')
time_left = self.list_length(musicplayer)
minutes, seconds = divmod(floor(time_left), 60)
hours, minutes = divmod(minutes, 60)
return await ctx.send('The length of the playlist is about {0}h {1}m {2}s'.format(hours, minutes, seconds))
@command(no_pm=True, ignore_extra=True, auth=Auth.BOT_MOD)
async def ds(self, ctx):
"""Delete song from autoplaylist and skip it"""
await ctx.invoke(self.delete_from_ap)
await ctx.invoke(self.skip)
@staticmethod
def list_length(musicplayer, index=None):
playlist = musicplayer.playlist
if not playlist:
return
time_left = musicplayer.current.duration - musicplayer.duration
for song in list(playlist)[:index]:
time_left += song.duration
return time_left
@staticmethod
def song_durations(musicplayer, until=None):
playlist = musicplayer.playlist
if not playlist:
return None
durations = []
time_left = musicplayer.current.duration - musicplayer.duration
for song in list(playlist)[:until]:
durations.append(time_left)
time_left += song.duration
return durations
@cooldown(1, 5, type=BucketType.user)
@command(no_pm=True, aliases=['dur'])
async def duration(self, ctx):
"""Gets the duration of the current song"""
if not await self.check_voice(ctx):
return
musicplayer = self.get_musicplayer(ctx.guild.id)
if not musicplayer:
return
if musicplayer.is_playing():
dur = musicplayer.duration
msg = get_track_pos(musicplayer.current.duration, dur)
await ctx.send(msg)
else:
await ctx.send('No songs are currently playing')
@command(no_pm=True)
@cooldown(2, 6)
async def autoplay(self, ctx, value: bool=None):
"""Determines if youtube autoplay should be emulated
If no value is passed current value is output"""
musicplayer = await self.check_player(ctx)
if not musicplayer:
return await ctx.send('Not playing any music right now')
if not await self.check_voice(ctx):
return
if value is None:
return await ctx.send(f'Autoplay currently {"on" if musicplayer.autoplay else "off"}')
musicplayer.autoplay = value
s = f'Autoplay set {"on" if value else "off"}'
await ctx.send(s)
@command(name='volm', no_pm=True)
@cooldown(1, 4, type=BucketType.guild)
async def vol_multiplier(self, ctx, value=None):
"""The multiplier that is used when dynamically calculating the volume"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not value:
return await ctx.send('Current volume multiplier is %s' % str(musicplayer.volume_multiplier))
try:
value = float(value)
musicplayer.volume_multiplier = value
await ctx.send(f'Volume multiplier set to {value}')
except ValueError:
await ctx.send('Value is not a number', delete_after=60)
@command(no_pm=True, aliases=['avolm'])
@cooldown(2, 4, type=BucketType.guild)
async def auto_volm(self, ctx):
"""Automagically set the volm value based on current volume"""
musicplayer = await self.check_player(ctx)
if not musicplayer:
return
if not await self.check_voice(ctx):
return
current = musicplayer.current
if not current:
return await ctx.send('Not playing anything right now')
old = musicplayer.volume_multiplier
if not current.rms:
for h in musicplayer.history:
if not h.rms:
continue
new = round(h.rms * h.volume, 1)
await ctx.send("Current song hadn't been processed yet so used song history to determine volm\n"
f"{old} -> {new}")
return
new = round(current.rms * musicplayer.current_volume, 1)
musicplayer.volume_multiplier = new
await ctx.send(f'volm changed automagically {old} -> {new}')
@command(no_pm=True)
@cooldown(1, 10, type=BucketType.guild)
async def link(self, ctx):
"""Link to the current song"""
if not await self.check_voice(ctx):
return
musicplayer = self.get_musicplayer(ctx.guild.id)
if musicplayer is None:
return
current = musicplayer.current
if not current:
return await ctx.send('Not playing anything')
await ctx.send('Link to **{0.title}** {0.webpage_url}'.format(current))
@command(name='delete', no_pm=True, aliases=['del', 'd'], auth=Auth.BOT_MOD)
async def delete_from_ap(self, ctx, *name):
"""Puts a song to the queue to be deleted from autoplaylist"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if not name:
name = [musicplayer.current.webpage_url]
if name is None:
terminal.debug('No name specified in delete_from')
await ctx.send('No song to delete', delete_after=60)
return
with open(DELETE_AUTOPLAYLIST, 'a', encoding='utf-8') as f:
f.write(' '.join(name) + '\n')
terminal.info('Added entry %s to the deletion list' % name)
await ctx.send('Added entry %s to the deletion list' % ' '.join(name), delete_after=60)
@command(name='add', no_pm=True, auth=Auth.BOT_MOD)
async def add_to_ap(self, ctx, *name):
"""Puts a song to the queue to be added to autoplaylist"""
musicplayer = self.get_musicplayer(ctx.guild.id)
if name:
name = ' '.join(name)
if not name:
if not musicplayer:
return
current = musicplayer.current
if current is None or current.webpage_url is None:
terminal.debug('No name specified in add_to')
await ctx.send('No song to add', delete_after=30)
return
data = current.webpage_url
name = data
elif 'playlist' in name or 'channel' in name:
async def on_error(e):
await ctx.send('Failed to get playlist %s' % e)
info = await self.downloader.extract_info(self.bot.loop, url=name, download=False,
on_error=on_error)
if info is None:
return
links = await Playlist.process_playlist(info, channel=ctx.message.channel)
if links is None:
await ctx.send('Incompatible playlist')
data = '\n'.join(links)
else:
data = name
with open(ADD_AUTOPLAYLIST, 'a', encoding='utf-8') as f:
f.write(data + '\n')
terminal.info('Added entry %s to autoplaylist' % name)
await ctx.send('Added entry %s' % name, delete_after=60)
@command(no_pm=True)
@cooldown(1, 5, type=BucketType.guild)
async def autoplaylist(self, ctx, option: str):
"""Set the autoplaylist on or off"""
musicplayer = self.get_musicplayer(ctx.guild.id)
option = option.lower().strip()
if option != 'on' and option != 'off':
await ctx.send('Autoplaylist state needs to be on or off')
return
if option == 'on':
musicplayer.autoplaylist = True
elif option == 'off':
musicplayer.autoplaylist = False
await ctx.send('Autoplaylist set %s' % option)
def clear_cache(self):
songs = []
for musicplayer in self.musicplayers.values():
for song in musicplayer.playlist.playlist:
songs += [song.id]
cachedir = os.path.join(os.getcwd(), 'data', 'audio', 'cache')
try:
files = os.listdir(cachedir)
except (OSError, FileNotFoundError):
return
def check_list(string):
if song.id is not None and song.id in string:
return True
return False
dont_delete = []
for song in songs:
file = list(filter(check_list, files))
if file:
dont_delete += file
for file in files:
if file not in dont_delete:
try:
os.remove(os.path.join(cachedir, file))
except os.error:
pass
def setup(bot):
bot.add_cog(Audio(bot))
<file_sep>"""
MIT License
Copyright (c) 2017 s0hvaperuna
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.
"""
import asyncio
import logging
import os
import time
import discord
logger = logging.getLogger('audio')
terminal = logging.getLogger('terminal')
class Song:
__slots__ = ['title', 'url', 'webpage_url', 'id', 'duration', 'default_duration',
'uploader', 'playlist', 'seek', 'success', 'filename', 'before_options',
'options', 'dl_folder', '_downloading', 'on_ready', 'volume',
'logger', 'bpm', 'config', 'requested_by', 'last_update', 'is_live',
'rms']
def __init__(self, playlist=None, filename=None, config=None, **kwargs):
self.title = kwargs.pop('title', 'Untitled')
self.url = kwargs.pop('url', 'None')
self.webpage_url = kwargs.pop('webpage_url', None)
self.id = kwargs.pop('id', None)
self.duration = kwargs.pop('duration', 0)
self.default_duration = self.duration # Used when speed is changed
self.uploader = kwargs.pop('uploader', 'None')
self.requested_by = kwargs.pop('requested_by', None)
self.is_live = kwargs.pop('is_live', True)
self.playlist = playlist
self.seek = False
self.success = False
self.config = config
self.filename = filename
self.before_options = kwargs.pop('before_options', '')
if '-nostdin' not in self.before_options:
self.before_options = ' '.join(('-nostdin', self.before_options)).strip()
self.options = kwargs.pop('options', '')
if '-vn -b:a' not in self.options:
self.options = ' '.join((self.options, '-vn -b:a 128k -bufsize 256K')).strip()
self.dl_folder = self.playlist.downloader.dl_folder
self._downloading = False
self.on_ready = asyncio.Event()
self.bpm = None
self.last_update = 0
self.volume = None
self.rms = kwargs.pop('rms', None)
@classmethod
def from_song(cls, song, **kwargs):
s = Song(**{k: getattr(song, k, None) for k in song.__slots__})
s.bpm = song.bpm
for k in kwargs:
if k in song.__slots__:
setattr(s, k, kwargs[k])
return s
def __str__(self):
string = '**{0.title}**'
return string.format(self)
@property
def long_str(self):
string = '**{0.title}**'
if self.requested_by:
string += ' enqueued by {0.requested_by}'
return string.format(self)
def info_from_dict(self, **kwargs):
self.title = kwargs.get('title', self.title)
self.url = kwargs.get('url', self.url)
self.webpage_url = kwargs.get('webpage_url', self.webpage_url)
self.id = kwargs.get('id', self.id)
self.duration = kwargs.get('duration', self.duration)
self.default_duration = self.duration
self.uploader = kwargs.get('uploader', self.uploader)
self.before_options = kwargs.get('before_options', self.before_options)
self.options = kwargs.get('options', self.options)
self.is_live = kwargs.pop('is_live', True)
if 'url' in kwargs:
self.last_update = time.time()
self.success = True
self.playlist.bot.loop.call_soon_threadsafe(self.on_ready.set)
if self.playlist.bot.config.download:
self.filename = self.playlist.downloader.safe_ytdl.prepare_filename(**kwargs)
else:
self.filename = self.url
@property
def downloading(self):
return self._downloading
async def validate_url(self, session):
if time.time() - self.last_update <= 7200:
return True # If link is under 2h old it probably still works
try:
async with session.get(self.url) as r:
if r.status != 200:
await self.download()
return True
except:
logger.exception('Failed to validate url')
return False
async def download(self):
if time.time() - self.last_update <= 7200 or self._downloading or self.success:
self.playlist.bot.loop.call_soon_threadsafe(self.on_ready.set)
return
self._downloading = True
logger.debug(f'Started downloading {self.long_str}')
try:
dl = self.config.download
if dl and self.last_update:
logger.debug('Skipping dl')
return
loop = self.playlist.bot.loop
if dl:
if not os.path.exists(self.dl_folder):
terminal.info(f'Making directory {self.dl_folder}')
os.makedirs(self.dl_folder)
logger.debug(f'Created dir {self.dl_folder}')
if self.filename is not None and os.path.exists(self.filename):
self.success = True
return
check_dl = False
if self.id is not None:
fdir = os.listdir(self.dl_folder)
for f in fdir:
if self.id in f:
check_dl = True
break
if check_dl and self.filename is None:
logger.debug('Getting and checking info for: {}'.format(self))
info = await self.playlist.downloader.safe_extract_info(loop, url=self.webpage_url, download=False)
logger.debug('Got info')
self.filename = self.playlist.downloader.safe_ytdl.prepare_filename(info)
logger.debug('Filename set to {}'.format(self.filename))
if self.filename is not None:
if os.path.exists(self.filename):
terminal.info('File exists for %s' % self.title)
logger.debug('File exists for %s' % self.title)
self.success = True
return
logger.debug('Getting info and downloading {}'.format(self.webpage_url))
info = await self.playlist.downloader.extract_info(loop, url=self.webpage_url, download=dl)
logger.debug('Got info')
self.info_from_dict(**info)
terminal.info('Downloaded ' + self.webpage_url)
logger.debug('Filename set to {}'.format(self.filename))
self.success = True
return
except Exception as e:
logger.debug('Download error: {}'.format(e))
try:
await self.playlist.channel.send('Failed to download {0}\nlink: {1}'.format(self.title, self.webpage_url))
except discord.HTTPException:
pass
finally:
self._downloading = False
self.playlist.bot.loop.call_soon_threadsafe(self.on_ready.set)
async def delete_file(self):
for _ in range(0, 2):
try:
if not os.path.exists(self.filename):
return
os.remove(self.filename)
terminal.info('Deleted ' + self.filename)
break
except PermissionError:
await asyncio.sleep(1)
<file_sep>import logging
import typing
from functools import partial
import discord
from discord.ext import commands
from discord.ext.commands import BucketType, has_permissions
from sqlalchemy.exc import SQLAlchemyError
from bot.bot import command, group, cooldown
from bot.converters import CommandConverter
from bot.formatter import Paginator
from bot.globals import BlacklistTypes, PermValues
from cogs.cog import Cog
from utils.utilities import (split_string, get_role, send_paged_message)
logger = logging.getLogger('debug')
perms = discord.Permissions(8)
class CommandBlacklist(Cog):
def __init__(self, bot):
super().__init__(bot)
@group(ignore_extra=True, no_pm=True, invoke_without_command=True)
@has_permissions(administrator=True)
@cooldown(1, 5, type=BucketType.guild)
async def blacklist(self, ctx, commands: commands.Greedy[CommandConverter]=None, *, mention: typing.Union[discord.TextChannel, discord.Role, discord.User]=None):
"""Blacklist a command for a user, role or channel
To blacklist multiple commands at the same time wrap the command names in quotes
like this {prefix}{name} \"command1 command2 command3\" #channel
The hierarchy of `blacklist` and `whitelist` is as follows
Whitelist always overrides blacklist of the same level
Then levels of scope it can have are as follows
`User` > `Role` > `Channel` > `Server` where each level overrides every scope perm after it
e.g. Blacklisting command ping for role Member and whitelisting it for role Mod
would make it so people with Member role wouldn't be able to use it unless they had Mod role
Also if you further whitelisted ping from a single member
that user would be able to use the command always
since user whitelist overrides every other scope
To blacklist a command server wide specify the commands and don't specify the mention param
like this `{prefix}blacklist "cmd1 cmd2 etc"` which would blacklist those commands
for everyone in the server unless they have it whitelisted
Whitelisting server wide isn't possible
For dangers of whitelisting see `{prefix}help whitelist`"""
guild = ctx.guild
if not commands and mention is None:
return await ctx.send('No parameters given')
async def _blacklist(name):
if mention is None:
whereclause = 'guild=%s AND type IN (%s, %s) AND command="%s" AND channel IS NULL AND role IS NULL AND user IS NULL' % (
guild.id, BlacklistTypes.BLACKLIST, BlacklistTypes.WHITELIST, name)
success = await self._set_blacklist(ctx, whereclause, guild=guild.id, command=name)
if success:
return 'Blacklisted command {} from this server'.format(name)
elif success is None:
return 'Removed blacklist for command {} on this server'.format(name)
elif isinstance(mention, discord.User):
return await self._add_user_blacklist(ctx, name, mention, guild)
elif isinstance(mention, discord.Role):
return await self._add_role_blacklist(ctx, name, mention, guild)
elif isinstance(mention, discord.TextChannel):
return await self._add_channel_blacklist(ctx, name, mention, guild)
s = ''
if commands is None:
val = await self._set_all_commands(ctx, mention)
if isinstance(val, str):
s += val
else:
for command in commands:
if command.name == 'privacy':
await ctx.send("Cannot blacklist privacy command as it's required that anyone can see it")
continue
val = await _blacklist(command.name)
if isinstance(val, str):
s += val + '\n'
if not s:
return
for msg in split_string(s, splitter='\n'):
await ctx.send(msg)
@blacklist.command(ignore_extra=True, no_pm=True)
@has_permissions(administrator=True)
async def toggle(self, ctx):
"""
Disable all commands on this server (owner will still be able to use them)
Whitelisting commands also overrides this rule
Won't override existing commands that have been blacklisted so when you toggle
again the commands that have been specifically blacklisted are still blacklisted
"""
guild = ctx.guild
values = {'command': None, 'guild': guild.id, 'type': BlacklistTypes.BLACKLIST}
where = 'guild=%s AND command IS NULL AND NOT type=%s AND user IS NULL AND role IS NULL AND channel IS NULL' % (guild.id, BlacklistTypes.GLOBAL)
success = await self._set_blacklist(where, **values)
if success:
msg = 'All commands disabled on this server for non whitelisted users'
elif success is None:
msg = 'Commands are usable on this server again'
else:
return
await ctx.send(msg)
async def _set_all_commands(self, ctx, scope, type=BlacklistTypes.BLACKLIST):
guild = ctx.guild
values = {'command': None, 'guild': guild.id, 'type': type}
where = 'guild=%s AND command IS NULL AND NOT type=%s AND ' % (guild.id, BlacklistTypes.GLOBAL)
type_string = 'Blacklisted' if type == BlacklistTypes.BLACKLIST else 'Whitelisted'
type_string2 = 'blacklist' if type == BlacklistTypes.BLACKLIST else 'whitelist'
message = None
if isinstance(scope, discord.User):
userid = scope.id
success = await self._set_blacklist(ctx, where + 'user=%s' % userid, user=userid, **values)
if success:
message = f'{type_string} all commands for user {scope} `{userid}`'
elif success is None:
message = f'removed {type_string2} from user {scope}, `{userid}`'
elif isinstance(scope, discord.Role):
success = await self._set_blacklist(ctx, where + 'role=%s' % scope.id, role=scope.id, **values)
if success:
message = '{0} all commands from role {1} `{1.id}`'.format(type_string, scope)
elif success is None:
message = 'Removed {0} from role {1} `{1.id}`'.format(type_string2, scope)
elif isinstance(scope, discord.TextChannel):
success = await self._set_blacklist(ctx, where + 'channel=%s' % scope.id,
channel=scope.id, **values)
if success:
message = '{0} all commands from channel {1} `{1.id}`'.format(type_string, scope)
elif success is None:
message = 'Removed {0} from channel {1} `{1.id}`'.format(type_string2, scope)
else:
return 'No valid mentions'
return message
@command(ignore_extra=True, no_pm=True)
@has_permissions(administrator=True)
@cooldown(1, 5, type=BucketType.guild)
async def whitelist(self, ctx, commands: commands.Greedy[CommandConverter], *, mention: typing.Union[discord.TextChannel, discord.Role, discord.User]):
"""Whitelist a command for a user, role or channel
To whitelist multiple commands at the same time wrap the command names in quotes
like this {prefix}{name} \"command1 command2 command3\" #channel
To see specifics on the hierarchy of whitelist/blacklist see `{prefix}help blacklist`
**WHITELISTING COULD BE DANGEROUS IF YOU DON'T KNOW WHAT YOU ARE DOING!**
Before whitelisting read the following
Whitelisting WILL OVERRIDE ANY REQUIRED PERMS for the command being called
If a command requires ban perms and you whitelist it for a role
everyone with that role can use that command even when they don't have ban perms
Due to safety reasons whitelisting commands from this module is not allowed.
Give the users correct discord perms instead
"""
msg = ctx.message
guild = msg.guild
async def _whitelist(_command):
name = _command.name
if _command.cog_name == self.__class__.__name__:
return f"Due to safety reasons commands from {_command.cog_name} module can't be whitelisted"
elif isinstance(mention, discord.User):
return await self._add_user_whitelist(ctx, name, mention, guild)
elif isinstance(mention, discord.Role):
return await self._add_role_whitelist(ctx, name, mention, guild)
elif isinstance(mention, discord.TextChannel):
return await self._add_channel_whitelist(ctx, name, mention, guild)
s = ''
for command in commands:
val = await _whitelist(command)
if isinstance(val, str):
s += val + '\n'
if not s:
return
for msg in split_string(s, splitter='\n'):
await ctx.send(msg)
async def _set_blacklist(self, ctx, whereclause, type_=BlacklistTypes.BLACKLIST, **values):
"""
:ctx: object that messages can be sent to
:return: True when new permission is set
None when permission is toggled
False when operation failed
"""
type_string = 'blacklist' if type_ == BlacklistTypes.BLACKLIST else 'whitelist'
sql = 'SELECT `id`, `type` FROM `command_blacklist` WHERE %s' % whereclause
try:
row = (await self.bot.dbutil.execute(sql, values)).first()
except SQLAlchemyError:
logger.exception('Failed to remove blacklist')
await ctx.send('Failed to remove %s' % type_string)
return
if row:
if row['type'] == type_:
sql = 'DELETE FROM `command_blacklist` WHERE id=:id'
try:
await self.bot.dbutil.execute(sql, {'id': row['id']}, commit=True)
except SQLAlchemyError:
logger.exception('Could not update %s with whereclause %s' % (type_string, whereclause))
await ctx.send('Failed to remove %s' % type_string)
return False
else:
return
else:
sql = 'UPDATE `command_blacklist` SET type=:type WHERE id=:id'
try:
await self.bot.dbutil.execute(sql, {'type': type_, 'id': row['id']}, commit=True)
except SQLAlchemyError:
logger.exception('Could not update %s with whereclause %s' % (type_string, whereclause))
await ctx.send('Failed to remove %s' % type_string)
return False
else:
return True
else:
sql = 'INSERT INTO `command_blacklist` ('
values['type'] = type_
keys = values.keys()
val = '('
l = len(keys)
for idx, k in enumerate(keys):
sql += '`%s`' % k
val += ':%s' % k
if idx != l - 1:
sql += ', '
val += ', '
sql += ') VALUES ' + val + ')'
try:
await self.bot.dbutil.execute(sql, values, commit=True)
except SQLAlchemyError:
logger.exception('Could not set values %s' % values)
await ctx.send('Failed to set %s' % type_string)
return False
return True
async def _add_user_blacklist(self, ctx, command_name, user, guild):
whereclause = 'guild=:guild AND command=:command AND user=:user AND NOT type=:type'
success = await self._set_blacklist(ctx, whereclause, command=command_name,
user=user.id,
guild=guild.id,
type=BlacklistTypes.GLOBAL)
if success:
return 'Blacklisted command {0} from user {1} `{1.id}`'.format(command_name, user)
elif success is None:
return 'Removed command {0} blacklist from user {1} `{1.id}`'.format(command_name, user)
async def _add_role_blacklist(self, ctx, command_name, role, guild):
whereclause = 'guild=:guild AND command=:command AND role=:role AND NOT type=:type'
success = await self._set_blacklist(ctx, whereclause, command=command_name,
role=role.id,
guild=guild.id,
type=BlacklistTypes.GLOBAL)
if success:
return 'Blacklisted command {0} from role {1} `{1.id}`'.format(command_name, role)
elif success is None:
return 'Removed command {0} blacklist from role {1} `{1.id}`'.format(command_name, role)
async def _add_channel_blacklist(self, ctx, command_name, channel, guild):
whereclause = 'guild=:guild AND command=:command AND channel=:channel AND NOT type=:type'
success = await self._set_blacklist(ctx, whereclause,
command=command_name,
channel=channel.id,
guild=guild.id,
type=BlacklistTypes.GLOBAL)
if success:
return 'Blacklisted command {0} from channel {1} `{1.id}`'.format(command_name, channel)
elif success is None:
return 'Removed command {0} blacklist from channel {1} `{1.id}`'.format(command_name, channel)
async def _add_user_whitelist(self, ctx, command_name, user, guild):
whereclause = 'guild=:guild AND command=:command AND user=:user AND NOT type=:type'
success = await self._set_blacklist(ctx, whereclause,
type_=BlacklistTypes.WHITELIST,
command=command_name,
user=user.id,
guild=guild.id,
type=BlacklistTypes.GLOBAL)
if success:
return 'Whitelisted command {0} from user {1} `{1.id}`'.format(command_name, user)
elif success is None:
return 'Removed command {0} whitelist from user {1} `{1.id}`'.format(command_name, user)
async def _add_role_whitelist(self, ctx, command_name, role, guild):
whereclause = 'guild=:guild AND command=:command AND role=:role AND NOT type=:type'
success = await self._set_blacklist(ctx, whereclause,
type_=BlacklistTypes.WHITELIST,
command=command_name,
role=role.id,
guild=guild.id,
type=BlacklistTypes.GLOBAL)
if success:
return 'Whitelisted command {0} from role {1} `{1.id}`'.format(command_name, role)
elif success is None:
return 'Removed command {0} whitelist from role {1} `{1.id}`'.format(command_name, role)
async def _add_channel_whitelist(self, ctx, command_name, channel, guild):
whereclause = 'guild=:guild AND command=:command AND channel=:channel AND NOT type=:type'
success = await self._set_blacklist(ctx, whereclause,
type_=BlacklistTypes.WHITELIST,
command=command_name,
channel=channel.id,
guild=guild.id,
type=BlacklistTypes.GLOBAL)
if success:
return 'Whitelisted command {0} from channel {1} `{1.id}`'.format(command_name, channel)
elif success is None:
return 'Removed command {0} whitelist from channel {1} `{1.id}`'.format(command_name, channel)
@command(owner_only=True)
async def test_perms(self, ctx, user: discord.Member, command_):
value = await self.bot.dbutil.check_blacklist(f'(command="{command_}" OR command IS NULL)', user, ctx, True)
await ctx.send(value or 'No special perms')
def get_rows(self, whereclause, select='*'):
session = self.bot.get_session
sql = 'SELECT %s FROM `command_blacklist` WHERE %s' % (select, whereclause)
rows = session.execute(sql).fetchall()
return rows
@staticmethod
def get_applying_perm(command_rows):
smallest = 18
smallest_row = None
for row in command_rows:
if row['type'] == BlacklistTypes.GLOBAL:
return False
if row['type'] == BlacklistTypes.WHITELIST:
v1 = PermValues.VALUES['whitelist']
else:
v1 = PermValues.VALUES['blacklist']
if row['user'] is not None:
v2 = PermValues.VALUES['user']
elif row['role'] is not None:
v2 = PermValues.VALUES['role']
else:
continue
v = v1 | v2
if v < smallest:
smallest = v
smallest_row = row
return smallest_row
@command(no_pm=True)
@cooldown(1, 30, BucketType.user)
async def role_perms(self, ctx, *role):
"""Show white- and blacklist for all or specified role"""
guild = ctx.guild
if role:
role = ' '.join(role)
role_ = get_role(role, guild.roles, name_matching=True)
if not role_:
return await ctx.send('No role found with {}'.format(role))
where = 'guild={} AND user IS NULL AND channel IS NULL AND role={}'.format(guild.id, role_.id)
else:
where = 'guild={} AND user IS NULL AND channel IS NULL AND NOT role IS NULL ORDER BY role, type'.format(guild.id)
rows = await self.bot.loop.run_in_executor(self.bot.threadpool, partial(self.get_rows, where))
if not rows:
return await ctx.send('No perms found')
paginator = Paginator('Role perms')
last = None
last_type = None
def get_command(row):
return 'All commands' if row['command'] is None else row['command']
for row in rows:
if row['role'] != last:
last = row['role']
role = guild.get_role(row['role'])
if role is None:
logger.warning('Role {} has been deleted and it has perms'.format(row['role']))
continue
last_type = row['type']
perm_type = 'Whitelisted:\n' if last_type == BlacklistTypes.WHITELIST else 'Blacklisted:\n'
paginator.add_field('{0.name} {0.id}'.format(role), perm_type + get_command(row) + '\n')
else:
s = ''
if row['type'] != last_type:
last_type = row['type']
s = '\nWhitelisted:\n' if last_type == BlacklistTypes.WHITELIST else '\nBlacklisted:\n'
s += get_command(row) + '\n'
paginator.add_to_field(s)
paginator.finalize()
pages = paginator.pages
for idx, page in enumerate(pages):
page.set_footer(text='Page {}/{}'.format(idx + 1, len(pages)))
await send_paged_message(ctx, pages, embed=True)
@command(name='commands', no_pm=True)
@cooldown(1, 30, type=BucketType.user)
async def commands_(self, ctx, user: discord.Member=None):
"""Get your or the specified users white- and blacklisted commands on this server"""
guild = ctx.guild
if not user:
user = ctx.author
if user.roles:
roles = '(role IS NULL OR role IN ({}))'.format(', '.join(map(lambda r: str(r.id), user.roles)))
else:
roles = 'role IS NULL'
where = f'guild={guild.id} AND (user={user.id} or user IS NULL) AND channel IS NULL AND {roles}'
rows = self.get_rows(where)
commands = {}
for row in rows:
name = row['command']
if name in commands:
commands[name].append(row)
else:
commands[name] = [row]
whitelist = []
blacklist = []
global_blacklist = []
for name, rows in commands.items():
row = self.get_applying_perm(rows)
name = f'`{name}`'
if row is False:
global_blacklist.append(name)
continue
# Don't want channel or server specific blacklists
if row is None:
continue
if row['type'] == BlacklistTypes.WHITELIST:
whitelist.append(name)
elif row['type'] == BlacklistTypes.BLACKLIST:
blacklist.append(name)
s = ''
if whitelist:
s += f'{user}s whitelisted commands\n' + '\n'.join(whitelist) + '\n\n'
if blacklist:
s += f'Commands blacklisted fom {user}\n' + '\n'.join(blacklist) + '\n\n'
if global_blacklist:
s += f'Commands globally blacklisted for {user}\n' + '\n'.join(global_blacklist) + '\n\n'
if not s:
s = '{0} has no special perms set up on the server {1}'.format(user, guild.name)
else:
s += '{}s perms on server {}\nChannel specific perms are not checked'.format(user, guild.name)
s = split_string(s, maxlen=2000, splitter='\n')
for ss in s:
await ctx.author.send(ss)
def setup(bot):
bot.add_cog(CommandBlacklist(bot))
<file_sep>#!/usr/bin/env python
# -*-coding=utf-8 -*-
import logging
import sys
import discord
from bot.Not_a_bot import NotABot
from bot.config import Config
from bot.formatter import LoggingFormatter
from utils import init_tf
discord_logger = logging.getLogger('discord')
discord_logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8-sig', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
discord_logger.addHandler(handler)
logger = logging.getLogger('debug')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='debug.log', encoding='utf-8-sig', mode='a')
handler.setFormatter(logging.Formatter('[{module}][{asctime}] [Thread: {thread}] [{levelname}]:{message}', datefmt='%Y-%m-%d %H:%M:%S', style='{'))
logger.addHandler(handler)
terminal = logging.getLogger('terminal')
terminal.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(LoggingFormatter('{color}[{module}][{asctime}] [Thread: {thread}] [{levelname}]:{colorend} {message}', datefmt='%Y-%m-%d %H:%M:%S', style='{'))
terminal.addHandler(handler)
terminal.info('testing colors')
terminal.debug('test')
terminal.warning('test')
terminal.error('test')
terminal.critical('test')
try:
int('d')
except:
terminal.exception('test exception')
config = Config()
if not discord.opus.is_loaded():
discord.opus.load_opus('opus')
initial_cogs = [
'admin',
'autoresponds',
'autoroles',
'botadmin',
'botmod',
'colors',
'command_blacklist',
'dbl',
'emotes',
'gachiGASM',
'hearthstone',
'images',
'jojo',
'last_seen',
'logging',
'misc',
'moderator',
'neural_networks',
'pokemon',
'privacy',
'search',
'server',
'server_specific',
'settings',
'stats',
'utils',
'voting']
terminal.info('Main bot starting up')
logger.info('Starting bot')
# Initialize tensorflow for text cmd
try:
poke_model = init_tf.init_poke_tf()
model = init_tf.init_tf()
except:
terminal.exception('Failed to initialize tensorflow')
model = None
poke_model = None
bot = NotABot(prefix='!', conf=config, pm_help=False, max_messages=10000, cogs=initial_cogs, model=model, poke_model=poke_model)
bot.run(config.token)
# We have systemctl set up in a way that different exit codes
# have different effects on restarting behavior
import sys
sys.exit(bot._exit_code)
<file_sep>import os
from datetime import datetime, timedelta
from random import Random, choice
import discord
from discord.ext.commands import BucketType
from bot.bot import command, cooldown, group, has_permissions
from bot.globals import PLAYLISTS
from cogs.cog import Cog
from utils.utilities import call_later
from utils.utilities import read_lines
class gachiGASM(Cog):
def __init__(self, bot):
super().__init__(bot)
self.gachilist = self.bot.gachilist
if not self.gachilist:
self.reload_gachilist()
self.reload_call = call_later(self._reload_and_post, self.bot.loop, self.time2tomorrow())
def __unload(self):
self.reload_call.cancel()
async def _reload_and_post(self):
self.reload_gachilist()
for guild in self.bot.guilds:
vid = Random(self.get_day()+guild.id).choice(self.gachilist)
channel = self.bot.guild_cache.dailygachi(guild.id)
if not channel:
continue
channel = guild.get_channel(channel)
if not channel:
continue
try:
await channel.send(f'Daily gachi {vid}')
except:
pass
self.reload_call = call_later(self._reload_and_post, self.bot.loop,
self.time2tomorrow())
def reload_gachilist(self):
self.bot.gachilist = read_lines(os.path.join(PLAYLISTS, 'gachi.txt'))
self.gachilist = self.bot.gachilist
@staticmethod
def time2tomorrow():
# Get utcnow, add 1 day to it and check how long it is to the next day
# by subtracting utcnow from the gained date
now = datetime.utcnow()
tomorrow = now + timedelta(days=1)
return (tomorrow.replace(hour=0, minute=0, second=0, microsecond=0)
- now).total_seconds()
@staticmethod
def get_day():
return (datetime.utcnow() - datetime.min).days
@command()
@cooldown(1, 2, BucketType.channel)
async def gachify(self, ctx, *, words):
"""Gachify a string"""
if ' ' not in words:
# We need to undo the string view or it will skip the first word
ctx.view.undo()
await self.gachify2.invoke(ctx)
else:
return await ctx.send(words.replace(' ', ' ♂ ').upper())
@command()
@cooldown(1, 2, BucketType.channel)
async def gachify2(self, ctx, *, words):
"""An alternative way of gachifying"""
return await ctx.send('♂ ' + words.replace(' ', ' ♂ ').upper() + ' ♂')
@command(ignore_extra=True, aliases=['rg'])
@cooldown(1, 5, BucketType.channel)
async def randomgachi(self, ctx):
await ctx.send(choice(self.gachilist))
@group(ignore_extra=True, invoke_without_command=True)
@cooldown(1, 5, BucketType.channel)
async def dailygachi(self, ctx):
await ctx.send(Random(self.get_day()+ctx.guild.id).choice(self.gachilist))
@dailygachi.command()
@cooldown(1, 5)
@has_permissions(manage_guild=True)
async def subscribe(self, ctx, *, channel: discord.TextChannel=None):
if channel:
await self.bot.guild_cache.set_dailygachi(ctx.guild.id, channel.id)
return await ctx.send(f'New dailygachi channel set to {channel}')
channel = self.bot.guild_cache.dailygachi(ctx.guild.id)
channel = ctx.guild.get_channel(channel)
if channel:
await ctx.send(f'Current dailygachi channel is {channel}')
else:
await ctx.send('No dailygachi channel set')
@dailygachi.command(ignore_extra=True)
@cooldown(1, 5)
@has_permissions(manage_guild=True)
async def unsubscribe(self, ctx):
await self.bot.guild_cache.set_dailygachi(ctx.guild.id, None)
await ctx.send('Dailygachi channel no longer set')
def setup(bot):
bot.add_cog(gachiGASM(bot))
<file_sep>aiohttp
aioredis
ansicolors
beautifulsoup4
colormath
colorthief
colour
dblpy
emoji
imagehash
opencv-python
git+https://github.com/cristobalcl/geopatterns.git#egg=geopatterns
gtts
lxml
matplotlib
numpy
pillow
psutil
pymysql
python-magic
sanic
selenium
sqlalchemy
validators
youtube_dl
git+https://github.com/Rapptz/discord.py@rewrite#egg=discord.py[voice]
<file_sep>import asyncio
import functools
import inspect
import logging
import os
import pprint
import re
import shlex
import subprocess
import sys
import textwrap
import time
import traceback
from enum import IntEnum
from importlib import reload, import_module
from io import BytesIO, StringIO
from pprint import PrettyPrinter
from types import ModuleType
import aiohttp
import discord
from discord.errors import HTTPException, InvalidArgument
from discord.ext.commands.core import GroupMixin
from discord.user import BaseUser
from sqlalchemy.exc import SQLAlchemyError
from bot.bot import command
from bot.config import Config
from bot.converters import PossibleUser
from bot.globals import SFX_FOLDER
from cogs.cog import Cog
from utils.utilities import split_string
from utils.utilities import (y_n_check, basic_check, y_check, check_import,
parse_timeout,
call_later, seconds2str, test_url)
logger = logging.getLogger('debug')
terminal = logging.getLogger('terminal')
class ExitStatus(IntEnum):
PreventRestart = 2
ForceRestart = 3
RestartNormally = 0
class NoStringWrappingPrettyPrinter(PrettyPrinter):
def _format_str(self, s):
if '\n' in s:
s = f'"""{s}"""'
else:
s = f'"{s}"'
return s
def _format(self, object, stream, *args):
if isinstance(object, str):
stream.write(self._format_str(object))
else:
super()._format(object, stream, *args)
class NonFormatted:
def __init__(self, original):
self.original = original
class BotAdmin(Cog):
def __init__(self, bot):
super().__init__(bot)
self._last_result = None
def load_extension(self, name, lib=None):
"""
Reworked implementation of the default bot extension loader
It works exactly the same unless you provide the lib argument manually
That way you can import the lib before this method to check for
errors in the file and pass the returned lib to this function if no errors were thrown.
Args:
name: str
name of the extension
lib: Module
lib returned from `import_module`
Raises:
ClientException
Raised when no setup function is found or when lib isn't a valid module
"""
if lib is None:
# Fall back to default implementation when lib isn't provided
return self.bot.load_extension(name)
if name in self.bot.extensions:
return
if not isinstance(lib, ModuleType):
raise discord.ClientException("lib isn't a valid module")
lib = import_module(name)
if not hasattr(lib, 'setup'):
del lib
del sys.modules[name]
raise discord.ClientException('extension does not have a setup function')
lib.setup(self.bot)
self.bot.extensions[name] = lib
async def reload_extension(self, name):
"""
Reload an cog with the given import path
"""
def do_reload():
t = time.perf_counter()
# Check that the module is importable
try:
# Check if code compiles. If not returns the error
# Only check this cog as the operation takes a while and
# Other cogs can be reloaded if they fail unlike this
if name == 'cogs.botadmin':
e = check_import(name)
if e:
return f'```py\n{e}\n```'
lib = import_module(name)
except:
logger.exception(f'Failed to reload extension {name}')
return f'Failed to import module {name}.\nError has been logged'
try:
self.bot.unload_extension(name)
self.load_extension(name, lib=lib)
except Exception:
logger.exception('Failed to reload extension %s' % name)
terminal.exception('Failed to reload extension %s' % name)
return 'Could not reload %s because of an error' % name
return 'Reloaded {} in {:.0f}ms'.format(name, (time.perf_counter()-t)*1000)
return await self.bot.loop.run_in_executor(self.bot.threadpool, do_reload)
async def reload_multiple(self, names):
"""
Same as reload_extension but for multiple files
"""
if not names:
return "No module names given",
messages = []
def do_reload():
for name in names:
t = time.perf_counter()
# Check that the module is importable
try:
# Check if code compiles. If not returns the error
# Only check this cog as the operation takes a while and
# Other cogs can be reloaded if they fail unlike this
if name == 'cogs.botadmin':
e = check_import(name)
if e:
return f'```py\n{e}\n```'
lib = import_module(name)
except:
logger.exception(f'Failed to reload extension {name}')
messages.append(f'Failed to import module {name}.\nError has been logged')
continue
try:
self.bot.unload_extension(name)
self.load_extension(name, lib=lib)
except Exception:
logger.exception('Failed to reload extension %s' % name)
messages.append('Could not reload %s because of an error' % name)
continue
t = time.perf_counter() - t
messages.append('Reloaded {} in {:.0f}ms'.format(name, t * 1000))
return messages
return await self.bot.loop.run_in_executor(self.bot.threadpool, do_reload)
@command(name='eval', owner_only=True)
async def eval_(self, ctx, *, code: str):
context = globals().copy()
context.update({'ctx': ctx,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'channel': ctx.channel,
'bot': ctx.bot,
'loop': ctx.bot.loop,
'_': self._last_result})
# A quick hack to run async functions in normal function
# It's not pretty but it does what it needs
def disgusting(coro_or_fut):
if isinstance(coro_or_fut, asyncio.Future):
return asyncio.run_coroutine_threadsafe(asyncio.wait_for(coro_or_fut, 60, loop=ctx.bot.loop), loop=ctx.bot.loop).result()
return asyncio.run_coroutine_threadsafe(coro_or_fut, loop=ctx.bot.loop).result()
# Gets source of object
def get_source(o):
source = inspect.getsource(o)
original_source = textwrap.dedent(source)
# Put zero width space between backticks so they can be within a codeblock
source = original_source.replace('```', '`\u200b`\u200b`')
source = f'```py\n{source}\n```'
if len(source) > 2000:
return original_source
return source
def no_pformat(o):
return NonFormatted(o)
def code_block(s, pretty_print=True):
if not isinstance(s, str) or pretty_print:
s = NoStringWrappingPrettyPrinter(width=1).pformat(s)
return f'```py\n{s}\n```'
context['await'] = disgusting
context['source'] = get_source
context['code_block'] = code_block
context['no_format'] = no_pformat
if code.startswith('```py\n') and code.endswith('\n```'):
code = code[6:-4]
code = textwrap.indent(code, ' ')
lines = list(filter(bool, code.split('\n')))
last = lines[-1]
if not last.strip().startswith('return'):
whitespace = len(last) - len(last.strip())
if whitespace > 2:
lines.append(' return')
else:
lines[-1] = ' return ' + last.strip() # if code doesn't have a return make one
lines = '\n'.join(lines)
code = f'def f():\n{lines}\nx = f()' # Transform the code to a function
local = {} # The variables outside of the function f() get stored here
try:
def run():
exec(compile(code, '<eval>', 'exec'), context, local)
await self.bot.loop.run_in_executor(self.bot.threadpool, run)
retval = local['x']
self._last_result = retval
if not isinstance(retval, str) and not isinstance(retval, NonFormatted):
retval = NoStringWrappingPrettyPrinter(width=1).pformat(retval)
except Exception as e:
self._last_result = e
retval = f'```py\n{e}\n{traceback.format_exc()}\n```'
if not isinstance(retval, str):
retval = str(retval)
if len(retval) > 2000:
await ctx.send(file=discord.File(StringIO(retval), filename='result.py'))
else:
await ctx.send(retval)
@command(name='exec', owner_only=True)
async def exec_(self, ctx, *, message):
context = globals().copy()
context.update({'ctx': ctx,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'channel': ctx.channel,
'bot': ctx.bot})
try:
retval = await self.bot.loop.run_in_executor(self.bot.threadpool, exec, message, context)
if asyncio.iscoroutine(retval):
retval = await retval
except Exception as e:
logger.exception('Failed to eval')
retval = 'Exception\n%s' % e.__name__
if not isinstance(retval, str):
retval = str(retval)
await ctx.send(retval)
@command(owner_only=True, aliases=['db_eval'])
async def dbeval(self, ctx, *, query):
try:
r, t = await self.bot.dbutil.execute(query, commit=True, measure_time=True)
except SQLAlchemyError:
logger.exception('Failed to execute eval query')
return await ctx.send('Failed to execute query. Exception logged')
embed = discord.Embed(title='sql', description=f'Query ran succesfully in {t*1000:.0f} ms')
embed.add_field(name='input', value=f'```sql\n{query}\n```', inline=False)
if r.returns_rows:
rows = r.fetchall()
if len(rows) > 30:
value = f'Too many results {len(rows)} > 30'
else:
value = '```py\n' + pprint.pformat(rows, compact=True)[:1000] + '```'
else:
value = f'{r.rowcount} rows were inserted/modified/deleted'
embed.add_field(name='output', value=value, inline=False)
await ctx.send(embed=embed)
def _recursively_remove_all_commands(self, command, bot=None):
commands = []
for _command in command.commands.copy().values():
if isinstance(_command, GroupMixin):
l = self._recursively_remove_all_commands(_command)
command.remove_command(_command.name)
commands.append(l)
else:
commands.append(command.remove_command(_command.name))
if bot:
bot.remove_command(command.name)
return command, commands
def _recursively_add_all_commands(self, commands, bot):
for command_ in commands:
if isinstance(command_, tuple):
command_, commands_ = command_
bot.add_command(command_)
self._recursively_add_all_commands(commands_, command_)
else:
bot.add_command(command_)
@command(owner_only=True)
async def reload(self, ctx, *, name):
cog_name = 'cogs.%s' % name if not name.startswith('cogs.') else name
await ctx.send(await self.reload_extension(cog_name))
@command(owner_only=True)
async def reload_all(self, ctx):
messages = await self.reload_multiple(self.bot.default_cogs)
messages = split_string(messages, list_join='\n', splitter='\n')
for msg in messages:
await ctx.send(msg)
@command(owner_only=True)
async def load(self, ctx, cog):
cog_name = 'cogs.%s' % cog if not cog.startswith('cogs.') else cog
t = time.perf_counter()
try:
await self.bot.loop.run_in_executor(self.bot.threadpool,
self.bot.load_extension, cog_name)
except Exception as e:
logger.exception('Failed to load')
return await ctx.send('Could not load %s because of %s' % (cog_name, e.__name__))
await ctx.send('Loaded {} in {:.0f}ms'.format(cog_name, (time.perf_counter() - t) * 1000))
@command(owner_only=True)
async def unload(self, ctx, cog):
cog_name = 'cogs.%s' % cog if not cog.startswith('cogs.') else cog
t = time.perf_counter()
try:
await self.bot.loop.run_in_executor(self.bot.threadpool,
self.bot.unload_extension, cog_name)
except Exception as e:
return await ctx.send('Could not unload %s because of %s' % (cog_name, e.__name__))
await ctx.send('Unloaded {} in {:.0f}ms'.format(cog_name, (time.perf_counter() - t) * 1000))
@command(owner_only=True)
async def shutdown(self, ctx):
await self._shutdown(ctx, ExitStatus.PreventRestart)
@command(owner_only=True)
async def restart(self, ctx):
await self._shutdown(ctx, ExitStatus.ForceRestart)
async def _shutdown(self, ctx, exit_code: ExitStatus):
try:
await ctx.send('Beep boop :wave:')
except HTTPException:
pass
logger.info('Unloading extensions')
self.bot._exit_code = int(exit_code)
def unload_all():
for ext in list(self.bot.extensions.keys()):
try:
self.bot.unload_extension(ext)
except:
pass
logger.info('Unloaded extensions')
await self.bot.loop.run_in_executor(self.bot.threadpool, unload_all)
await self.bot.aiohttp_client.close()
logger.info('Closed aiohttp client')
redis = getattr(self.bot, 'redis', None)
if redis:
redis.close()
await redis.wait_closed()
try:
audio = self.bot.get_cog('Audio')
if audio:
await audio.shutdown()
try:
session = self.bot._Session
engine = self.bot._engine
session.close_all()
engine.dispose()
except:
logger.exception('Failed to shut db down gracefully')
logger.info('Closed db connection')
try:
logger.info('Logging out')
await self.bot.logout()
logger.info('Logged out')
except:
pass
except Exception:
logger.exception('Bot shutdown error')
finally:
# We have systemctl set up in a way that different exit codes
# have different effects on restarting behavior
sys.exit(int(exit_code))
@command(owner_only=True)
async def notice_me(self, ctx):
guild = ctx.message.guild
if guild.id == 217677285442977792:
try:
await self.bot.request_offline_members(guild)
except InvalidArgument:
pass
for member in list(guild.members):
await self.bot._wants_to_be_noticed(member, guild)
@command(owner_only=True)
async def reload_dbutil(self, ctx):
reload(import_module('bot.dbutil'))
from bot import dbutil
self.bot._dbutil = dbutil.DatabaseUtils(self.bot)
await ctx.send(':ok_hand:')
@command(owner_only=True)
async def reload_config(self, ctx):
try:
config = Config()
except:
logger.exception('Failed to reload config')
await ctx.send('Failed to reload config')
return
self.bot.config = config
await ctx.send(':ok_hand:')
@command(owner_only=True)
async def cache_guilds(self):
for guild in self.bot.guilds:
sql = 'SELECT * FROM `guilds` WHERE guild=%s' % guild.id
row = await self.bot.dbutil.execute(sql).first()
if not row:
sql = 'INSERT INTO `guilds` (`guild`, `prefix`) ' \
'VALUES (%s, "%s")' % (guild.id, self.bot.command_prefix)
try:
await self.bot.dbutil.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to cache guild')
d = {'prefix': self.bot.command_prefix}
else:
d = {**row}
del d['guild']
self.bot.guild_cache.update_guild(guild.id, **d)
@command(owner_only=True)
async def reload_module(self, ctx, module_name):
try:
reload(import_module(module_name))
except Exception as e:
return await ctx.send('Failed to reload module %s because of %s' % (module_name, e.__name__))
await ctx.send('Reloaded module %s' % module_name)
@command(owner_only=True)
async def runas(self, ctx, user: discord.User=None):
self.bot._runas = user
await ctx.send(f'Now running as {user}')
@command(owner_only=True, ignore_extra=True)
async def update_bot(self, ctx, *, options=None):
"""Does a git pull"""
cmd = 'git pull'.split(' ')
if options:
cmd.extend(shlex.split(options))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = await self.bot.loop.run_in_executor(self.bot.threadpool, p.communicate)
out = out.decode('utf-8')
if err:
out = err.decode('utf-8') + out
# Only tries to update files in the cogs folder
files = re.findall(r'(cogs/\w+)(?:.py *|)', out)
if len(out) > 2000:
out = out[:1996] + '...'
await ctx.send(out)
if files:
files = [f.replace('/', '.') for f in files]
await ctx.send(f'Do you want to reload files `{"` `".join(files)}`')
try:
msg = await self.bot.wait_for('message', check=basic_check(ctx.author, ctx.channel), timeout=30)
except asyncio.TimeoutError:
return await ctx.send('Timed out')
if not y_n_check(msg):
return await ctx.send('Invalid answer. Not auto reloading')
if not y_check(msg.content):
return await ctx.send('Not auto updating')
messages = split_string(await self.reload_multiple(files), list_join='\n', splitter='\n')
for msg in messages:
await ctx.send(msg)
@command(owner_only=True)
async def add_sfx(self, ctx, file=None, name=None):
client = self.bot.aiohttp_client
if file and name:
url = file
elif not file:
if not ctx.message.attachments:
return await ctx.send('No files found')
url = ctx.message.attachments[0].url
name = url.split('/')[-1]
else:
if not test_url(file):
if not ctx.message.attachments:
return await ctx.send('No files found')
url = ctx.message.attachments[0].url
name = file
else:
url = file
name = url.split('/')[-1]
p = os.path.join(SFX_FOLDER, name)
if os.path.exists(p):
return await ctx.send(f'File {name} already exists')
try:
async with client.get(url) as r:
data = BytesIO()
chunk = 4096
async for d in r.content.iter_chunked(chunk):
data.write(d)
data.seek(0)
except aiohttp.ClientError:
logger.exception('Could not download image %s' % url)
await ctx.send('Failed to download %s' % url)
else:
def write():
with open(p, 'wb') as f:
f.write(data.getvalue())
if os.path.exists(p):
return await ctx.send(f'File {name} already exists')
await self.bot.loop.run_in_executor(self.bot.threadpool, write)
await ctx.send(f'Added sfx {name}')
@command(owner_only=True)
async def botban(self, ctx, user: PossibleUser, *, reason):
"""
Ban someone from using this bot. Owner only
"""
if isinstance(user, BaseUser):
name = user.name + ' '
user_id = user.id
else:
name = ''
user_id = user
try:
await self.bot.dbutil.botban(user_id, reason)
except SQLAlchemyError:
logger.exception(f'Failed to botban user {name}{user_id}')
return await ctx.send(f'Failed to ban user {name}`{user_id}`')
await ctx.send(f'Banned {name}`{user_id}` from using this bot')
@command(owner_only=True)
async def botunban(self, ctx, user: PossibleUser):
"""
Remove someones botban
"""
if isinstance(user, BaseUser):
name = user.name + ' '
user_id = user.id
else:
name = ''
user_id = user
try:
await self.bot.dbutil.botunban(user_id)
except SQLAlchemyError:
logger.exception(f'Failed to remove botban of user {name}{user_id}')
return await ctx.send(f'Failed to remove botban of user {name}`{user_id}`')
await ctx.send(f'Removed the botban of {name}`{user_id}`')
@command(owner_only=True)
async def leave_guild(self, ctx, guild_id: int):
g = self.bot.get_guild(guild_id)
if not g:
return await ctx.send(f'Guild {guild_id} not found')
await g.leave()
await ctx.send(f'Left guild {g.name} `{g.id}`')
@command(owner_only=True)
async def blacklist_guild(self, ctx, guild_id: int, *, reason):
try:
await self.bot.dbutil.blacklist_guild(guild_id, reason)
except SQLAlchemyError:
logger.exception('Failed to blacklist guild')
return await ctx.send('Failed to blacklist guild\nException has been logged')
guild = self.bot.get_guild(guild_id)
if guild:
await guild.leave()
s = f'{guild} `{guild_id}`' if guild else guild_id
await ctx.send(f'Blacklisted guild {s}')
@command(owner_only=True)
async def unblacklist_guild(self, ctx, guild_id: int):
try:
await self.bot.dbutil.unblacklist_guild(guild_id)
except SQLAlchemyError:
logger.exception('Failed to unblacklist guild')
return await ctx.send('Failed to unblacklist guild\nException has been logged')
guild = self.bot.get_guild(guild_id)
s = f'{guild} `{guild_id}`' if guild else guild_id
await ctx.send(f'Unblacklisted guild {s}')
@command(owner_only=True, ignore_extra=True)
async def restart_db(self, ctx):
def reconnect():
t = time.perf_counter()
session = self.bot._Session
engine = self.bot._engine
session.close_all()
engine.dispose()
self.bot._setup_db()
del session
del engine
return (time.perf_counter()-t)*1000
t = await self.bot.loop.run_in_executor(self.bot.threadpool, reconnect)
await ctx.send(f'Reconnected to db in {t:.0f}ms')
def remove_call(self, _, msg_id):
self.bot.call_laters.pop(msg_id, None)
@command(owner_only=True)
async def call_later(self, ctx, *, call):
msg = ctx.message
# Parse timeout can basically parse anything where you want time
# separated from the rest
run_in, call = parse_timeout(call)
msg.content = f'{ctx.prefix}{call}'
new_ctx = await self.bot.get_context(msg)
self.bot.call_laters[msg.id] = call_later(self.bot.invoke, self.bot.loop,
run_in.total_seconds(), new_ctx,
after=functools.partial(self.remove_call, msg_id=msg.id))
await ctx.send(f'Scheduled call `{msg.id}` to run in {seconds2str(run_in.total_seconds(), False)}')
@command(owner_only=True)
async def add_todo(self, ctx, priority: int=0, *, todo):
try:
rowid = await self.bot.dbutil.add_todo(todo, priority=priority)
except SQLAlchemyError:
logger.exception('Failed to add todo')
return await ctx.send('Failed to add to todo')
await ctx.send(f'Added todo with priority {priority} and id {rowid}')
@command(owner_only=True, name='todo')
async def list_todo(self, ctx, limit: int=3):
try:
rows = (await self.bot.dbutil.get_todo(limit)).fetchall()
except SQLAlchemyError:
logger.exception('Failed to get todo')
return await ctx.send('Failed to get todo')
if not rows:
return await ctx.send('Nothing to do')
s = ''
for row in rows:
s += f'{row["id"]} {row["time"]} `{row["priority"]}` {row["todo"]}\n\n'
if len(rows) > 2000:
return await ctx.send('Too long todo')
await ctx.send(s)
@command(owner_only=True)
async def complete_todo(self, ctx, id: int):
sql = 'UPDATE `todo` SET completed_at=CURRENT_TIMESTAMP, completed=TRUE WHERE id=%s AND completed=FALSE' % id
res = await self.bot.dbutil.execute(sql)
await ctx.send(f'{res.rowcount} rows updated')
@command(owner_only=True)
async def reset_cooldown(self, ctx, command):
cmd = self.bot.all_commands.get(command, None)
if not cmd:
return await ctx.send(f'Command {command} not found')
cmd.reset_cooldown(ctx)
await ctx.send(f'Cooldown of {cmd.name} reset')
@command(owner_only=True)
async def send_message(self, ctx, channel: discord.TextChannel, *, message):
try:
await channel.send(message)
except discord.HTTPException as e:
await ctx.send(f'Failed to send message\n```py\n{e}\n```')
except:
await ctx.send('Failed to send message')
@command(owner_only=True, aliases=['add_changelog'])
async def add_changes(self, ctx, *, changes):
try:
rowid = await self.bot.dbutil.add_changes(changes)
except SQLAlchemyError:
logger.exception('Failed to add changes')
return await ctx.send('Failed to add to todo')
await ctx.send(f'Added changes with id {rowid}')
def setup(bot):
bot.add_cog(BotAdmin(bot))
<file_sep>import base64
import logging
import os
import time
from asyncio import Lock
from functools import partial
from io import BytesIO
from random import randint
from typing import Optional
from PIL import (Image, ImageSequence, ImageFont, ImageDraw, ImageChops,
GifImagePlugin)
from bs4 import BeautifulSoup
from discord import File
from discord.ext.commands import BucketType, BotMissingPermissions
from discord.ext.commands.errors import BadArgument
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.common.exceptions import WebDriverException
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from bot.bot import command, cooldown
from bot.converters import CleanContent
from bot.exceptions import NoPokeFoundException, BotException
from cogs.cog import Cog
from utils.imagetools import (resize_keep_aspect_ratio, image_from_url,
gradient_flash, sepia, optimize_gif, func_to_gif,
get_duration, convert_frames, apply_transparency)
from utils.utilities import (get_image_from_message, find_coeffs, check_botperm,
split_string)
logger = logging.getLogger('debug')
terminal = logging.getLogger('terminal')
TEMPLATES = os.path.join('data', 'templates')
class Pokefusion:
RANDOM = '%'
def __init__(self, client, bot):
self._last_dex_number = 0
self._pokemon = {}
self._poke_reverse = {}
self._last_updated = 0
self._client = client
self._data_folder = os.path.join(os.getcwd(), 'data', 'pokefusion')
self._driver_lock = Lock(loop=bot.loop)
self._bot = bot
self._update_lock = Lock(loop=bot.loop)
p = self.bot.config.chromedriver
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
binary = self.bot.config.chrome
if binary:
options.binary_location = binary
self.driver = Chrome(p, chrome_options=options)
@property
def bot(self):
return self._bot
@property
def last_dex_number(self):
return self._last_dex_number
@property
def client(self):
return self._client
def is_dex_number(self, s):
# No need to convert when the number is that big
if len(s) > 5:
return False
try:
return int(s) <= self.last_dex_number
except ValueError:
return False
async def cache_types(self, start=1):
name = 'sprPKMType_{}.png'
url = 'http://pokefusion.japeal.com/sprPKMType_{}.png'
while True:
r = await self.client.get(url.format(start))
if r.status == 404:
r.close()
break
with open(os.path.join(self._data_folder, name.format(start)), 'wb') as f:
f.write(await r.read())
start += 1
async def update_cache(self):
if self._update_lock.locked():
# If and update is in progress wait for it to finish and then continue
await self._update_lock.acquire()
self._update_lock.release()
return
await self._update_lock.acquire()
success = False
try:
logger.info('Updating pokecache')
r = await self.client.get('http://pokefusion.japeal.com/PKMSelectorV3.php')
soup = BeautifulSoup(await r.text(), 'lxml')
selector = soup.find(id='s1')
if selector is None:
logger.debug('Failed to update pokefusion cache')
return False
pokemon = selector.find_all('option')
for idx, p in enumerate(pokemon[1:]):
name = ' #'.join(p.text.split(' #')[:-1])
self._pokemon[name.lower()] = idx + 1
self._poke_reverse[idx + 1] = name.lower()
self._last_dex_number = len(pokemon) - 1
types = filter(lambda f: f.startswith('sprPKMType_'), os.listdir(self._data_folder))
await self.cache_types(start=max(len(list(types)), 1))
self._last_updated = time.time()
success = True
except:
logger.exception('Failed to update pokefusion cache')
finally:
self._update_lock.release()
return success
def get_by_name(self, name):
poke = self._pokemon.get(name.lower())
if poke is None:
for poke_, v in self._pokemon.items():
if name in poke_:
return v
return poke
def get_by_dex_n(self, n: int):
return n if n <= self.last_dex_number else None
def get_pokemon(self, name):
if name == self.RANDOM and self.last_dex_number > 0:
return randint(1, self._last_dex_number)
if self.is_dex_number(name):
return int(name)
else:
return self.get_by_name(name)
async def get_url(self, url):
# Attempt at making phantomjs async friendly
# After visiting the url remember to put 1 item in self.queue
# Otherwise the browser will be locked
# If lock is not locked lock it until this operation finishes
unlock = False
if not self._driver_lock.locked():
await self._driver_lock.acquire()
unlock = True
f = partial(self.driver.get, url)
await self.bot.loop.run_in_executor(self.bot.threadpool, f)
if unlock:
try:
self._driver_lock.release()
except RuntimeError:
pass
async def fuse(self, poke1=RANDOM, poke2=RANDOM, poke3=None):
# Update cache once per day
if time.time() - self._last_updated > 86400:
if not await self.update_cache():
raise BotException('Could not cache pokemon')
dex_n = []
for p in (poke1, poke2):
poke = self.get_pokemon(p)
if poke is None:
raise NoPokeFoundException(p)
dex_n.append(poke)
if poke3 is None:
color = 0
else:
color = self.get_pokemon(poke3)
if color is None:
raise NoPokeFoundException(poke3)
url = 'http://pokefusion.japeal.com/PKMColourV5.php?ver=3.2&p1={}&p2={}&c={}&e=noone'.format(*dex_n, color)
async with self._driver_lock:
try:
await self.get_url(url)
except UnexpectedAlertPresentException:
self.driver.switch_to.alert.accept()
raise BotException('Invalid pokemon given')
data = self.driver.execute_script("return document.getElementById('image1').src")
types = self.driver.execute_script("return document.querySelectorAll('*[width=\"30\"]')")
name = self.driver.execute_script("return document.getElementsByTagName('b')[0].textContent")
data = data.replace('data:image/png;base64,', '', 1)
img = Image.open(BytesIO(base64.b64decode(data)))
type_imgs = []
for tp in types:
file = tp.get_attribute('src').split('/')[-1].split('?')[0]
try:
im = Image.open(os.path.join(self._data_folder, file))
type_imgs.append(im)
except (FileNotFoundError, OSError):
raise BotException('Error while getting type images')
bg = Image.open(os.path.join(self._data_folder, 'poke_bg.png'))
# Paste pokemon in the middle of the background
x, y = (bg.width//2-img.width//2, bg.height//2-img.height//2)
bg.paste(img, (x, y), img)
w, h = type_imgs[0].size
padding = 2
# Total width of all type images combined with padding
type_w = len(type_imgs) * (w + padding)
width = bg.width
start_x = (width - type_w)//2
y = y + img.height
for tp in type_imgs:
bg.paste(tp, (start_x, y), tp)
start_x += w + padding
font = ImageFont.truetype(os.path.join('M-1c', 'mplus-1c-bold.ttf'), 36)
draw = ImageDraw.Draw(bg)
w, h = draw.textsize(name, font)
draw.text(((bg.width-w)//2, bg.height//2-img.height//2 - h), name, font=font, fill='black')
s = 'Fusion of {} and {}'.format(self._poke_reverse[dex_n[0]], self._poke_reverse[dex_n[1]])
if color:
s += ' using the color palette of {}'.format(self._poke_reverse[color])
return bg, s
class Images(Cog):
def __init__(self, bot):
super().__init__(bot)
self.threadpool = bot.threadpool
try:
self._pokefusion = Pokefusion(self.bot.aiohttp_client, bot)
except WebDriverException:
terminal.exception('failed to load pokefusion')
self._pokefusion = None
def __unload(self):
if self._pokefusion:
self._pokefusion.driver.quit()
@staticmethod
def __local_check(ctx):
if not check_botperm('attach_files', ctx=ctx):
raise BotMissingPermissions(('attach_files', ))
return True
async def image_func(self, func, *args, **kwargs):
return await self.bot.loop.run_in_executor(self.bot.threadpool, func, *args, **kwargs)
@staticmethod
def save_image(img, format='PNG'):
data = BytesIO()
img.save(data, format)
data.seek(0)
return data
async def _get_image(self, ctx, image):
img = await get_image_from_message(ctx, image)
if img is None:
if image is not None:
await ctx.send(f'No image found from {image}')
else:
await ctx.send('Please input a mention, emote or an image when using the command')
return
img = await self._dl_image(ctx, img)
return img
async def _dl_image(self, ctx, url):
try:
img = await image_from_url(url, self.bot.aiohttp_client)
except OverflowError:
await ctx.send('Failed to download. File is too big')
except TypeError:
await ctx.send('Link is not a direct link to an image')
else:
return img
@command(ignore_extra=True)
@cooldown(3, 5, type=BucketType.guild)
async def anime_deaths(self, ctx, image=None):
"""Generate a top 10 anime deaths image based on provided image"""
path = os.path.join(TEMPLATES, 'saddest-anime-deaths.png')
img = await self._get_image(ctx, image)
if img is None:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
x, y = 9, 10
w, h = 854, 480
template = Image.open(path)
img = resize_keep_aspect_ratio(img, (w, h), can_be_bigger=False, resample=Image.BILINEAR)
new_w, new_h = img.width, img.height
if new_w != w:
x += int((w - new_w)/2)
if new_h != h:
y += int((h - new_h) / 2)
img = img.convert("RGBA")
template.paste(img, (x, y), img)
return self.save_image(template)
await ctx.send(file=File(await self.image_func(do_it), filename='top10-anime-deaths.png'))
@command(ignore_extra=True)
@cooldown(3, 5, type=BucketType.guild)
async def anime_deaths2(self, ctx, image=None):
"""same as anime_deaths but with a transparent bg"""
path = os.path.join(TEMPLATES, 'saddest-anime-deaths2.png')
img = await self._get_image(ctx, image)
if img is None:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
x, y = 9, 10
w, h = 854, 480
template = Image.open(path)
img = resize_keep_aspect_ratio(img, (w, h), can_be_bigger=False, resample=Image.BILINEAR)
new_w, new_h = img.width, img.height
if new_w != w:
x += int((w - new_w)/2)
if new_h != h:
y += int((h - new_h) / 2)
img = img.convert("RGBA")
template.paste(img, (x, y), img)
return self.save_image(template)
await ctx.send(file=File(await self.image_func(do_it), filename='top10-anime-deaths.png'))
@command(ignore_extra=True)
@cooldown(3, 5, type=BucketType.guild)
async def trap(self, ctx, image=None):
"""Is it a trap?
"""
img = await self._get_image(ctx, image)
if img is None:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
path = os.path.join(TEMPLATES, 'is_it_a_trap.png')
path2 = os.path.join(TEMPLATES, 'is_it_a_trap_layer.png')
img = img.convert("RGBA")
x, y = 820, 396
w, h = 355, 505
rotation = -22.5
img = resize_keep_aspect_ratio(img, (w, h), can_be_bigger=False,
resample=Image.BILINEAR)
img = img.rotate(rotation, expand=True, resample=Image.BILINEAR)
x_place = x - int(img.width / 2)
y_place = y - int(img.height / 2)
template = Image.open(path)
template.paste(img, (x_place, y_place), img)
layer = Image.open(path2)
template.paste(layer, (0, 0), layer)
return self.save_image(template)
await ctx.send(file=File(await self.image_func(do_it), filename='is_it_a_trap.png'))
@command(ignore_extra=True, aliases=['jotaro_no'])
@cooldown(3, 5, BucketType.guild)
async def jotaro(self, ctx, image=None):
"""Jotaro wasn't pleased"""
img = await self._get_image(ctx, image)
if img is None:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
# The size we want from the transformation
width = 524
height = 326
d_x = 90
w, h = img.size
coeffs = find_coeffs(
[(d_x, 0), (width - d_x, 0), (width, height), (0, height)],
[(0, 0), (w, 0), (w, h), (0, h)])
img = img.transform((width, height), Image.PERSPECTIVE, coeffs,
Image.BICUBIC)
template = os.path.join(TEMPLATES, 'jotaro.png')
template = Image.open(template)
white = Image.new('RGBA', template.size, 'white')
x, y = 9, 351
white.paste(img, (x, y))
white.paste(template, mask=template)
return self.save_image(white)
await ctx.send(file=File(await self.image_func(do_it), filename='jotaro_no.png'))
@command(ignore_extra=True, aliases=['jotaro2'])
@cooldown(2, 5, BucketType.guild)
async def jotaro_photo(self, ctx, image=None):
"""Jotaro takes an image and looks at it"""
# Set to false because discord doesn't embed it correctly
# Should be used if it can be embedded since the file size is much smaller
use_webp = False
img = await self._get_image(ctx, image)
if img is None:
return
extension = 'webp' if use_webp else 'gif'
await ctx.trigger_typing()
def do_it():
nonlocal img
r = 34.7
x = 6
y = -165
width = 468
height = 439
duration = [120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120,
80, 120, 120, 120, 120, 120, 30, 120, 120, 120, 120, 120,
120, 120, 760, 2000] # Frame timing
frames = [frame.copy().convert('RGBA') for frame in ImageSequence.Iterator(Image.open(os.path.join(TEMPLATES, 'jotaro_photo.gif')))]
photo = os.path.join(TEMPLATES, 'photo.png')
finger = os.path.join(TEMPLATES, 'finger.png')
im = Image.open(photo)
img = img.convert('RGBA')
img = resize_keep_aspect_ratio(img, (width, height), resample=Image.BICUBIC,
can_be_bigger=False, crop_to_size=True,
center_cropped=True, background_color='black')
w, h = img.size
width, height = (472, 441)
coeffs = find_coeffs(
[(0, 0), (437, 0), (width, height), (0, height)],
[(0, 0), (w, 0), (w, h), (0, h)])
img = img.transform((width, height), Image.PERSPECTIVE, coeffs,
Image.BICUBIC)
img = img.rotate(r, resample=Image.BICUBIC, expand=True)
im.paste(img, box=(x, y), mask=img)
finger = Image.open(finger)
im.paste(finger, mask=finger)
frames[-1] = im
if use_webp:
# We save room for some colors when not using the shadow in a gif
shadow = os.path.join(TEMPLATES, 'photo.png')
im.alpha_composite(shadow)
kwargs = {}
else:
# Duration won't work in the save() params when using a gif so I have to do it this way
frames[0].info['duration'] = duration
kwargs = {'optimize': True}
file = BytesIO()
frames[0].save(file, format=extension, save_all=True, append_images=frames[1:], duration=duration, **kwargs)
if file.tell() > 8000000:
raise BotException('Generated image was too big in filesize')
file.seek(0)
return optimize_gif(file.getvalue())
await ctx.send(file=File(await self.image_func(do_it), filename='jotaro_photo.{}'.format(extension)))
@command(ignore_extra=True, aliases=['jotaro3'])
@cooldown(2, 5, BucketType.guild)
async def jotaro_smile(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
im = Image.open(os.path.join(TEMPLATES, 'jotaro_smile.png'))
img = img.convert('RGBA')
i = Image.new('RGBA', im.size, 'black')
size = (337, 350)
img = resize_keep_aspect_ratio(img, size, can_be_bigger=False,
crop_to_size=True, center_cropped=True,
resample=Image.BICUBIC)
img = img.rotate(13.7, Image.BICUBIC, expand=True)
x, y = (207, 490)
i.paste(img, (x, y), mask=img)
i.paste(im, mask=im)
return self.save_image(i)
await ctx.send(file=File(await self.image_func(do_it), filename='jotaro.png'))
@command(ignore_extra=True, aliases=['jotaro4'])
@cooldown(2, 5, BucketType.guild)
async def jotaro_photo2(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'jotaro_photo2.png'))
img = img.convert('RGBA')
img = resize_keep_aspect_ratio(img, (305, 440), can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True)
img = img.rotate(5, Image.BICUBIC, expand=True)
bg = Image.new('RGBA', template.size)
bg.paste(img, (460, 841), img)
bg.alpha_composite(template)
return self.save_image(bg)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='jotaro_photo.png'))
@command(aliases=['tbc'], ignore_extra=True)
@cooldown(2, 5, BucketType.guild)
async def tobecontinued(self, ctx, image=None, no_sepia=False):
"""Make a to be continued picture
Usage: {prefix}{name} `image/emote/mention` `[optional sepia filter off] on/off`
Sepia filter is on by default
"""
img = await self._get_image(ctx, image)
if not img:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
if not no_sepia:
img = sepia(img)
width, height = img.width, img.height
if width < 300:
width = 300
if height < 200:
height = 200
img = resize_keep_aspect_ratio(img, (width, height), resample=Image.BILINEAR)
width, height = img.width, img.height
tbc = Image.open(os.path.join(TEMPLATES, 'tbc.png'))
x = int(width * 0.09)
y = int(height * 0.90)
tbc = resize_keep_aspect_ratio(tbc, (width * 0.5, height * 0.3),
can_be_bigger=False, resample=Image.BILINEAR)
if y + tbc.height > height:
y = height - tbc.height - 10
img.paste(tbc, (x, y), tbc)
return self.save_image(img)
await ctx.send(file=File(await self.image_func(do_it), filename='To_be_continued.png'))
@command(aliases=['heaven', 'heavens_door'], ignore_extra=True)
@cooldown(2, 5, BucketType.guild)
async def overheaven(self, ctx, image=None):
img = await self._get_image(ctx, image)
if not img:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
overlay = Image.open(os.path.join(TEMPLATES, 'heaven.png'))
base = Image.open(os.path.join(TEMPLATES, 'heaven_base.png'))
size = (750, 750)
img = resize_keep_aspect_ratio(img, size, can_be_bigger=False,
crop_to_size=True, center_cropped=True)
img = img.convert('RGBA')
x, y = (200, 160)
base.paste(img, (x, y), mask=img)
base.alpha_composite(overlay)
return self.save_image(base)
await ctx.send(file=File(await self.image_func(do_it), filename='overheaven.png'))
@command(aliases=['puccireset'], ignore_extra=True)
@cooldown(2, 5, BucketType.guild)
async def pucci(self, ctx, image=None):
img = await self._get_image(ctx, image)
if not img:
return
await ctx.trigger_typing()
def do_it():
nonlocal img
img = img.convert('RGBA')
im = Image.open(os.path.join(TEMPLATES, 'pucci_bg.png'))
overlay = Image.open(os.path.join(TEMPLATES, 'pucci_faded.png'))
size = (682, 399)
img = resize_keep_aspect_ratio(img, size, can_be_bigger=False,
crop_to_size=True, center_cropped=True)
x, y = (0, 367)
im.paste(img, (x, y), mask=img)
im.alpha_composite(overlay)
return self.save_image(im)
await ctx.send(file=File(await self.image_func(do_it), filename='pucci_reset.png'))
@command(ignore_extra=True)
@cooldown(1, 10, BucketType.guild)
async def party(self, ctx, image=None):
"""Takes a long ass time to make the gif"""
img = await self._get_image(ctx, image)
if img is None:
return
async with ctx.typing():
img = await self.bot.loop.run_in_executor(self.threadpool, partial(gradient_flash, img, get_raw=True))
await ctx.send(content=f"Use {ctx.prefix}party2 if transparency guess went wrong",
file=File(img, filename='party.gif'))
@command(ignore_extra=True)
@cooldown(1, 10, BucketType.guild)
async def party2(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
async with ctx.typing():
img = await self.bot.loop.run_in_executor(self.threadpool, partial(gradient_flash, img, get_raw=True, transparency=False))
await ctx.send(file=File(img, filename='party.gif'))
@command(ignore_extra=True)
@cooldown(2, 2, type=BucketType.guild)
async def blurple(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
im = Image.new('RGBA', img.size, color='#7289DA')
img = img.convert('RGBA')
if img.format == 'GIF':
def multiply(frame):
return ImageChops.multiply(frame, im)
data = func_to_gif(img, multiply, get_raw=True)
name = 'blurple.gif'
else:
img = ImageChops.multiply(img, im)
data = self.save_image(img)
name = 'blurple.png'
return data, name
async with ctx.typing():
file = File(*await self.image_func(do_it))
await ctx.send(file=file)
@command(ignore_extra=True, aliases=['gspd', 'gif_spd'])
@cooldown(2, 5)
async def gif_speed(self, ctx, image, speed=None):
"""
Speed up or slow a gif down by multiplying the frame delay
the specified speed (higher is faster, lower is slower, 1 is default speed)
Due to the fact that different engines render gifs differently higher speed
might not actually mean faster gif. After a certain threshold
the engine will start throttling and set the frame delay to a preset default
If this happens try making the speed value smaller
"""
if speed is None:
img = await self._get_image(ctx, None)
speed = image
else:
img = await self._get_image(ctx, image)
if img is None:
return
if not isinstance(img, GifImagePlugin.GifImageFile):
raise BadArgument('Image must be a gif')
try:
speed = float(speed)
except (ValueError, TypeError) as e:
raise BadArgument(str(e))
if speed == 1:
return await ctx.send("Setting speed to 1 won't change the speed ya know")
if not 0 < speed <= 10:
raise BadArgument('Speed must be larger than 0 and less or equal to 10')
def do_speedup():
frames = convert_frames(img, 'RGBA')
durations = get_duration(frames)
def transform(duration):
# Frame delay is stored as an unsigned 2 byte int
# A delay of 0 would mean that the frame would change as fast
# as the pc can do it which is useless. Also rendering engines
# like to round delays higher up to 10 and most don't display the
# smallest delays
duration = min(max(duration//speed, 5), 65535)
return duration
durations = list(map(transform, durations))
frames[0].info['duration'] = durations
for f, d in zip(frames, durations):
f.info['duration'] = d
frames = apply_transparency(frames)
file = BytesIO()
frames[0].save(file, format='GIF', duration=durations, save_all=True,
append_images=frames[1:], loop=65535, optimize=False, disposal=2)
file.seek(0)
data = file.getvalue()
if len(data) > 8000000:
return optimize_gif(file.getvalue())
return data
async with ctx.typing():
file = await self.image_func(do_speedup)
await ctx.send(file=File(file, filename='speedup.gif'))
@command(ignore_extra=True)
@cooldown(2, 5, BucketType.guild)
async def smug(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
img = img.convert('RGBA')
template = Image.open(os.path.join(TEMPLATES, 'smug_man.png'))
w, h = 729, 607
img = resize_keep_aspect_ratio(img, (w, h), can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True)
template.paste(img, (168, 827), img)
return self.save_image(template)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='smug_man.png'))
@command(ignore_extra=True)
@cooldown(2, 5, BucketType.guild)
async def seeyouagain(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'seeyouagain.png'))
img = img.convert('RGBA')
img = resize_keep_aspect_ratio(img, (360, 300), can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True)
template.paste(img, (800, 915), img)
return self.save_image(template)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='see_you_again.png'))
@command(ignore_extra=True, aliases=['sha'])
@cooldown(2, 5, BucketType.guild)
async def sheer_heart_attack(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'sheer_heart_attack.png'))
img = img.convert('RGBA')
img = resize_keep_aspect_ratio(img, (1000, 567), can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True, background_color='white')
template.paste(img, (0, 563), img)
return self.save_image(template)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='sha.png'))
@command(ignore_extra=True)
@cooldown(2, 5, BucketType.guild)
async def kira(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'kira.png'))
img = img.convert('RGBA')
img = resize_keep_aspect_ratio(img, (810, 980), can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True)
bg = Image.new('RGBA', (1918, 2132), (0, 0, 0, 0))
bg.paste(img, (610, 1125), img)
bg.alpha_composite(template)
return self.save_image(bg)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='kira.png'))
@command(ignore_extra=True)
@cooldown(2, 5, BucketType.guild)
async def josuke(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'josuke.png'))
img = img.convert('RGBA')
img = resize_keep_aspect_ratio(img, (198, 250), can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True)
bg = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0))
bg.paste(img, (1000, 155), img)
bg.alpha_composite(template)
return self.save_image(bg)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='josuke.png'))
@command(ignore_extra=True, aliases=['josuke2'])
@cooldown(2, 5, BucketType.guild)
async def josuke_binoculars(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'josuke_binoculars.png'))
img = img.convert('RGBA')
size = (700, 415)
img = resize_keep_aspect_ratio(img, size, can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True)
bg = Image.new('RGBA', template.size, (255, 255, 255))
bg.paste(img, (50, 460), img)
bg.alpha_composite(template)
return self.save_image(bg)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='josuke_binoculars.png'))
@command(ignore_extra=True, aliases=['02'])
@cooldown(2, 5, BucketType.guild)
async def zerotwo(self, ctx, image=None):
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'zerotwo.png')).convert('RGBA')
img = img.convert('RGBA')
img = resize_keep_aspect_ratio(img, (840, 615), can_be_bigger=False,
resample=Image.BICUBIC, crop_to_size=True,
center_cropped=True)
img = img.rotate(4, Image.BICUBIC, expand=True)
template.alpha_composite(img, (192, 29))
return self.save_image(template)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='02.png'))
@command(ignore_extra=True, aliases=['greatview'])
@cooldown(2, 5, BucketType.guild)
async def giorno(self, ctx, stretch: Optional[bool]=True, image=None):
"""
If stretch is set off the image will not be stretched to size
"""
img = await self._get_image(ctx, image)
if img is None:
return
def do_it():
nonlocal img
template = Image.open(os.path.join(TEMPLATES, 'whatagreatview.png'))
img = img.convert('RGBA')
size = (868, 607)
if stretch:
img = img.resize(size, resample=Image.BICUBIC)
else:
img = resize_keep_aspect_ratio(img, size, can_be_bigger=False,
resample=Image.BICUBIC,
crop_to_size=True,
center_cropped=True)
bg = Image.new('RGBA', template.size, 'white')
bg.paste(img, (212, 608), img)
bg.alpha_composite(template)
return self.save_image(bg)
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='02.png'))
@command()
@cooldown(2, 5, BucketType.guild)
async def narancia(self, ctx, *, text: CleanContent(escape_markdown=True, fix_channel_mentions=True,
remove_everyone=False, fix_emotes=True)):
text = text.strip('\u200b \n\r\t')
def do_it():
nonlocal text
# Linearly decreasing fontsize
fontsize = int(round(45.0 - 0.08 * len(text)))
fontsize = min(max(fontsize, 15), 45)
font = ImageFont.truetype(os.path.join('M-1c', 'mplus-1c-bold.ttf'), fontsize)
im = Image.open(os.path.join(TEMPLATES, 'narancia.png'))
shadow = Image.open(os.path.join(TEMPLATES, 'narancia_shadow.png'))
draw = ImageDraw.Draw(im)
size = (250, 350) # Size of the page
spot = (400, 770) # Pasting spot for first page
text = text.replace('\n', ' ')
# We need to replace the height of the text with the height of A
# Since that what draw.text uses in it's text drawing methods but not
# in the text size methods. Nice design I know. It makes textsize inaccurate
# so don't use that method
text_size = font.getsize(text)
text_size = (text_size[0], font.getsize('A')[1])
# Linearly growing spacing
spacing = int(round(0.5 + 0.167 * fontsize))
spacing = min(max(spacing, 3), 6)
# We add 2 extra to compensate for measuring inaccuracies
line_height = text_size[1]
spot_changed = False
all_lines = []
# Split lines based on average width
# If max characters per line is less than the given max word
# use max line width as max word width
max_line = int(len(text) // (text_size[0] / size[0]))
lines = split_string(text, maxlen=max_line, max_word=min(max_line, 30))
total_y = 0
for line in lines:
line = line.strip()
if not line:
continue
total_y += line_height
if total_y > size[1]:
draw.multiline_text(spot, '\n'.join(all_lines), font=font,
fill='black', spacing=spacing)
all_lines = []
if spot_changed:
# We are already on second page. Let's stop here
break
spot_changed = True
# Pasting spot and size for second page
spot = (678, 758)
size = (250, 350)
total_y = line_height
total_y += spacing
all_lines.append(line)
draw.multiline_text(spot, '\n'.join(all_lines), font=font,
fill='black', spacing=spacing)
im.alpha_composite(shadow)
return self.save_image(im, 'PNG')
async with ctx.typing():
file = await self.image_func(do_it)
await ctx.send(file=File(file, filename='narancia.png'))
@command(ignore_extra=True, aliases=['poke'])
@cooldown(2, 2, type=BucketType.guild)
async def pokefusion(self, ctx, poke1=Pokefusion.RANDOM, poke2=Pokefusion.RANDOM, color_poke=None):
"""
Gets a random pokemon fusion from http://pokefusion.japeal.com
You can specify the wanted fusion by specifying their pokedex index or their name or just a part of their name.
Color poke defines the pokemon whose color palette will be used. By default it's not used
Passing % as a parameter will randomize that value
"""
if not self._pokefusion:
return await ctx.send('Pokefusion not supported')
await ctx.trigger_typing()
try:
img, s = await self._pokefusion.fuse(poke1, poke2, color_poke)
except NoPokeFoundException as e:
return await ctx.send(str(e))
file = BytesIO()
img.save(file, 'PNG')
file.seek(0)
await ctx.send(s, file=File(file, filename='pokefusion.png'))
@command(ignore_extra=True, aliases=['get_im'])
@cooldown(3, 3, BucketType.guild)
async def get_image(self, ctx, *, data=None):
"""Get's the latest image in the channel if data is None
otherwise gets the image based on data. If data is an id, first avatar lookup is done
then message lookup. If data is an image url this will just return that url"""
img = await get_image_from_message(ctx, data)
s = img if img else 'No image found'
return await ctx.send(s)
@command(owner_only=True)
async def update_poke_cache(self, ctx):
if await self._pokefusion.update_cache() is False:
await ctx.send('Failed to update cache')
else:
await ctx.send('Successfully updated cache')
def setup(bot):
bot.add_cog(Images(bot))
<file_sep>import inspect
import itertools
import logging
import colors
import discord
from discord import Embed
from discord.ext.commands import Command
from discord.ext.commands.errors import CommandError
from discord.ext.commands.formatter import HelpFormatter
from sqlalchemy.exc import SQLAlchemyError
from utils.utilities import check_perms
logger = logging.getLogger('debug')
class Formatter(HelpFormatter):
Generic = 0
Cog = 1
Command = 2
Filtered = 3 # Show only the commands that the caller can use based on required discord permissions
ExtendedFilter = 4 # Include database black/whitelist to filter
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def format_help_for(self, context, command_or_bot, is_owner=False, type=Generic):
self.context = context
self.command = command_or_bot
self.type = type
retval = await self.format(is_owner=is_owner)
context.skip_check = False # Just in case
return retval
async def format(self, is_owner=False):
"""Handles the actual behaviour involved with formatting.
To change the behaviour, this method should be overridden.
Returns
--------
list
A paginated output of the help command.
"""
description = self.command.description if not self.is_cog() else inspect.getdoc(self.command)
self._paginator = Paginator(title='Help')
ctx = self.context
user = ctx.message.author
channel = ctx.message.channel
if isinstance(user, discord.Member) and user.roles:
roles = '(role IS NULL OR role IN ({}))'.format(', '.join(map(lambda r: str(r.id), user.roles)))
else:
roles = 'role IS NULL'
if isinstance(self.command, Command):
# <signature portion>
signature = self.get_command_signature()
if getattr(self.command, 'owner_only', False):
signature = 'This command is owner only\n' + signature
elif self.type == self.Filtered or self.type == self.ExtendedFilter:
try:
can_run = await self.command.can_run(ctx) and await ctx.bot.can_run(ctx)
except CommandError as e:
signature = str(e) + '\n\n' + signature
# Workaround to get past the next if
can_run = True
if not can_run:
signature = "This command is blacklisted for you\n\n" + signature
signature = description + '\n' + signature
# <long doc> section
if self.command.help:
self._paginator.edit_page(self.command.name, self.command.help.format(prefix=self.context.prefix, name=self.command.name))
self._paginator.add_field('Usage', signature)
# end it here if it's just a regular command
if not self.has_subcommands():
self._paginator.finalize()
return self._paginator.pages
def category(tup):
cog = tup[1].cog_name
return cog if cog is not None else 'No Category'
if self.is_bot():
guild_owner = False if not ctx.guild else user.id == ctx.guild.owner.id
command_blacklist = {}
if self.type == self.ExtendedFilter and not guild_owner:
sql = 'SELECT `type`, `role`, `user`, `channel`, `command` FROM `command_blacklist` WHERE guild=:guild ' \
'AND (user IS NULL OR user=:user) AND {} AND (channel IS NULL OR channel=:channel)'.format(roles)
try:
rows = await ctx.bot.dbutil.execute(sql, {'guild': user.guild.id,
'user': user.id,
'channel': channel.id})
for row in rows:
name = row['command']
if name in command_blacklist:
command_blacklist[name].append(row)
else:
command_blacklist[name] = [row]
except SQLAlchemyError:
logger.exception('Failed to get role blacklist for help command')
# We dont wanna check perms again for each individual command
ctx.skip_check = True
data = sorted(await self.filter_command_list(), key=category)
# We also dont wanna leave it on
ctx.skip_check = False
if self.type == self.ExtendedFilter and command_blacklist:
def check(command):
rows = command_blacklist.get(command.name, None)
if not rows:
return True
return check_perms(rows)
else:
check = None
for category_, commands in itertools.groupby(data, key=category):
# there simply is no prettier way of doing this.
commands = list(commands)
def inline(entries):
if len(entries) > 5:
return False
else:
return True
self._add_subcommands_and_page(category_, commands, is_owner=is_owner, inline=inline, predicate=check)
else:
# TODO same kind of check as in general help command
self._add_subcommands_and_page('Commands:', await self.filter_command_list(), is_owner=is_owner)
# add the ending note
ending_note = self.get_ending_note()
self._paginator.add_field('Note', ending_note)
self._paginator.finalize()
return self._paginator.pages
def get_ending_note(self):
command_name = self.context.invoked_with
return "Type `{0}{1} command` for more info on a command.\n" \
"You can also type `{0}{1} Category` for more info on a category.\n" \
"This list is filtered based on your and the bots permissions. To get a list of all commands use `{0}{1} all`".format(self.clean_prefix, command_name)
def _add_subcommands_and_page(self, page, commands, is_owner=False, inline=None, predicate=None):
# Like _add_subcommands_to_page but doesn't leave empty fields in the embed
# Can be extended to include other filters too
entries = []
for name, command in commands:
if name in command.aliases:
# skip aliases
continue
if command.owner_only and not is_owner:
continue
if self.type == self.ExtendedFilter and predicate and not predicate(command):
continue
entry = '`{0}` '.format(name)
entries.append(entry)
if not entries:
return
if callable(inline):
inline = inline(entries)
self._paginator.add_field(page, inline=inline)
for entry in entries:
self._paginator.add_to_field(entry)
def _add_subcommands_to_page(self, commands, is_owner=False):
for name, command in commands:
if name in command.aliases:
# skip aliases
continue
if command.owner_only and not is_owner:
continue
entry = '`{0}` '.format(name)
self._paginator.add_to_field(entry)
class Limits:
Field = 1024
Name = 256
Title = 256
Description = 2048
Fields = 25
Total = 6000
class Paginator:
def __init__(self, title=None, description=None, page_count=True):
self._fields = 0
self._pages = []
self.title = title
self.description = description
self.set_page_count = page_count
self._current_page = -1
self._char_count = 0
self._current_field = None
self.add_page(title, description)
@property
def pages(self):
return self._pages
def finalize(self):
self._add_field()
if not self.set_page_count:
return
total = len(self.pages)
for idx, embed in enumerate(self.pages):
embed.set_footer(text=f'{idx+1}/{total}')
def add_page(self, title=None, description=None):
title = title or self.title
description = description or self.description
self._pages.append(Embed(title=title, description=description))
self._current_page += 1
self._fields = 0
self._char_count = 0
self._char_count += len(title) if title else 0
self._char_count += len(description) if description else 0
self.title = title
self.description = description
def edit_page(self, title=None, description=None):
page = self.pages[self._current_page]
if title:
self._char_count -= len(str(title))
page.title = str(title)
self.title = title
self._char_count += len(title)
if description:
self._char_count -= len(str(description))
page.description = str(description)
self.description = description
self._char_count += len(description)
def _add_field(self):
if not self._current_field:
return
if not self._current_field['value']:
self._current_field['value'] = 'Emptiness'
self.pages[self._current_page].add_field(**self._current_field)
self._fields += 1
self._char_count += len(self._current_field['name']) + len(self._current_field['value'])
self._current_field = None
def add_field(self, name, value='', inline=False):
if self._current_field is not None and self._fields < 25:
self._add_field()
name = name[:Limits.Title]
value = value[:Limits.Field]
length = len(name) + len(value)
if self._fields == 25:
self._pages.append(Embed(title=self.title))
self._current_page += 1
self._fields = 0
self._char_count = len(self.title)
if self._current_field is not None:
self._add_field()
elif length + self._char_count > Limits.Total:
self._pages.append(Embed(title=self.title))
self._current_page += 1
self._fields = 0
self._char_count = len(self.title)
self._current_field = {'name': name, 'value': value, 'inline': inline}
def add_to_field(self, value):
v = self._current_field['value']
if len(v) + len(value) > Limits.Field:
self.add_field(self._current_field['name'], value)
else:
self._current_field['value'] += value
def get_color(fg=None, bg=None, style=None):
"""
Get the ANSI color based on params
:param str|int|tuple fg: Foreground color specification.
:param str|int|tuple bg: Background color specification.
:param str style: Style names, separated by '+'
:returns: ANSI color code
:rtype: str
"""
codes = []
if fg:
codes.append(colors.colors._color_code(fg, 30))
if bg:
codes.append(colors.colors._color_code(bg, 40))
if style:
for style_part in style.split('+'):
if style_part in colors.STYLES:
codes.append(colors.STYLES.index(style_part))
else:
raise ValueError('Invalid style "%s"' % style_part)
if codes:
template = '\x1b[{0}m'
return template.format(colors.colors._join(*codes))
else:
return ''
class LoggingFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None, style='%', override_colors: dict=None):
super().__init__(fmt, datefmt, style)
self.colors = {logging.NOTSET: {'fg': 'default'},
logging.DEBUG: {'fg': 'CYAN'},
logging.INFO: {'fg': 'GREEN'},
logging.WARNING: {'fg': 'YELLOW'},
logging.ERROR: {'fg': 'red'},
logging.CRITICAL: {'fg': 'RED', 'style': 'negative'},
'EXCEPTION': {'fg': 'RED'}} # Style for exception traceback
if override_colors:
self.colors.update(override_colors)
def format(self, record):
"""
Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
are carried out. The message attribute of the record is computed
using LogRecord.getMessage(). If the formatting string uses the
time (as determined by a call to usesTime(), formatTime() is
called to format the event time. If there is exception information,
it is formatted using formatException() and appended to the message.
"""
record.message = record.getMessage()
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
color = get_color(**self.colors.get(record.levelno, {}))
if color:
record.color = color
record.colorend = '\x1b[0m'
s = self.formatMessage(record)
if record.exc_info:
# Cache the traceback text to avoid converting it multiple times
# (it's constant anyway)
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
if s[-1:] != "\n":
s = s + "\n"
color = get_color(**self.colors.get('EXCEPTION', {}))
if color:
s = s + color + record.exc_text + '\x1b[0m'
else:
s = s + record.exc_text
if record.stack_info:
if s[-1:] != "\n":
s = s + "\n"
s = s + self.formatStack(record.stack_info)
return s
<file_sep>import asyncio
import logging
import random
import textwrap
import unicodedata
from datetime import datetime
from datetime import timedelta
from typing import Union
import discord
import emoji
from discord.errors import HTTPException
from discord.ext.commands import (BucketType, check, bot_has_permissions)
from numpy import sqrt
from numpy.random import choice
from sqlalchemy.exc import SQLAlchemyError
from bot.bot import command, has_permissions, cooldown
from bot.formatter import Paginator
from cogs.cog import Cog
from utils.utilities import (split_string, parse_time, datetime2sql, call_later,
get_avatar, retry, send_paged_message,
check_botperm)
logger = logging.getLogger('debug')
def create_check(guild_ids):
def guild_check(ctx):
return ctx.guild.id in guild_ids
return guild_check
whitelist = [217677285442977792, 353927534439825429]
main_check = create_check(whitelist)
grant_whitelist = {486834412651151361, 279016719916204032}
grant_whitelist.update(whitelist)
grant_check = create_check(grant_whitelist)
# waifus to add
"""
ram
emilia
chiaki nanami
nagito komaeda
ochako uraraka
tsuyu asui
kyouka jirou
momo yaoyorozu
<NAME>
himiko toga
akeno himejima
xenovia quarta
ushikai musume
Koneko toujou
asuna yuuki
kanna kamui
ann takamaki
yousei yunde
yorha 2-gou b-gata"""
waifus = [('<NAME>', 1, ['https://i.imgur.com/V9X7Rbm.png', 'https://i.imgur.com/ny8IwLI.png', 'https://i.imgur.com/RxxYp62.png']),
("Aqua", 10, ['https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=7B4dkxZXrniNxKaJFq0XFVO86alUbsoiQNXbaxFmhwqyCd2KfYqkUpW5YHaZhuAh&tea=FvLvedTFWlgNSavX', 'https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=stWZ5xmBZkDH8bHyhVpG9Y4iae8Cqf3ajoY0lD7r3Sdysa4IilA6aZSUHznVbQWG&tea=TPiTxOZcgmMieAnO']),
('Zero Two', 10, ['https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=5YJ%2FlstHJTPWWcZ0RfBsOuoHlK48mDUK5Dd596ED%2BonGAIJcACI9xwoVreZSM0WI&tea=iBvsVVWHNcdsvaOK', 'https://cdn.discordapp.com/attachments/477293401054642177/477319994259275796/055fb45a-e8d7-4084-b61d-eea31b0fd235.jpg']),
('Shalltear Bloodfallen', 10, ['https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=QZXjFYY%2BKrSOKMP7FXg1vTkHZLtBgIczQJEJWP3THtgsEIz7VhhE2menxbFv1VS9&tea=qckYylIRjoKUbjzG', 'https://cdn.discordapp.com/attachments/477293401054642177/477317853389783042/2b513572-a239-4bb7-a58a-bb48a23e4379.jpg']),
('Esdeath', 10, ['https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=oxQ4Hy%2Bhh4EuSfBwMzxGP%2BJgVhga0OQ3d%2BFdV4mxMcTABwPfyjO7Ai86D5mijMxq&tea=zCbXylfXYsArnJuq', 'https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=P%2BS2ZekqqFZ8xzXqKgipdQLzckmAwRK%2FUkvsnMCxcHFDyyRet4lgcGRqvbF1Y4Vq&tea=ulrKjZyNCLDhktvW']),
('Megumin', 10, ['https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=3TvoZWcwlI3WlJXUyNLeloFBNV6oF2qq8NYfukqNk0ht0zqKhP7%2FrEGz0frs6Wq5&tea=wfDsVgPNOOTkwMhz', ]),
('Albedo', 10, ['https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=6mFvoz3jJ%2BwhW9lOWR49KTbLIiKjuYFhittUwcQhMc%2B0JstX%2FkkXyXVPZxWiiEkr&tea=VyKIujqwVbHiWTUz']),
('Rem', 10, ['https://remilia.cirno.pw/teahouse/teapot.jpg?biscuit=bUUxHLQv6IzKqWZnxrO8nUw723nFGHALSm9ZM8Ly3VU1%2B0DyE8qL1yRaNtnQe7wj&tea=AFfSbWSfwXFONvvV']),
]
chances = [t[1] for t in waifus]
_s = sum(chances)
chances = [p/_s for p in chances]
del _s
class ServerSpecific(Cog):
def __init__(self, bot):
super().__init__(bot)
asyncio.run_coroutine_threadsafe(self.load_giveaways(), loop=self.bot.loop)
self.main_whitelist = whitelist
self.grant_whitelist = grant_whitelist
self.redis = self.bot.redis
def __unload(self):
for g in list(self.bot.every_giveaways.values()):
g.cancel()
async def load_giveaways(self):
sql = 'SELECT * FROM `giveaways`'
try:
rows = (await self.bot.dbutil.execute(sql)).fetchall()
except SQLAlchemyError:
logger.exception('Failed to load giveaways')
return
for row in rows:
guild = row['guild']
channel = row['channel']
message = row['message']
title = row['title']
winners = row['winners']
timeout = max((row['expires_in'] - datetime.utcnow()).total_seconds(), 0)
if message in self.bot.every_giveaways:
self.bot.every_giveaways[message].cancel()
fut = call_later(self.remove_every, self.bot.loop, timeout, guild, channel, message, title, winners,
after=lambda f: self.bot.every_giveaways.pop(message))
self.bot.every_giveaways[message] = fut
@property
def dbutil(self):
return self.bot.dbutil
async def _check_role_grant(self, ctx, user, role_id, guild_id):
where = 'user=%s OR user_role IN (%s)' % (user.id, ', '.join((str(r.id) for r in user.roles)))
sql = 'SELECT `role` FROM `role_granting` WHERE guild=%s AND role=%s AND (%s) LIMIT 1' % (guild_id, role_id, where)
try:
row = (await self.bot.dbutil.execute(sql)).first()
if not row:
return False
except SQLAlchemyError:
await ctx.send('Something went wrong. Try again in a bit')
return None
return True
@command(no_pm=True)
@cooldown(1, 4, type=BucketType.user)
@check(grant_check)
@bot_has_permissions(manage_roles=True)
async def grant(self, ctx, user: discord.Member, *, role: discord.Role):
"""Give a role to the specified user if you have the perms to do it"""
guild = ctx.guild
author = ctx.author
no = (117256618617339905, 189458911886049281)
if author.id in no and user.id in no and user.id != author.id:
return await ctx.send('no')
can_grant = await self._check_role_grant(ctx, author, role.id, guild.id)
if can_grant is None:
return
elif can_grant is False:
return await ctx.send("You don't have the permission to grant this role", delete_after=30)
try:
await user.add_roles(role, reason=f'{ctx.author} granted role')
except HTTPException as e:
return await ctx.send('Failed to add role\n%s' % e)
await ctx.send('👌')
@command(no_pm=True)
@cooldown(2, 4, type=BucketType.user)
@check(grant_check)
@bot_has_permissions(manage_roles=True)
async def ungrant(self, ctx, user: discord.Member, *, role: discord.Role):
"""Remove a role from a user if you have the perms"""
guild = ctx.guild
author = ctx.message.author
length = len(author.roles)
if length == 0:
return
no = (117256618617339905, 189458911886049281)
if author.id in no and user.id in no and user.id != author.id:
return await ctx.send('no')
can_grant = await self._check_role_grant(ctx, author, role.id, guild.id)
if can_grant is None:
return
elif can_grant is False:
return await ctx.send("You don't have the permission to remove this role", delete_after=30)
try:
await user.remove_roles(role, reason=f'{ctx.author} ungranted role')
except HTTPException as e:
return await ctx.send('Failed to remove role\n%s' % e)
await ctx.send('👌')
@command(no_pm=True, ignore_extra=True)
@cooldown(2, 4, type=BucketType.guild)
@check(grant_check)
@has_permissions(administrator=True)
@bot_has_permissions(manage_roles=True)
async def add_grant(self, ctx, role_user: Union[discord.Role, discord.Member], *, target_role: discord.Role):
"""Make the given role able to grant the target role"""
guild = ctx.guild
if isinstance(role_user, discord.Role):
values = (role_user.id, target_role.id, guild.id, 0)
roles = (role_user.id, target_role.id)
else:
values = (0, target_role.id, guild.id, role_user.id)
roles = (target_role.id, 0)
if not await self.dbutil.add_roles(guild.id, *roles):
return await ctx.send('Could not add roles to database')
sql = 'INSERT IGNORE INTO `role_granting` (`user_role`, `role`, `guild`, `user`) VALUES ' \
'(%s, %s, %s, %s)' % values
try:
await self.dbutil.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add grant role')
return await ctx.send('Failed to add perms. Exception logged')
await ctx.send(f'{role_user} 👌 {target_role}')
@command(no_pm=True, ignore_extra=True)
@cooldown(1, 4, type=BucketType.user)
@check(grant_check)
@has_permissions(administrator=True)
@bot_has_permissions(manage_roles=True)
async def remove_grant(self, ctx, role_user: Union[discord.Role, discord.Member], *, target_role: discord.Role):
"""Remove a grantable role from the target role"""
guild = ctx.guild
if isinstance(role_user, discord.Role):
where = 'user_role=%s' % role_user.id
else:
where = 'user=%s' % role_user.id
sql = 'DELETE FROM `role_granting` WHERE role=%s AND guild=%s AND %s' % (target_role.id, guild.id, where)
try:
await self.dbutil.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to remove role grant')
return await ctx.send('Failed to remove perms. Exception logged')
await ctx.send(f'{role_user} 👌 {target_role}')
@command(no_pm=True)
@cooldown(2, 5)
async def all_grants(self, ctx, role_user: Union[discord.Role, discord.User]=None):
"""Shows all grants on the server.
If user or role provided will get all grants specific to that."""
sql = f'SELECT `role`, `user_role`, `user` FROM `role_granting` WHERE guild={ctx.guild.id}'
if isinstance(role_user, discord.Role):
sql += f' AND user_role={role_user.id}'
elif isinstance(role_user, discord.User):
sql += f' AND user={role_user.id}'
try:
rows = await self.bot.dbutil.execute(sql)
except SQLAlchemyError:
logger.exception(f'Failed to get grants for {role_user}')
return await ctx.send('Failed to get grants')
role_grants = {}
user_grants = {}
# Add user grants and role grants to their respective dicts
for row in rows:
role_id = row['user_role']
target_role = row['role']
# Add user grants
if not role_id:
user = row['user']
if user in user_grants:
user_grants[user].append(target_role)
else:
user_grants[user] = [target_role]
# Add role grants
else:
if role_id not in role_grants:
role_grants[role_id] = [target_role]
else:
role_grants[role_id].append(target_role)
if not role_grants and not user_grants:
return await ctx.send('No role grants found')
# Paginate role grants first then user grants
paginator = Paginator('Role grants')
for role_id, roles in role_grants.items():
role = ctx.guild.get_role(role_id)
role_name = role.name if role else '*Deleted role*'
paginator.add_field(f'{role_name} `{role_id}`')
for role in roles:
paginator.add_to_field(f'<@&{role}> `{role}`\n')
for user_id, roles in user_grants.items():
user = self.bot.get_user(user_id)
if not user:
user = f'<@{user}>'
paginator.add_field(f'{user} `{user_id}`')
for role in roles:
paginator.add_to_field(f'<@&{role}> `{role}`\n')
paginator.finalize()
await send_paged_message(ctx, paginator.pages, embed=True)
@command(no_pm=True, aliases=['get_grants', 'grants'])
@cooldown(1, 4)
@check(grant_check)
async def show_grants(self, ctx, user: discord.Member=None):
"""Shows the roles you or the specified user can grant"""
guild = ctx.guild
if not user:
user = ctx.author
sql = 'SELECT `role` FROM `role_granting` WHERE guild=%s AND (user=%s OR user_role IN (%s))' % (guild.id, user.id, ', '.join((str(r.id) for r in user.roles)))
try:
rows = (await self.dbutil.execute(sql)).fetchall()
except SQLAlchemyError:
logger.exception('Failed to get role grants')
return await ctx.send('Failed execute sql')
if not rows:
return await ctx.send("{} can't grant any roles".format(user))
msg = 'Roles {} can grant:\n'.format(user)
roles = set()
for row in rows:
role = guild.get_role(row['role'])
if not role:
continue
if role.id in roles:
continue
roles.add(role.id)
msg += '{0.name} `{0.id}`\n'.format(role)
if not roles:
return await ctx.send("{} can't grant any roles".format(user))
for s in split_string(msg, maxlen=2000, splitter='\n'):
await ctx.send(s)
@command(disabled=True)
@cooldown(1, 3, type=BucketType.guild)
@check(main_check)
async def text(self, ctx, prime='', n: int=100, sample: int=1):
"""Generate text"""
if not 10 <= n <= 200:
return await ctx.send('n has to be between 10 and 200')
if not 0 <= sample <= 2:
return await ctx.send('sample hs to be 0, 1 or 2')
if not self.bot.tf_model:
return await ctx.send('Not supported')
async with ctx.typing():
s = await self.bot.loop.run_in_executor(self.bot.threadpool, self.bot.tf_model.sample, prime, n, sample)
await ctx.send(s)
@command(owner_only=True, aliases=['flip'])
@check(main_check)
async def flip_the_switch(self, ctx, value: bool=None):
if value is None:
self.bot.anti_abuse_switch = not self.bot.anti_abuse_switch
else:
self.bot.anti_abuse_switch = value
await ctx.send(f'Switch set to {self.bot.anti_abuse_switch}')
@command(no_pm=True)
@cooldown(1, 3, type=BucketType.user)
@check(create_check((217677285442977792, )))
async def default_role(self, ctx):
"""Temporary fix to easily get default role"""
if self.bot.test_mode:
return
guild = ctx.guild
role = guild.get_role(352099343953559563)
if not role:
return await ctx.send('Default role not found')
member = ctx.author
if role in member.roles:
return await ctx.send('You already have the default role. Reload discord (ctrl + r) to get your global emotes')
try:
await member.add_roles(role)
except HTTPException as e:
return await ctx.send('Failed to add default role because of an error.\n{}'.format(e))
await ctx.send('You now have the default role. Reload discord (ctrl + r) to get your global emotes')
# https://stackoverflow.com/questions/48340622/extract-all-emojis-from-string-and-ignore-fitzpatrick-modifiers-skin-tones-etc
@staticmethod
def check_type(emoji_str):
if unicodedata.name(emoji_str).startswith("EMOJI MODIFIER"):
return False
else:
return True
def extract_emojis(self, emojis):
return [c for c in emojis if c in emoji.UNICODE_EMOJI and self.check_type(c)]
@command(no_pm=True)
@cooldown(1, 600)
@bot_has_permissions(manage_guild=True)
@check(main_check)
async def rotate(self, ctx, emoji=None):
emoji_faces = {'😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉',
'😊', '😋', '😎', '😍', '😘', '😗', '😙', '😚', '☺',
'🙂', '🤗', '\U0001f929', '🤔', '\U0001f928', '😐', '😑',
'😶', '🙄', '😏', '😣', '😥', '😮', '🤐', '😯', '😪',
'😫', '😴', '😌', '😛', '😜', '😝', '🤤', '😒', '😓',
'😔', '😕', '🙃', '🤑', '😲', '☹', '🙁', '😖', '😞',
'😟', '😤', '😢', '😭', '😦', '😧', '😨', '😩',
'\U0001f92f', '😬', '😰', '😱', '😳', '👱', '\U0001f92a',
'😡', '😠', '\U0001f92c', '😷', '🤒', '🤕', '🤢', '😵',
'\U0001f92e', '🤧', '😇', '🤠', '🤡', '🤥', '\U0001f92b',
'\U0001f92d', '\U0001f9d0', '🤓', '😈', '👿', '👶', '🐶',
'🐱', '🐻', '🐸', '🐵', '🐧', '🐔', '🐣', '🐥', '🐝',
'🐍', '🐢', '🐹', '💩', '👦', '👧', '👨', '👩', '🎅',
'🍆', '🥚', '👌', '👏', '🌚', '🌝', '🌞', '⭐', '🦆', '👖',
'🍑', '🌈', '♿', '💯', '🐛', '💣', '🔞', '🆗', '🚼'}
if emoji is not None:
invalid = True
emoji_check = emoji
if len(emoji) > 1:
try:
emojis = self.extract_emojis(emoji)
except ValueError:
return await ctx.send('Invalid emoji')
if len(emojis) == 1:
emoji_check = emojis[0]
if emoji_check in emoji_faces:
invalid = False
if invalid:
ctx.command.reset_cooldown(ctx)
return await ctx.send('Invalid emoji')
elif emoji is None:
emoji = random.choice(list(emoji_faces))
try:
await ctx.guild.edit(name=emoji*(100//(len(emoji))))
except discord.HTTPException as e:
await ctx.send(f'Failed to change name because of an error\n{e}')
else:
await ctx.send('♻')
async def _toggle_every(self, channel, winners: int, expires_in):
guild = channel.guild
perms = channel.permissions_for(guild.get_member(self.bot.user.id))
if not perms.manage_roles and not perms.administrator:
return await channel.send('Invalid server perms')
role = guild.get_role(323098643030736919 if not self.bot.test_mode else 440964128178307082)
if role is None:
return await channel.send('Every role not found')
sql = 'INSERT INTO `giveaways` (`guild`, `title`, `message`, `channel`, `winners`, `expires_in`) VALUES (:guild, :title, :message, :channel, :winners, :expires_in)'
now = datetime.utcnow()
expired_date = now + expires_in
sql_date = datetime2sql(expired_date)
title = 'Toggle the every role on the winner.'
embed = discord.Embed(title='Giveaway: {}'.format(title),
description='React with <:GWjojoGachiGASM:363025405562585088> to enter',
timestamp=expired_date)
text = 'Expires at'
if winners > 1:
text = '{} winners | '.format(winners) + text
embed.set_footer(text=text, icon_url=get_avatar(self.bot.user))
message = await channel.send(embed=embed)
try:
await message.add_reaction('GWjojoGachiGASM:363025405562585088')
except:
pass
try:
await self.bot.dbutil.execute(sql, params={'guild': guild.id,
'title': 'Toggle every',
'message': message.id,
'channel': channel.id,
'winners': winners,
'expires_in': sql_date},
commit=True)
except SQLAlchemyError:
logger.exception('Failed to create every toggle')
return await channel.send('SQL error')
task = call_later(self.remove_every, self.bot.loop, expires_in.total_seconds(),
guild.id, channel.id, message.id, title, winners)
self.bot.every_giveaways[message.id] = task
@command(no_pm=True)
@cooldown(1, 3, type=BucketType.guild)
@check(main_check)
@has_permissions(manage_roles=True, manage_guild=True)
@bot_has_permissions(manage_roles=True)
async def toggle_every(self, ctx, winners: int, *, expires_in):
"""Host a giveaway to toggle the every role"""
expires_in = parse_time(expires_in)
if not expires_in:
return await ctx.send('Invalid time string')
if expires_in.days > 29:
return await ctx.send('Maximum time is 29 days 23 hours 59 minutes and 59 seconds')
if not self.bot.test_mode and expires_in.total_seconds() < 300:
return await ctx.send('Minimum time is 5 minutes')
if winners < 1:
return await ctx.send('There must be more than 1 winner')
if winners > 100:
return await ctx.send('Maximum amount of winners is 100')
await self._toggle_every(ctx.channel, winners, expires_in)
async def delete_giveaway_from_db(self, message_id):
sql = 'DELETE FROM `giveaways` WHERE message=:message'
try:
await self.bot.dbutil.execute(sql, {'message': message_id}, commit=True)
except SQLAlchemyError:
logger.exception('Failed to delete giveaway {}'.format(message_id))
async def remove_every(self, guild, channel, message, title, winners):
guild = self.bot.get_guild(guild)
if not guild:
await self.delete_giveaway_from_db(message)
return
role = guild.get_role(323098643030736919 if not self.bot.test_mode else 440964128178307082)
if role is None:
await self.delete_giveaway_from_db(message)
return
channel = self.bot.get_channel(channel)
if not channel:
await self.delete_giveaway_from_db(message)
return
try:
message = await channel.get_message(message)
except discord.NotFound:
logger.exception('Could not find message for every toggle')
await self.delete_giveaway_from_db(message)
return
except Exception:
logger.exception('Failed to get toggle every message')
react = None
for reaction in message.reactions:
emoji = reaction.emoji
if isinstance(emoji, str):
continue
if emoji.id == 363025405562585088 and emoji.name == 'GWjojoGachiGASM':
react = reaction
break
if react is None:
logger.debug('react not found')
return
title = 'Giveaway: {}'.format(title)
description = 'No winners'
users = await react.users(limit=react.count).flatten()
candidates = [guild.get_member(user.id) for user in users if user.id != self.bot.user.id and guild.get_member(user.id)]
winners = choice(candidates, min(winners, len(candidates)), replace=False)
if len(winners) > 0:
winners = sorted(winners, key=lambda u: u.name)
description = 'Winners: {}'.format('\n'.join([user.mention for user in winners]))
added = 0
removed = 0
for winner in winners:
winner = guild.get_member(winner.id)
if not winner:
continue
if role in winner.roles:
retval = await retry(winner.remove_roles, role, reason='Won every toggle giveaway')
removed += 1
else:
retval = await retry(winner.add_roles, role, reason='Won every toggle giveaway')
added += 1
if isinstance(retval, Exception):
logger.debug('Failed to toggle every role on {0} {0.id}\n{1}'.format(winner, retval))
embed = discord.Embed(title=title, description=description[:2048], timestamp=datetime.utcnow())
embed.set_footer(text='Expired at', icon_url=get_avatar(self.bot.user))
await message.edit(embed=embed)
description += '\nAdded every to {} user(s) and removed it from {} user(s)'.format(added, removed)
for msg in split_string(description, splitter='\n', maxlen=2000):
await message.channel.send(msg)
await self.delete_giveaway_from_db(message.id)
async def on_member_join(self, member):
if self.bot.test_mode:
return
guild = member.guild
if guild.id != 366940074635558912:
return
if random.random() < 0.09:
name = str(member.discriminator)
else:
name = str(random.randint(1000, 9999))
await member.edit(nick=name, reason='Auto nick')
async def on_message(self, message):
if not self.bot.antispam:
return
guild = message.guild
if not guild or guild.id not in self.main_whitelist:
return
if message.webhook_id:
return
if message.author.bot:
return
if message.type != discord.MessageType.default:
return
moderator = self.bot.get_cog('Moderator')
if not moderator:
return
blacklist = moderator.automute_blacklist.get(guild.id, ())
if message.channel.id in blacklist or message.channel.id in (384422173462364163, 484450452243742720):
return
user = message.author
whitelist = moderator.automute_whitelist.get(guild.id, ())
invulnerable = discord.utils.find(lambda r: r.id in whitelist,
user.roles)
if invulnerable is not None:
return
mute_role = self.bot.guild_cache.mute_role(message.guild.id)
mute_role = discord.utils.find(lambda r: r.id == mute_role,
message.guild.roles)
if not mute_role:
return
if not isinstance(user, discord.Member):
user = guild.get_member(user.id)
if not user:
logger.debug(f'User found when expected member and member not found in guild {guild.name} user {user} in channel {message.channel.name}')
return
if mute_role in user.roles:
return
if not check_botperm('manage_roles', guild=message.guild, channel=message.channel):
return
key = f'{message.guild.id}:{user.id}'
value = await self.redis.get(key)
if value:
score, repeats, last_msg = value.split(':', 2)
score = float(score)
repeats = int(repeats)
else:
score, repeats, last_msg = 0, 0, None
ttl = await self.redis.ttl(key)
certainty = 0
created_td = (datetime.utcnow() - user.created_at)
joined_td = (datetime.utcnow() - user.joined_at)
if joined_td.days > 14:
joined = 0.2 # 2/sqrt(1)*2
else:
# seconds to days
# value is max up to 1 day after join
joined = max(joined_td.total_seconds()/86400, 1)
joined = 2/sqrt(joined)*2
certainty += joined * 4
if created_td.days > 14:
created = 0.2 # 2/(7**(1/4))*4
else:
# Calculated the same as join
created = max(created_td.total_seconds()/86400, 1)
created = 2/(created**(1/5))*4
certainty += created * 4
points = created+joined
old_ttl = 10
if ttl > 0:
old_ttl = min(ttl+2, 10)
if ttl > 4:
ttl = max(10-ttl, 0.5)
points += 6*1/sqrt(ttl)
if user.avatar is None:
points += 5*max(created/2, 1)
certainty += 20
msg = message.content
if msg:
msg = msg.lower()
len_multi = max(sqrt(len(msg))/18, 0.5)
if msg == last_msg:
repeats += 1
points += 5*((created+joined)/5) * len_multi
points += repeats*3*len_multi
certainty += repeats * 4
else:
msg = ''
score += points
needed_for_mute = 50
needed_for_mute += min(joined_td.days, 14)*2.14
needed_for_mute += min(created_td.days, 21)*1.42
certainty *= 100 / needed_for_mute
certainty = min(round(certainty, 1), 100)
if score > needed_for_mute and certainty > 55:
certainty = str(certainty) + '%'
channel = self.bot.get_channel(252872751319089153)
if channel:
await channel.send(f'{user.mention} got muted for spam with score of {score} at {message.created_at}')
time = timedelta(hours=2)
await moderator.add_timeout(message.channel, guild.id, user.id,
datetime.utcnow() + time,
time.total_seconds(),
reason='Automuted for spam. Certainty %s' % certainty)
d = 'Automuted user {0} `{0.id}` for {1}'.format(message.author,
time)
await message.author.add_roles(mute_role, reason='[Automute] Spam')
url = f'https://discordapp.com/channels/{guild.id}/{message.channel.id}/{message.id}'
embed = discord.Embed(title='Moderation action [AUTOMUTE]',
description=d, timestamp=datetime.utcnow())
embed.add_field(name='Reason', value='Spam')
embed.add_field(name='Certainty', value=certainty)
embed.add_field(name='link', value=url)
embed.set_thumbnail(url=user.avatar_url or user.default_avatar_url)
embed.set_footer(text=str(self.bot.user), icon_url=self.bot.user.avatar_url or self.bot.user.default_avatar_url)
await moderator.send_to_modlog(guild, embed=embed)
score = 0
msg = ''
await self.redis.set(key, f'{score}:{repeats}:{msg}', expire=old_ttl)
@command(ignore_extra=True)
@check(lambda ctx: ctx.author.id==3<PASSWORD>) # Check if chad
async def rt2_lock(self, ctx):
if ctx.channel.id != 341610158755020820:
return await ctx.send("This isn't rt2")
mod = self.bot.get_cog('Moderator')
if not mod:
return await ctx.send("This bot doesn't support locking")
await mod._set_channel_lock(ctx, True)
@command(ignore_extra=True, hidden=True)
@cooldown(1, 60, BucketType.channel)
async def zeta(self, ctx):
try:
await ctx.message.delete()
except discord.HTTPException:
pass
try:
wh = await ctx.channel.webhooks()
if not wh:
return
wh = wh[0]
except discord.HTTPException:
return
waifu = choice(len(waifus), p=chances)
waifu = waifus[waifu]
def get_inits(s):
inits = ''
for c in s.split(' '):
inits += f'{c[0].upper()}. '
return inits
initials = get_inits(waifu[0])
link = choice(waifu[2])
desc = """
A waifu/husbando appeared!
Try guessing their name with `.claim <name>` to claim them!
Hints:
This character's initials are '{}'
Use `.lookup <name>` if you can't remember the full name.
(If the image is missing, click [here]({})."""
desc = textwrap.dedent(desc).format(initials, link).strip()
e = discord.Embed(title='Character', color=16745712, description=desc)
e.set_image(url=link)
wb = self.bot.get_user(472141928578940958)
await wh.send(embed=e, username=wb.name, avatar_url=wb.avatar_url)
guessed = False
def check_(msg):
if msg.channel != ctx.channel:
return False
content = msg.content.lower()
if content.startswith('.claim '):
return True
return False
name = waifu[0]
while not guessed:
try:
msg = await self.bot.wait_for('message', check=check_, timeout=360)
except asyncio.TimeoutError:
return
guess = ' '.join(msg.content.split(' ')[1:]).replace('-', ' ').lower()
if guess != name.lower():
await wh.send("That isn't the right name.", username=wb.name, avatar_url=wb.avatar_url)
continue
await wh.send(f'Nice {msg.author.mention}, you claimed [ζ] {name}!', username=wb.name, avatar_url=wb.avatar_url)
return
def setup(bot):
bot.add_cog(ServerSpecific(bot))
<file_sep>import logging
from datetime import datetime
import discord
from discord.ext.commands import BucketType, bot_has_permissions
from sqlalchemy.exc import SQLAlchemyError
from bot.bot import command, cooldown
from bot.converters import AnyUser, CommandConverter
from cogs.cog import Cog
from utils.utilities import send_paged_message, format_timedelta
logger = logging.getLogger('debug')
terminal = logging.getLogger('terminal')
class Stats(Cog):
def __init__(self, bot):
super().__init__(bot)
@command(no_pm=True)
@cooldown(2, 5, type=BucketType.guild)
@bot_has_permissions(embed_links=True)
async def mention_stats(self, ctx, page=None):
"""
Get stats on how many times which roles are mentioned on this server
Only counts mentions in channels the bot can see
Also matches all role mentions not just those that ping"""
guild = ctx.guild
if page is not None:
try:
# No one probably hasn't created this many roles
if len(page) > 3:
return await ctx.send('Page out of range')
page = int(page)
if page <= 0:
page = 1
except ValueError:
page = 1
else:
page = 1
sql = 'SELECT * FROM `mention_stats` WHERE guild={} ORDER BY amount DESC LIMIT {}'.format(guild.id, 10*page)
rows = (await self.bot.dbutil.execute(sql)).fetchall()
if not rows:
return await ctx.send('No role mentions logged on this server')
embed = discord.Embed(title='Most mentioned roles in server {}'.format(guild.name))
added = 0
p = page*10
for idx, row in enumerate(rows[p-10:p]):
added += 1
role = guild.get_role(row['role'])
if role:
role_name, role = role.name, role.id
else:
role_name, role = row['role_name'], row['role']
embed.add_field(name='{}. {}'.format(idx + p-9, role),
value='<@&{}>\n{}\nwith {} mentions'.format(role, role_name, row['amount']))
if added == 0:
return await ctx.send('Page out of range')
await ctx.send(embed=embed)
@command(aliases=['seen'])
@cooldown(1, 5, BucketType.user)
async def last_seen(self, ctx, *, user: AnyUser):
"""Get when a user was last seen on this server and elsewhere
User can be a mention, user id, or full discord username with discrim Username#0001"""
if isinstance(user, discord.User):
user_id = user.id
username = str(user)
elif isinstance(user, int):
user_id = user
username = None
else:
user_id = None
username = user
if user_id:
user_clause = 'user=:user'
else:
user_clause = 'username=:user'
guild = ctx.guild
if guild is not None:
guild = guild.id
sql = 'SELECT seen.* FROM `last_seen_users` seen WHERE guild=:guild AND {0} ' \
'UNION ALL (SELECT seen2.* FROM `last_seen_users` seen2 WHERE guild!=:guild AND {0} ORDER BY seen2.last_seen DESC LIMIT 1)'.format(user_clause)
else:
guild = 0
sql = 'SELECT * FROM `last_seen_users` WHERE guild=0 AND %s' % user_clause
try:
rows = (await self.bot.dbutil.execute(sql, {'guild': guild, 'user': user_id or username})).fetchall()
except SQLAlchemyError:
terminal.exception('Failed to get last seen from db')
return await ctx.send('Failed to get user because of an error')
if len(rows) == 0:
return await ctx.send("No users found with {}. Either the bot hasn't had the chance to log activity or the name was wrong."
"Names are case sensitive and must include the discrim".format(username))
local = None
global_ = None
for row in rows:
if not guild or row['guild'] != guild:
global_ = row
else:
local = row
if user_id is None:
if local:
user_id = local['user']
else:
user_id = global_['user']
if username is None:
username = local['username']
msg = 'User {} `{}`\n'.format(username, user_id)
if local:
time = local['last_seen']
fmt = format_timedelta(datetime.utcnow() - time, accuracy=2)
msg += 'Last seen on this server `{} UTC` {} ago\n'.format(time, fmt)
if global_:
time = global_['last_seen']
fmt = format_timedelta(datetime.utcnow() - time, accuracy=2)
msg += 'Last seen elsewhere `{} UTC` {} ago'.format(time, fmt)
await ctx.send(msg)
@command(aliases=['cmdstats'])
@cooldown(1, 5, BucketType.guild)
async def command_stats(self, ctx, cmd: CommandConverter=None):
"""
Get command usage statistics. If command is provided only get the stats
for that command
"""
if cmd:
cmd = cmd.qualified_name.split(' ')
parent = cmd[0]
name = ' '.join(cmd[1:])
else:
parent = None
name = None
cmds = await self.bot.dbutil.get_command_stats(parent, name)
if not cmds:
return await ctx.send('Failed to get command stats')
pages = list(cmds)
size = 15
pages = [pages[i:i+size] for i in range(0, len(pages), size)]
def get_page(page, idx):
if isinstance(page, discord.Embed):
return page
desc = ''
for r in page:
desc += f'`{r["parent"]}'
name = r['cmd']
if name:
desc += f' {name}'
desc += f'` {r["uses"]} uses\n'
embed = discord.Embed(title='Command usage stats', description=desc)
embed.set_footer(text=f'{idx+1}/{len(pages)}')
pages[idx] = embed
return embed
await send_paged_message(ctx, pages, embed=True, page_method=get_page)
def setup(bot):
bot.add_cog(Stats(bot))
<file_sep>import asyncio
import base64
import logging
from datetime import datetime
from math import ceil
import discord
from discord.ext.commands import BucketType, bot_has_permissions
from discord.user import BaseUser
from validators import url as is_url
from bot.bot import command, has_permissions, cooldown, group
from bot.converters import PossibleUser, GuildEmoji
from cogs.cog import Cog
from utils.imagetools import raw_image_from_url
from utils.utilities import (get_emote_url, get_emote_name, send_paged_message,
basic_check, format_timedelta, DateAccuracy,
create_custom_emoji, wait_for_yes)
logger = logging.getLogger('debug')
class Server(Cog):
def __init__(self, bot):
super().__init__(bot)
@group(no_pm=True, invoke_without_command=True)
@cooldown(1, 20, type=BucketType.user)
async def top(self, ctx, page: int=1):
"""Get the top users on this server based on the most important values"""
if page > 0:
page -= 1
guild = ctx.guild
sorted_users = sorted(guild.members, key=lambda u: len(u.roles), reverse=True)
# Indexes of all of the pages
pages = list(range(1, ceil(len(guild.members)/10)+1))
def get_msg(page, _):
s = 'Leaderboards for **{}**\n\n```md\n'.format(guild.name)
added = 0
p = page*10
for idx, u in enumerate(sorted_users[p-10:p]):
added += 1
s += '{}. {} with {} roles\n'.format(idx + p-9, u, len(u.roles) - 1)
if added == 0:
return 'Page out of range'
try:
idx = sorted_users.index(ctx.author) + 1
s += '\nYour rank is {} with {} roles\n'.format(idx, len(ctx.author.roles) - 1)
except:
pass
s += '```'
return s
await send_paged_message(ctx, pages, starting_idx=page,
page_method=get_msg)
async def _date_sort(self, ctx, page, key, dtype='joined'):
if page > 0:
page -= 1
guild = ctx.guild
sorted_users = list(sorted(guild.members, key=key))
# Indexes of all of the pages
pages = list(range(1, ceil(len(guild.members)/10)+1))
own_rank = ''
try:
idx = sorted_users.index(ctx.author) + 1
t = datetime.utcnow() - key(ctx.author)
t = format_timedelta(t, DateAccuracy.Day)
own_rank = f'\nYour rank is {idx}. You {dtype} {t} ago at {key(ctx.author).strftime("%a, %d %b %Y %H:%M:%S GMT")}\n'
except:
pass
def get_page(pg, _):
s = 'Leaderboards for **{}**\n\n```md\n'.format(guild.name)
index = pg*10
page = sorted_users[index-10:index]
max_s = max(map(lambda u: len(str(u)), page))
if not page:
return 'Page out of range'
for idx, u in enumerate(page):
t = datetime.utcnow() - key(u)
t = format_timedelta(t, DateAccuracy.Day)
join_date = key(u).strftime('%a, %d %b %Y %H:%M:%S GMT')
# We try to align everything but due to non monospace fonts
# it will never be perfect
tabs, spaces = divmod(max_s-len(str(u)), 4)
padding = '\t'*tabs + ' '*spaces
s += f'{idx+index-9}. {u} {padding}{dtype} {t} ago at {join_date}\n'
s += own_rank
s += '```'
return s
await send_paged_message(ctx, pages, starting_idx=page, page_method=get_page)
@top.command(np_pm=True)
@cooldown(1, 10)
async def join(self, ctx, page: int=1):
"""Sort users by join date"""
await self._date_sort(ctx, page, lambda u: u.joined_at, 'joined')
@top.command(np_pm=True)
@cooldown(1, 10)
async def created(self, ctx, page: int=1):
"""Sort users by join date"""
await self._date_sort(ctx, page, lambda u: u.created_at, 'created')
@command(no_dm=True, aliases=['mr_top', 'mr_stats'])
@cooldown(2, 5, BucketType.channel)
async def mute_roll_top(self, ctx, user: PossibleUser=None):
stats = await self.bot.dbutil.get_mute_roll(ctx.guild.id)
if not stats:
return await ctx.send('No mute roll stats on this server')
page_length = ceil(len(stats)/10)
pages = [False for _ in range(page_length)]
title = f'Mute roll stats for guild {ctx.guild}'
def cache_page(idx, custom_description=None):
i = idx*10
rows = stats[i:i+10]
if custom_description:
embed = discord.Embed(title=title, description=custom_description)
else:
embed = discord.Embed(title=title)
embed.set_footer(text=f'Page {idx+1}/{len(pages)}')
for row in rows:
winrate = round(row['wins'] * 100 / row['games'], 1)
v = f'<@{row["user"]}>\n' \
f'Winrate: {winrate}% with {row["wins"]} wins \n'\
f'Current streak: {row["current_streak"]}\n' \
f'Biggest streak: {row["biggest_streak"]}'
embed.add_field(name=f'{row["games"]} games', value=v)
pages[idx] = embed
return embed
def get_page(page, idx):
if not page:
return cache_page(idx)
return page
if isinstance(user, BaseUser):
user_id = user.id
else:
user_id = user
if user_id:
for idx, r in enumerate(stats):
if r['user'] == user_id:
i = idx // 10
winrate = round(r['wins'] * 100 / r['games'], 1)
d = f'Stats for <@{user_id}> at page {i+1}\n' \
f'Winrate: {winrate}% with {r["wins"]} wins \n' \
f'Current streak: {r["current_streak"]}\n' \
f'Biggest streak: {r["biggest_streak"]}'
e = discord.Embed(description=d)
e.set_footer(text=f'Ranking {idx+1}/{len(stats)}')
await ctx.send(embed=e)
return
return await ctx.send(f"Didn't find user {user} on the leaderboards.\n"
"Are you sure they have played mute roll")
await send_paged_message(ctx, pages, embed=True, page_method=get_page)
async def _dl(self, ctx, url):
try:
data, mime_type = await raw_image_from_url(url, self.bot.aiohttp_client,
get_mime=True)
except OverflowError:
await ctx.send('Failed to download. File is too big')
except TypeError:
await ctx.send('Link is not a direct link to an image')
else:
return data, mime_type
@command(no_pm=True, aliases=['delete_emoji', 'delete_emtoe', 'del_emote'])
@cooldown(2, 6, BucketType.guild)
@has_permissions(manage_emojis=True)
@bot_has_permissions(manage_emojis=True)
async def delete_emote(self, ctx, *, emote: GuildEmoji):
await ctx.send('Do you want to delete the emoji {0} {0.name} `{0.id}`'.format(emote))
if not await wait_for_yes(ctx, 60):
return
try:
await emote.delete()
except discord.HTTPException as e:
await ctx.send('Failed to delete emote because of an error\n%s' % e)
except:
logger.exception('Failed to delete emote')
await ctx.send('Failed to delete emote because of an error')
else:
await ctx.send(f'Deleted emote {emote.name} `{emote.id}`')
@command(no_pm=True, aliases=['addemote', 'addemoji', 'add_emoji', 'add_emtoe'])
@cooldown(2, 6, BucketType.guild)
@has_permissions(manage_emojis=True)
@bot_has_permissions(manage_emojis=True)
async def add_emote(self, ctx, link, *name):
"""Add an emote to the server"""
guild = ctx.guild
author = ctx.author
if is_url(link):
if not name:
await ctx.send('What do you want to name the emote as', delete_after=30)
try:
msg = await self.bot.wait_for('message', check=basic_check(author=author, channel=ctx.channel), timeout=30)
except asyncio.TimeoutError:
msg = None
if not msg:
return await ctx.send('Took too long.')
data = await self._dl(ctx, link)
name = ' '.join(name)
else:
if not ctx.message.attachments:
return await ctx.send('No image provided')
data = await self._dl(ctx, ctx.message.attachments[0].url)
name = link + ' '.join(name)
if not data:
return
data, mime = data
if 'gif' in mime:
fmt = 'data:{mime};base64,{data}'
b64 = base64.b64encode(data.getvalue()).decode('ascii')
img = fmt.format(mime=mime, data=b64)
already_b64 = True
else:
img = data.getvalue()
already_b64 = False
try:
await create_custom_emoji(guild=guild, name=name, image=img, already_b64=already_b64,
reason=f'{ctx.author} created emote')
except discord.HTTPException as e:
await ctx.send('Failed to create emote because of an error\n%s\nDId you check if the image is under 256kb in size' % e)
except:
await ctx.send('Failed to create emote because of an error')
logger.exception('Failed to create emote')
else:
await ctx.send('created emote %s' % name)
@command(no_pm=True, aliases=['trihard'])
@cooldown(2, 6, BucketType.guild)
@has_permissions(manage_emojis=True)
@bot_has_permissions(manage_emojis=True)
async def steal(self, ctx, *emoji):
"""Add emotes to this server from other servers.
Usage:
{prefix}{name} :emote1: :emote2: :emote3:"""
if not emoji:
return await ctx.send('Specify the emotes you want to steal')
errors = 0
guild = ctx.guild
emotes = []
for e in emoji:
if errors >= 3:
return await ctx.send('Too many errors while uploading emotes. Aborting')
url = get_emote_url(e)
if not url:
continue
if e.startswith(url):
name = url.split('/')[-1].split('.')[0]
else:
_, name = get_emote_name(e)
if not name:
continue
data = await self._dl(ctx, url)
if not data:
continue
data, mime = data
if 'gif' in mime:
fmt = 'data:{mime};base64,{data}'
b64 = base64.b64encode(data.getvalue()).decode('ascii')
img = fmt.format(mime=mime, data=b64)
already_b64 = True
else:
img = data.getvalue()
already_b64 = False
try:
emote = await create_custom_emoji(guild=guild, name=name, image=img, already_b64=already_b64,
reason=f'{ctx.author} stole emote')
emotes.append(emote)
except discord.HTTPException as e:
if e.code == 400:
return await ctx.send('Emote capacity reached\n{}'.format(e))
await ctx.send('Error while uploading emote\n%s' % e)
errors += 1
except:
await ctx.send('Failed to create emote because of an error')
logger.exception('Failed to create emote')
errors += 1
if emotes:
await ctx.send('Successfully stole {}'.format(' '.join(map(lambda e: str(e), emotes))))
else:
await ctx.send("Didn't steal anything")
def setup(bot):
bot.add_cog(Server(bot))
<file_sep>"""
MIT License
Copyright (c) 2017 s0hvaperuna
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.
"""
import asyncio
import inspect
import itertools
import logging
import discord
from aiohttp import ClientSession
from discord import state
from discord.ext import commands
from discord.ext.commands import CommandNotFound, bot_has_permissions
from discord.ext.commands.bot import _mention_pattern, _mentions_transforms
from discord.ext.commands.errors import CommandError
from discord.ext.commands.formatter import HelpFormatter, Paginator
from discord.http import HTTPClient
from bot.cooldowns import Cooldown, CooldownMapping
from bot.formatter import Formatter
from bot.globals import Auth
from utils.utilities import is_owner, check_blacklist, no_dm, seconds2str
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
from bot import exceptions
log = logging.getLogger('discord')
logger = logging.getLogger('debug')
terminal = logging.getLogger('terminal')
class Context(commands.context.Context):
__slots__ = ('override_perms', 'skip_check', 'original_user', 'domain',
'received_at')
def __init__(self, **attrs):
super().__init__(**attrs)
self.override_perms = attrs.pop('override_perms', None)
self.original_user = self.author # Used to determine original user with runas
# Used when wanting to skip database check like in help command
self.skip_check = attrs.pop('skip_check', False)
self.domain = attrs.get('domain', None)
self.received_at = attrs.get('received_at', None)
class Command(commands.Command):
def __init__(self, name, callback, **kwargs):
super(Command, self).__init__(name=name, callback=callback, **kwargs)
self.level = kwargs.pop('level', 0)
self.owner_only = kwargs.pop('owner_only', False)
self.auth = kwargs.pop('auth', Auth.NONE)
if 'required_perms' in kwargs:
raise DeprecationWarning('Required perms is deprecated, use "from bot.bot import has_permissions" instead')
self.checks.insert(0, check_blacklist)
if self.owner_only:
terminal.info('registered owner_only command %s' % name)
self.checks.insert(0, is_owner)
if 'no_pm' in kwargs or 'no_dm' in kwargs:
self.checks.insert(0, no_dm)
def undo_use(self, ctx):
"""Undoes one use of command"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx.message)
bucket.undo_one()
async def can_run(self, ctx):
original = ctx.command
ctx.command = self
try:
if not (await ctx.bot.can_run(ctx)):
raise commands.errors.CheckFailure('The global check functions for command {0.qualified_name} failed.'.format(self))
cog = self.instance
if cog is not None:
try:
local_check = getattr(cog, '_{0.__class__.__name__}__local_check'.format(cog))
except AttributeError:
pass
else:
ret = await discord.utils.maybe_coroutine(local_check, ctx)
if not ret:
return False
predicates = self.checks
if not predicates:
# since we have no checks, then we just return True.
return True
return ctx.override_perms or await discord.utils.async_all(predicate(ctx) for predicate in predicates)
finally:
ctx.command = original
class Group(Command, commands.Group):
def __init__(self, **attrs):
Command.__init__(self, **attrs)
self.invoke_without_command = attrs.pop('invoke_without_command', False)
def group(self, *args, **kwargs):
def decorator(func):
result = group(*args, **kwargs)(func)
self.add_command(result)
return result
return decorator
def command(self, *args, **kwargs):
def decorator(func):
if 'owner_only' not in kwargs:
kwargs['owner_only'] = self.owner_only
result = command(*args, **kwargs)(func)
self.add_command(result)
return result
return decorator
class ConnectionState(state.ConnectionState):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def parse_message_delete_bulk(self, data):
message_ids = set(data.get('ids', []))
to_be_deleted = []
for msg in self._messages:
if msg.id in message_ids:
to_be_deleted.append(msg)
message_ids.remove(msg.id)
for msg in to_be_deleted:
self._messages.remove(msg)
if to_be_deleted:
self.dispatch('bulk_message_delete', to_be_deleted)
if message_ids:
self.dispatch('raw_bulk_message_delete', message_ids)
class Client(discord.Client):
def __init__(self, loop=None, **options):
self.ws = None
self._exit_code = 0
self.loop = asyncio.get_event_loop() if loop is None else loop
self._listeners = {}
self.shard_id = options.get('shard_id')
self.shard_count = options.get('shard_count')
connector = options.pop('connector', None)
proxy = options.pop('proxy', None)
proxy_auth = options.pop('proxy_auth', None)
self.http = HTTPClient(connector, proxy=proxy, proxy_auth=proxy_auth, loop=self.loop)
self._handlers = {
'ready': self._handle_ready
}
self._connection = ConnectionState(dispatch=self.dispatch, chunker=self._chunker, handlers=self._handlers,
syncer=self._syncer, http=self.http, loop=self.loop, **options)
self._connection.shard_count = self.shard_count
self._closed = asyncio.Event(loop=self.loop)
self._ready = asyncio.Event(loop=self.loop)
self._connection._get_websocket = lambda g: self.ws
if discord.VoiceClient.warn_nacl:
discord.VoiceClient.warn_nacl = False
log.warning("PyNaCl is not installed, voice will NOT be supported")
class Bot(commands.Bot, Client):
def __init__(self, prefix, config, aiohttp=None, **options):
if 'formatter' not in options:
options['formatter'] = Formatter(width=150)
super().__init__(prefix, owner_id=config.owner, **options)
self._runas = None
self.remove_command('help')
@self.group(invoke_without_command=True)
@bot_has_permissions(embed_links=True)
@cooldown(2, 10, commands.BucketType.guild)
async def help(ctx, *commands_: str):
"""Shows all commands you can use on this server.
Use {prefix}{name} all to see all commands"""
await self._help(ctx, *commands_)
@help.command(name='all')
@bot_has_permissions(embed_links=True)
@cooldown(1, 10, commands.BucketType.guild)
async def all_(ctx, *commands_: str):
"""Shows all available commands even if you don't have the correct
permissions to use the commands. Bot owner only commands are still hidden tho"""
await self._help(ctx, *commands_, type=Formatter.Generic)
log.debug('Using loop {}'.format(self.loop))
if aiohttp is None:
aiohttp = ClientSession(loop=self.loop)
self.aiohttp_client = aiohttp
self.config = config
self.voice_clients_ = {}
self._error_cdm = CooldownMapping(commands.Cooldown(2, 5, commands.BucketType.guild))
@property
def runas(self):
return self._runas
def _check_error_cd(self, message):
if self._error_cdm.valid:
bucket = self._error_cdm.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
return False
return True
async def on_command_error(self, context, exception):
"""|coro|
The default command error handler provided by the bot.
By default this prints to ``sys.stderr`` however it could be
overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
"""
if self.extra_events.get('on_command_error', None):
return
if hasattr(context.command, "on_error"):
return
if hasattr(exception, 'original'):
exception = exception.original
if isinstance(exception, commands.errors.CommandNotFound):
return
if isinstance(exception, exceptions.SilentException):
return
if isinstance(exception, exceptions.PermException):
return
if isinstance(exception, discord.Forbidden):
return
if isinstance(exception, exceptions.NotOwner):
return
channel = context.channel
if isinstance(exception, commands.errors.BotMissingPermissions) or isinstance(exception, commands.errors.MissingPermissions):
if self._check_error_cd(context.message):
try:
return await channel.send(str(exception))
except discord.Forbidden:
pass
return
if isinstance(exception, commands.errors.CheckFailure):
return
error_msg = None
if isinstance(exception, commands.errors.CommandOnCooldown):
error_msg = 'Command on cooldown. Try again in {}'.format(seconds2str(exception.retry_after, False))
if isinstance(exception, commands.errors.BadArgument) or isinstance(exception, commands.errors.MissingRequiredArgument) or isinstance(exception, commands.BadUnionArgument):
error_msg = str(exception)
if isinstance(exception, exceptions.BotException):
error_msg = str(exception)
if error_msg:
if self._check_error_cd(context.message):
try:
await channel.send(error_msg, delete_after=300)
except discord.Forbidden:
pass
return
terminal.warning('Ignoring exception in command {}'.format(context.command))
terminal.exception('', exc_info=exception)
@staticmethod
def get_role_members(role, guild):
members = []
for member in guild.members:
if role in member.roles:
members.append(member)
return members
async def _help(self, ctx, *commands, type=Formatter.ExtendedFilter):
"""Shows this message."""
author = ctx.author
if isinstance(ctx.author, discord.User):
type = Formatter.Generic
bot = ctx.bot
destination = ctx.message.channel
is_owner = author.id == self.owner_id
def repl(obj):
return _mentions_transforms.get(obj.group(0), '')
# help by itself just lists our own commands.
if len(commands) == 0:
pages = await self.formatter.format_help_for(ctx, self, is_owner=is_owner, type=type)
elif len(commands) == 1:
# try to see if it is a cog name
name = _mention_pattern.sub(repl, commands[0])
command = None
if name in bot.cogs:
command = bot.cogs[name]
else:
command = bot.all_commands.get(name)
if command is None:
ctx.command.undo_use(ctx)
await destination.send(bot.command_not_found.format(name))
return
pages = await self.formatter.format_help_for(ctx, command, is_owner=is_owner, type=type)
else:
name = _mention_pattern.sub(repl, commands[0])
command = bot.all_commands.get(name)
if command is None:
ctx.command.undo_use(ctx)
await destination.send(bot.command_not_found.format(name))
return
for key in commands[1:]:
try:
key = _mention_pattern.sub(repl, key)
command = command.all_commands.get(key)
if command is None:
ctx.command.undo_use(ctx)
await destination.send(bot.command_not_found.format(key))
return
except AttributeError:
ctx.command.undo_use(ctx)
await destination.send(bot.command_has_no_subcommands.format(command, key))
return
pages = await self.formatter.format_help_for(ctx, command, is_owner=is_owner, type=type)
for page in pages:
await destination.send(embed=page)
async def invoke(self, ctx):
"""|coro|
Invokes the command given under the invocation context and
handles all the internal event dispatch mechanisms.
Parameters
-----------
ctx: :class:`.Context`
The invocation context to invoke.
"""
if ctx.command is not None:
self.dispatch('command', ctx)
try:
if (await self.can_run(ctx, call_once=True)):
await ctx.command.invoke(ctx)
except CommandError as e:
await ctx.command.dispatch_error(ctx, e)
else:
self.dispatch('command_completion', ctx)
elif ctx.invoked_with:
exc = CommandNotFound('Command "{}" is not found'.format(ctx.invoked_with))
self.dispatch('command_error', ctx, exc)
async def get_context(self, message, *, cls=Context):
ctx = await super().get_context(message, cls=cls)
if self.runas is not None and message.author.id == self.owner_id:
if ctx.guild:
member = ctx.guild.get_member(self.runas.id)
if not member:
return ctx
else:
member = self.runas
ctx.author = member
ctx.message.author = member
return ctx
async def process_commands(self, message, local_time=None):
ctx = await self.get_context(message, cls=Context)
ctx.received_at = local_time
await self.invoke(ctx)
def command(self, *args, **kwargs):
"""A shortcut decorator that invokes :func:`command` and adds it to
the internal command list via :meth:`add_command`.
"""
def decorator(func):
result = command(*args, **kwargs)(func)
self.add_command(result)
return result
return decorator
def group(self, *args, **kwargs):
def decorator(func):
result = group(*args, **kwargs)(func)
self.add_command(result)
return result
return decorator
def handle_reaction_changed(self, reaction, user):
removed = []
event = 'reaction_changed'
listeners = self._listeners.get(event)
if not listeners:
return
for i, (future, condition) in enumerate(listeners):
if future.cancelled():
removed.append(i)
continue
try:
result = condition(reaction, user)
except Exception as e:
future.set_exception(e)
removed.append(i)
else:
if result:
future.set_result((reaction, user))
removed.append(i)
if len(removed) == len(listeners):
self._listeners.pop(event)
else:
for idx in reversed(removed):
del listeners[idx]
async def on_reaction_add(self, reaction, user):
self.handle_reaction_changed(reaction, user)
async def on_reaction_remove(self, reaction, user):
self.handle_reaction_changed(reaction, user)
@staticmethod
def get_role(role_id, guild):
if role_id is None:
return
return discord.utils.find(lambda r: r.id == role_id, guild.roles)
def command(*args, **attrs):
if 'cls' not in attrs:
attrs['cls'] = Command
return commands.command(*args, **attrs)
def group(name=None, **attrs):
"""Uses custom Group class"""
if 'cls' not in attrs:
attrs['cls'] = Group
return commands.command(name=name, **attrs)
def cooldown(rate, per, type=commands.BucketType.default):
"""See `commands.cooldown` docs"""
def decorator(func):
if isinstance(func, Command):
func._buckets = CooldownMapping(Cooldown(rate, per, type))
else:
func.__commands_cooldown__ = Cooldown(rate, per, type)
return func
return decorator
def has_permissions(**perms):
"""
Same as the default discord.ext.commands.has_permissions
except this one supports overriding perms
"""
def predicate(ctx):
if ctx.override_perms:
return True
ch = ctx.channel
permissions = ch.permissions_for(ctx.author)
missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value]
if not missing:
return True
raise commands.MissingPermissions(missing)
return commands.check(predicate)
class FormatterDeprecated(HelpFormatter):
Generic = 0
Cog = 1
Command = 2
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def format_help_for(self, context, command_or_bot, is_owner=False):
self.context = context
self.command = command_or_bot
return self.format(is_owner=is_owner)
def format(self, is_owner=False, generic=False):
"""Handles the actual behaviour involved with formatting.
To change the behaviour, this method should be overridden.
Returns
--------
list
A paginated output of the help command.
"""
if generic:
self._paginator = Paginator(prefix='```Markdown\n')
else:
self._paginator = Paginator(prefix='', suffix='')
# we need a padding of ~80 or so
description = self.command.description if not self.is_cog() else inspect.getdoc(self.command)
if description:
# <description> portion
self._paginator.add_line(description, empty=True)
if isinstance(self.command, Command):
# <signature portion>
signature = self.get_command_signature()
if self.command.owner_only:
signature = 'This command is owner only\n' + signature
self._paginator.add_line(signature, empty=True)
# <long doc> section
if self.command.help:
self._paginator.add_line(self.command.help, empty=True)
# end it here if it's just a regular command
if not self.has_subcommands():
self._paginator.close_page()
return self._paginator.pages
max_width = self.max_name_size
def category(tup):
cog = tup[1].cog_name
# we insert the zero width space there to give it approximate
# last place sorting position.
return cog + ':' if cog is not None else '\u200bNo Category:'
if self.is_bot():
data = sorted(self.filter_command_list(), key=category)
for category, commands in itertools.groupby(data, key=category):
# there simply is no prettier way of doing this.
commands = list(commands)
if len(commands) > 0:
self._paginator.add_line('#' + category)
self._add_subcommands_to_page(max_width, commands, is_owner=is_owner)
else:
self._paginator.add_line('Commands:')
self._add_subcommands_to_page(max_width, self.filter_command_list(), is_owner=is_owner)
# add the ending note
self._paginator.add_line()
ending_note = self.get_ending_note()
self._paginator.add_line(ending_note)
return self._paginator.pages
def _add_subcommands_to_page(self, max_width, commands, is_owner=False):
for name, command in commands:
if name in command.aliases:
# skip aliases
continue
if command.owner_only and not is_owner:
continue
entry = ' {0:<{width}} {1}'.format(name, command.short_doc, width=max_width)
shortened = self.shorten(entry)
self._paginator.add_line(shortened)
<file_sep>import asyncio
import logging
import os
import re
from datetime import datetime, timedelta
from random import randint, random
import discord
from discord.ext.commands import (BucketType, bot_has_permissions)
from sqlalchemy.exc import SQLAlchemyError
from bot.bot import command, group, has_permissions, cooldown
from bot.converters import MentionedMember, PossibleUser, TimeDelta
from bot.globals import DATA
from cogs.cog import Cog
from utils.utilities import (call_later, parse_timeout,
datetime2sql, get_avatar, find_user,
seconds2str, get_role, get_channel, Snowflake,
basic_check, sql2timedelta, check_botperm)
logger = logging.getLogger('debug')
manage_roles = discord.Permissions(268435456)
lock_perms = discord.Permissions(268435472)
class Moderator(Cog):
def __init__(self, bot):
super().__init__(bot)
self.timeouts = self.bot.timeouts
self.temproles = self.bot.temproles
self.automute_blacklist = {}
self.automute_whitelist = {}
self._current_rolls = {} # Users currently active in a mute roll
self._load_timeouts()
self._load_automute()
self._load_temproles()
def __unload(self):
for timeouts in list(self.timeouts.values()):
for timeout in list(timeouts.values()):
timeout.cancel()
for temproles in list(self.temproles.values()):
for temprole in list(temproles.values()):
temprole.cancel()
def _load_automute(self):
sql = 'SELECT * FROM `automute_blacklist`'
session = self.bot.get_session
rows = session.execute(sql)
for row in rows:
id_ = row['guild']
if id_ not in self.automute_blacklist:
s = set()
self.automute_blacklist[id_] = s
else:
s = self.automute_blacklist[id_]
s.add(row['channel'])
sql = 'SELECT * FROM `automute_whitelist`'
rows = session.execute(sql)
for row in rows:
id_ = row['guild']
if id_ not in self.automute_whitelist:
s = set()
self.automute_whitelist[id_] = s
else:
s = self.automute_whitelist[id_]
s.add(row['role'])
def _load_temproles(self):
session = self.bot.get_session
sql = 'SELECT * FROM `temproles`'
rows = session.execute(sql)
for row in rows:
time = row['expires_at'] - datetime.utcnow()
guild = row['guild']
user = row['user']
role = row['role']
self.register_temprole(user, role, guild, time.total_seconds())
def _load_timeouts(self):
session = self.bot.get_session
sql = 'SELECT * FROM `timeouts`'
rows = session.execute(sql)
for row in rows:
try:
time = row['expires_on'] - datetime.utcnow()
guild = row['guild']
user = row['user']
if guild not in self.timeouts:
guild_timeouts = {}
self.timeouts[guild] = guild_timeouts
else:
guild_timeouts = self.timeouts.get(guild)
t = guild_timeouts.get(user)
if t:
t.cancel()
seconds = time.total_seconds()
if seconds <= 1:
seconds = 1
task = call_later(self.untimeout, self.bot.loop, seconds,
user, guild, after=lambda f: guild_timeouts.pop(user, None))
guild_timeouts[user] = task
except:
logger.exception('Could not untimeout %s' % row)
async def send_to_modlog(self, guild, *args, **kwargs):
if isinstance(guild, int):
guild = self.bot.get_guild(guild)
if not guild:
return
channel = self.get_modlog(guild)
if channel is None:
return
perms = channel.permissions_for(channel.guild.get_member(self.bot.user.id))
is_embed = 'embed' in kwargs
if not perms.send_messages:
return
if is_embed and not perms.embed_links:
return
await channel.send(*args, **kwargs)
async def on_message(self, message):
guild = message.guild
if guild and self.bot.guild_cache.automute(guild.id):
if message.webhook_id:
return
mute_role = self.bot.guild_cache.mute_role(guild.id)
mute_role = discord.utils.find(lambda r: r.id == mute_role, message.guild.roles)
if not mute_role:
return
user = message.author
if not isinstance(user, discord.Member):
logger.debug(f'User found when expected member guild {guild.name} user {user} in channel {message.channel.name}')
user = guild.get_member(user.id)
if not user:
return
if mute_role in user.roles:
return
if not check_botperm('manage_roles', guild=message.guild, channel=message.channel):
return
s = '.img penile hemorrhage'
if guild.id == 217677285442977792 and message.content.strip().lower() == s:
def check(msg):
if msg.author.id != 439205512425504771 or msg.channel != message.channel:
return False
if not msg.embeds or not msg.embeds[0].author:
return False
embed = msg.embeds[0]
if embed.title != 'Image Search Results' or (isinstance(embed.author.icon_url, str) and str(user.id) not in embed.author.icon_url):
return False
return True
try:
msg = await self.bot.wait_for('message', check=check, timeout=20)
except asyncio.TimeoutError:
return
await msg.delete()
time = timedelta(days=3)
await self.add_timeout(message.channel, guild.id, user.id,
datetime.utcnow() + time, time.total_seconds(),
reason=f'Automuted for {message.content}')
await message.author.add_roles(mute_role, reason=f'[Automute] {message.content}')
d = f'Automuted user {user} `{user.id}` for {time}'
url = f'https://discordapp.com/channels/{guild.id}/{message.channel.id}/{message.id}'
embed = discord.Embed(title='Moderation action [AUTOMUTE]', description=d,
timestamp=datetime.utcnow())
embed.add_field(name='Reason', value=message.content)
embed.add_field(name='link', value=url)
embed.set_thumbnail(url=user.avatar_url or user.default_avatar_url)
embed.set_footer(text=str(self.bot.user),
icon_url=self.bot.user.avatar_url or self.bot.user.default_avatar_url)
await self.send_to_modlog(guild, embed=embed)
return
limit = self.bot.guild_cache.automute_limit(guild.id)
if len(message.mentions) + len(message.role_mentions) > limit:
blacklist = self.automute_blacklist.get(guild.id, ())
if message.channel.id not in blacklist:
whitelist = self.automute_whitelist.get(guild.id, ())
invulnerable = discord.utils.find(lambda r: r.id in whitelist,
user.roles)
if invulnerable is None:
time = self.bot.guild_cache.automute_time(guild.id)
if time is not None:
if isinstance(time, str):
time = sql2timedelta(time)
await self.add_timeout(message.channel, guild.id, user.id, datetime.utcnow() + time, time.total_seconds(),
reason='Automuted for too many mentions')
d = 'Automuted user {0} `{0.id}` for {1}'.format(message.author, time)
else:
d = 'Automuted user {0} `{0.id}`'.format(message.author)
url = f'https://discordapp.com/channels/{guild.id}/{message.channel.id}/{message.id}'
await message.author.add_roles(mute_role, reason='[Automute] too many mentions in message')
embed = discord.Embed(title='Moderation action [AUTOMUTE]', description=d, timestamp=datetime.utcnow())
embed.add_field(name='Reason', value='Too many mentions in a message')
embed.add_field(name='link', value=url)
embed.set_thumbnail(url=user.avatar_url or user.default_avatar_url)
embed.set_footer(text=str(self.bot.user), icon_url=self.bot.user.avatar_url or self.bot.user.default_avatar_url)
await self.send_to_modlog(guild, embed=embed)
return
@group(invoke_without_command=True, name='automute_whitelist', aliases=['mute_whitelist'], no_pm=True)
@cooldown(2, 5, BucketType.guild)
async def automute_whitelist_(self, ctx):
"""Show roles whitelisted from automutes"""
guild = ctx.guild
roles = self.automute_whitelist.get(guild.id, ())
roles = map(lambda r: guild.get_role(r), roles)
roles = [r for r in roles if r]
if not roles:
return await ctx.send('No roles whitelisted from automutes')
msg = 'Roles whitelisted from automutes'
for r in roles:
msg += '\n{0.name} `{0.id}`'.format(r)
await ctx.send(msg)
@automute_whitelist_.command(no_pm=True)
@has_permissions(manage_guild=True, manage_roles=True)
@cooldown(2, 5, BucketType.guild)
async def add(self, ctx, *, role):
"""Add a role to the automute whitelist"""
guild = ctx.guild
roles = self.automute_whitelist.get(guild.id)
if roles is None:
roles = set()
self.automute_whitelist[guild.id] = roles
if len(roles) >= 10:
return await ctx.send('Maximum of 10 roles can be added to automute whitelist.')
role_ = get_role(role, guild.roles, name_matching=True)
if not role_:
return await ctx.send('Role {} not found'.format(role))
if ctx.author.top_role <= role:
return await ctx.send('The role you are trying to add is higher than your top role in the hierarchy')
success = await self.bot.dbutils.add_automute_whitelist(guild.id, role_.id)
if not success:
return await ctx.send('Failed to add role because of an error')
roles.add(role_.id)
await ctx.send('Added role {0.name} `{0.id}`'.format(role_))
@automute_whitelist_.command(aliases=['del', 'delete'], no_pm=True)
@has_permissions(manage_guild=True, manage_roles=True)
@cooldown(2, 5, BucketType.guild)
async def remove(self, ctx, *, role):
"""Remove a role from the automute whitelist"""
guild = ctx.guild
roles = self.automute_whitelist.get(guild.id, ())
role_ = get_role(role, guild.roles, name_matching=True)
if not role_:
return await ctx.send('Role {} not found'.format(role))
if role_.id not in roles:
return await ctx.send('Role {0.name} not found in whitelist'.format(role_))
if ctx.author.top_role <= role:
return await ctx.send('The role you are trying to remove is higher than your top role in the hierarchy')
success = await self.bot.dbutils.remove_automute_whitelist(guild.id, role.id)
if not success:
return await ctx.send('Failed to remove role because of an error')
roles.discard(role_.id)
await ctx.send('Role {0.name} `{0.id}` removed from automute whitelist'.format(role_))
@group(invoke_without_command=True, name='automute_blacklist', aliases=['mute_blacklist'], no_pm=True)
@cooldown(2, 5, BucketType.guild)
async def automute_blacklist_(self, ctx):
"""Show channels that are blacklisted from automutes.
That means automutes won't triggered from messages sent in those channels"""
guild = ctx.guild
channels = self.automute_blacklist.get(guild.id, ())
channels = map(guild.get_channel, channels)
channels = [c for c in channels if c]
if not channels:
return await ctx.send('No channels blacklisted from automutes')
msg = 'Channels blacklisted from automutes'
for c in channels:
msg += '\n{0.name} `{0.id}`'.format(c)
await ctx.send(msg)
@automute_blacklist_.command(name='add', no_pm=True)
@has_permissions(manage_guild=True, manage_roles=True)
@cooldown(2, 5, BucketType.guild)
async def add_(self, ctx, *, channel: discord.TextChannel):
"""Add a channel to the automute blacklist"""
guild = ctx.guild
channels = self.automute_blacklist.get(guild.id)
if channels is None:
channels = set()
self.automute_whitelist[guild.id] = channels
success = await self.bot.dbutils.add_automute_blacklist(guild.id, channel.id)
if not success:
return await ctx.send('Failed to add channel because of an error')
channels.add(channel.id)
await ctx.send('Added channel {0.name} `{0.id}`'.format(channel))
@automute_blacklist_.command(name='remove', aliases=['del', 'delete'], no_pm=True)
@has_permissions(manage_guild=True, manage_roles=True)
@cooldown(2, 5, BucketType.guild)
async def remove_(self, ctx, *, channel):
"""Remove a channel from the automute blacklist"""
guild = ctx.guild
channels = self.automute_blacklist.get(guild.id, ())
channel_ = get_channel(guild.channels, channel, name_matching=True)
if not channel_:
return await ctx.send('Channel {} not found'.format(channel))
if channel_.id not in channels:
return await ctx.send('Channel {0.name} not found in blacklist'.format(channel_))
success = await self.bot.dbutils.remove_automute_blacklist(guild.id, channel.id)
if not success:
return await ctx.send('Failed to remove channel because of an error')
channels.discard(channel.id)
await ctx.send('Channel {0.name} `{0.id}` removed from automute blacklist'.format(channel_))
# Required perms: manage roles
@command(no_pm=True)
@cooldown(2, 5, BucketType.guild)
@bot_has_permissions(manage_roles=True)
@has_permissions(manage_roles=True)
async def add_role(self, ctx, name, random_color=True, mentionable=True, hoist=False):
"""Add a role to the server.
random_color makes the bot choose a random color for the role and
hoist will make the role show up in the member list"""
guild = ctx.guild
if guild is None:
return await ctx.send('Cannot create roles in DM')
default_perms = guild.default_role.permissions
if random_color:
color = discord.Color(randint(1, 16777215))
else:
color = discord.Color.default()
try:
r = await guild.create_role(name=name, permissions=default_perms, colour=color,
mentionable=mentionable, hoist=hoist,
reason=f'responsible user {ctx.author} {ctx.author.id}')
except discord.HTTPException as e:
return await ctx.send('Could not create role because of an error\n```%s```' % e)
await ctx.send('Successfully created role %s `%s`' % (name, r.id))
async def _mute_check(self, ctx):
guild = ctx.guild
mute_role = self.bot.guild_cache.mute_role(guild.id)
if mute_role is None:
await ctx.send(f'No mute role set. You can set it with {ctx.prefix}settings mute_role role name')
return False
mute_role = guild.get_role(mute_role)
if mute_role is None:
await ctx.send('Could not find the mute role')
return False
return mute_role
@command(no_pm=True)
@bot_has_permissions(manage_roles=True)
@has_permissions(manage_roles=True)
async def mute(self, ctx, user: MentionedMember, *reason):
"""Mute a user. Only works if the server has set the mute role"""
mute_role = await self._mute_check(ctx)
if not mute_role:
return
guild = ctx.guild
if guild.id == 217677285442977792 and user.id == 123050803752730624:
return await ctx.send("Not today kiddo. I'm too powerful for you")
if guild.id == 217677285442977792 and ctx.author.id == <PASSWORD> and user.id == 189458911886049281:
return await ctx.send('No <:peepoWeird:423445885180051467>')
if ctx.author != guild.owner and ctx.author.top_role <= user.top_role:
return await ctx.send('The one you are trying to mute is higher or same as you in the role hierarchy')
reason = ' '.join(reason) if reason else 'No reason <:HYPERKINGCRIMSONANGRY:356798314752245762>'
try:
await user.add_roles(mute_role, reason=f'[{ctx.author}] {reason}')
except discord.HTTPException:
await ctx.send('Could not mute user {}'.format(user))
return
guild_timeouts = self.timeouts.get(guild.id, {})
task = guild_timeouts.get(user.id)
if task:
task.cancel()
await self.remove_timeout(user.id, guild.id)
try:
await ctx.send('Muted user {} `{}`'.format(user.name, user.id))
chn = self.get_modlog(guild)
if chn:
author = ctx.author
description = '{} muted {} {}'.format(author.mention, user, user.id)
url = f'https://discordapp.com/channels/{guild.id}/{ctx.channel.id}/{ctx.message.id}'
embed = discord.Embed(title='🤐 Moderation action [MUTE]',
timestamp=datetime.utcnow(),
description=description)
embed.add_field(name='Reason', value=reason)
embed.add_field(name='link', value=url)
embed.set_thumbnail(url=user.avatar_url or user.default_avatar_url)
embed.set_footer(text=str(author), icon_url=author.avatar_url or author.default_avatar_url)
await self.send_to_modlog(guild, embed=embed)
except discord.HTTPException:
pass
@command(ignore_extra=True, no_dm=True)
@cooldown(2, 3, BucketType.guild)
@bot_has_permissions(manage_roles=True)
async def mute_roll(self, ctx, user: discord.Member, minutes: int):
"""Challenge another user to a game where the loser gets muted for the specified amount of time
ranging from 10 to 60 minutes"""
if not 9 < minutes < 61:
return await ctx.send('Mute length should be between 10 and 60 minutes')
if ctx.author == user:
return await ctx.send("Can't play yourself")
if user.bot:
return await ctx.send("Can't play against a bot since most don't have a free will")
mute_role = await self._mute_check(ctx)
if not mute_role:
return
if mute_role in user.roles or mute_role in ctx.author.roles:
return await ctx.send('One of the participants is already muted')
if ctx.guild.id not in self._current_rolls:
state = set()
self._current_rolls[ctx.guild.id] = state
else:
state = self._current_rolls[ctx.guild.id]
if user.id in state or ctx.author.id in state:
return await ctx.send('One of the users is already participating in a roll')
state.add(user.id)
state.add(ctx.author.id)
try:
await ctx.send(f'{user.mention} type accept to join this mute roll of {minutes} minutes')
_check = basic_check(user, ctx.channel)
def check(msg):
return _check(msg) and msg.content.lower() in ('accept', 'reject', 'no', 'deny', 'decline', 'i refuse')
try:
msg = await self.bot.wait_for('message', check=check, timeout=120)
except asyncio.TimeoutError:
return await ctx.send('Took too long.')
if msg.content.lower() != 'accept':
return await ctx.send(f'{user} declined')
td = timedelta(minutes=minutes)
expires_on = datetime2sql(datetime.utcnow() + td)
msg = await ctx.send(f'{user} vs {ctx.author}\nLoser: <a:loading:449907001569312779>')
await asyncio.sleep(2)
counter = True
counter_counter = random() < 0.01
if not counter_counter:
counter = random() < 0.05
choices = [user, ctx.author]
if random() < 0.5:
loser = 0
else:
loser = 1
await msg.edit(content=f'{user} vs {ctx.author}\nLoser: {choices[loser]}')
perms = ctx.channel.permissions_for(ctx.guild.me)
if counter:
p = os.path.join(DATA, 'templates', 'reverse.png')
await asyncio.sleep(2)
if perms.attach_files:
await ctx.send(f'{choices[loser]} counters', file=discord.File(p))
else:
await ctx.send(f'{choices[loser]} counters. (No image perms so text only counter)')
loser = abs(loser - 1)
await msg.edit(content=f'{user} vs {ctx.author}\nLoser: {choices[loser]}')
if counter_counter:
p = os.path.join(DATA, 'templates', 'counter_counter.png')
await asyncio.sleep(2)
if perms.attach_files:
await ctx.send(f'{choices[loser]} counters the counter', file=discord.File(p))
else:
await ctx.send(f'{choices[loser]} counters the counter. (No image perms so text only counter)')
loser = abs(loser - 1)
await msg.edit(content=f'{user} vs {ctx.author}\nLoser: {choices[loser]}')
loser = choices[loser]
await asyncio.sleep(3)
if mute_role in user.roles or mute_role in ctx.author.roles:
return await ctx.send('One of the participants is already muted')
choices.remove(loser)
await self.add_timeout(ctx, ctx.guild.id, loser.id, expires_on, td.total_seconds(),
reason=f'Lost mute roll to {choices[0]}')
try:
await loser.add_roles(mute_role, reason=f'Lost mute roll to {ctx.author}')
except discord.DiscordException:
return await ctx.send('Failed to mute loser')
await self.bot.dbutil.increment_mute_roll(ctx.guild.id, ctx.author.id, loser != ctx.author)
await self.bot.dbutil.increment_mute_roll(ctx.guild.id, user.id, loser != user)
finally:
state.discard(user.id)
state.discard(ctx.author.id)
async def remove_timeout(self, user_id, guild_id):
try:
sql = 'DELETE FROM `timeouts` WHERE `guild`=:guild AND `user`=:user'
await self.bot.dbutil.execute(sql, params={'guild': guild_id, 'user': user_id}, commit=True)
except SQLAlchemyError:
logger.exception('Could not delete untimeout')
async def add_timeout(self, ctx, guild_id, user_id, expires_on, as_seconds,
reason='No reason'):
try:
await self.bot.dbutil.add_timeout(guild_id, user_id, expires_on, reason)
except SQLAlchemyError:
logger.exception('Could not save timeout')
await ctx.send('Could not save timeout. Canceling action')
return False
if guild_id not in self.timeouts:
guild_timeouts = {}
self.timeouts[guild_id] = guild_timeouts
else:
guild_timeouts = self.timeouts.get(guild_id)
t = guild_timeouts.get(user_id)
if t:
t.cancel()
task = call_later(self.untimeout, self.bot.loop,
as_seconds, user_id, guild_id,
after=lambda f: guild_timeouts.pop(user_id, None))
guild_timeouts[user_id] = task
return True
async def untimeout(self, user_id, guild_id):
mute_role = self.bot.guild_cache.mute_role(guild_id)
if mute_role is None:
return
guild = self.bot.get_guild(guild_id)
if guild is None:
await self.remove_timeout(user_id, guild_id)
return
user = guild.get_member(user_id)
if not user:
await self.remove_timeout(user_id, guild_id)
return
if guild.get_role(mute_role):
try:
await user.remove_roles(Snowflake(mute_role), reason='Unmuted')
except discord.HTTPException:
logger.exception('Could not autounmute user %s' % user.id)
await self.remove_timeout(user.id, guild.id)
@command(no_pm=True)
@bot_has_permissions(manage_channels=True)
@has_permissions(manage_channels=True)
async def slowmode(self, ctx, time: int):
try:
await ctx.channel.edit(slowmode_delay=time)
except discord.HTTPException as e:
await ctx.send('Failed to set slowmode because of an error\n%s' % e)
except:
logger.exception('Failed to set slowmode')
await ctx.send('Failed to set slowmode because of an unknown error')
else:
await ctx.send('Slowmode set to %ss' % time)
@command(aliases=['temp_mute'], no_pm=True)
@bot_has_permissions(manage_roles=True)
@has_permissions(manage_roles=True)
async def timeout(self, ctx, user: MentionedMember, *, timeout):
"""Mute user for a specified amount of time
`timeout` is the duration of the mute.
The format is `n d|days` `n h|hours` `n m|min|minutes` `n s|sec|seconds` `reason`
where at least one of them must be provided.
Maximum length for a timeout is 30 days
e.g. `{prefix}{name} <@!12345678> 10d 10h 10m 10s This is the reason for the timeout`
"""
mute_role = await self._mute_check(ctx)
if not mute_role:
return
time, reason = parse_timeout(timeout)
guild = ctx.guild
if not time:
return await ctx.send('Invalid time string')
if user.id == ctx.author.id and time.total_seconds() < 21600:
return await ctx.send('If you gonna timeout yourself at least make it a longer timeout')
if guild.id == 217677285442977792 and user.id == 123050803752730624:
return await ctx.send("Not today kiddo. I'm too powerful for you")
r = guild.get_role(339841138393612288)
if not ctx.author.id == 1<PASSWORD>2730624 and self.bot.anti_abuse_switch and r in user.roles and r in ctx.author.roles:
return await ctx.send('All hail our leader <@!222399701390065674>')
abusers = (189458911886049281, 117699419951988737)
if user.id in abusers and ctx.author.id in abusers:
return await ctx.send("Abuse this 🖕")
if ctx.author.id in abusers and mute_role in ctx.author.roles:
return await ctx.send("Abuse this 🖕")
if guild.id == 217677285442977792 and ctx.author.id == <PASSWORD> and user.id == 189458911886049281:
return await ctx.send('No <:peepoWeird:423445885180051467>')
if ctx.author != guild.owner and ctx.author.top_role <= user.top_role:
return await ctx.send('The one you are trying to timeout is higher or same as you in the role hierarchy')
if time.days > 30:
return await ctx.send("Timeout can't be longer than 30 days")
if guild.id == 217677285442977792 and time.total_seconds() < 500:
return await ctx.send('This server is retarded so I have to hardcode timeout limits and the given time is too small')
if time.total_seconds() < 59:
return await ctx.send('Minimum timeout is 1 minute')
now = datetime.utcnow()
if guild.id == 217677285442977792:
words = ('game', 'phil', 'ligma', 'christianserver', 'sugondese', 'deeznuts', 'haha', 'mute', 'lost')
rs = '' if not reason else reason.lower().replace(' ', '')
gay = not reason or any([word in rs for word in words])
if ctx.author.id in abusers and gay:
if mute_role not in ctx.author.roles:
very_gay = timedelta(seconds=time.total_seconds()*2)
await ctx.send('Abuse this <:christianServer:336568327939948546>')
await ctx.author.add_roles(mute_role, reason='Abuse this')
await self.add_timeout(ctx, guild.id, ctx.author.id, datetime2sql(now + very_gay), very_gay.total_seconds(),
reason='Abuse this <:christianServer:336568327939948546>')
reason = reason if reason else 'No reason <:HYPERKINGCRIMSONANGRY:356798314752245762>'
expires_on = datetime2sql(now + time)
await self.add_timeout(ctx, guild.id, user.id, expires_on, time.total_seconds(),
reason=reason)
try:
await user.add_roles(mute_role, reason=f'[{ctx.author}] {reason}')
if guild.id == 217677285442977792:
try:
sql = 'INSERT INTO `timeout_logs` (`guild`, `user`, `time`, `reason`) VALUES ' \
'(:guild, :user, :time, :reason)'
d = {'guild': guild.id, 'user': ctx.author.id,
'time': time.total_seconds(), 'reason': reason}
await self.bot.dbutils.execute(sql, params=d, commit=True)
except SQLAlchemyError:
logger.exception('Fail to log timeout')
await ctx.send('Muted user {} for {}'.format(user, time))
chn = self.get_modlog(guild)
if chn:
author = ctx.message.author
description = '{} muted {} `{}` for {}'.format(author.mention,
user, user.id, time)
url = f'https://discordapp.com/channels/{guild.id}/{ctx.channel.id}/{ctx.message.id}'
embed = discord.Embed(title='🕓 Moderation action [TIMEOUT]',
timestamp=datetime.utcnow() + time,
description=description)
embed.add_field(name='Reason', value=reason)
embed.add_field(name='link', value=url)
embed.set_thumbnail(url=user.avatar_url or user.default_avatar_url)
embed.set_footer(text='Expires at', icon_url=author.avatar_url or author.default_avatar_url)
await self.send_to_modlog(guild, embed=embed)
except discord.HTTPException:
await ctx.send('Could not mute user {}'.format(user))
@group(invoke_without_command=True, no_pm=True)
@bot_has_permissions(manage_roles=True)
@has_permissions(manage_roles=True)
async def unmute(self, ctx, user: MentionedMember):
"""Unmute a user"""
guild = ctx.guild
mute_role = self.bot.guild_cache.mute_role(guild.id)
if mute_role is None:
return await ctx.send(f'No mute role set. You can set it with {ctx.prefix}settings mute_role role name')
if guild.id == 217677285442977792 and user.id == 123050803752730624:
return await ctx.send("Not today kiddo. I'm too powerful for you")
mute_role = guild.get_role(mute_role)
if mute_role is None:
return await ctx.send('Could not find the muted role')
try:
await user.remove_roles(mute_role, reason=f'Responsible user {ctx.author}')
except discord.HTTPException:
await ctx.send('Could not unmute user {}'.format(user))
else:
await ctx.send('Unmuted user {}'.format(user))
t = self.timeouts.get(guild.id, {}).get(user.id)
if t:
t.cancel()
async def _unmute_when(self, ctx, user, embed=True):
guild = ctx.guild
if user:
member = find_user(' '.join(user), guild.members, case_sensitive=True, ctx=ctx)
else:
member = ctx.author
if not member:
return await ctx.send('User %s not found' % ' '.join(user))
muted_role = self.bot.guild_cache.mute_role(guild.id)
if not muted_role:
return await ctx.send(f'No mute role set on this server. You can set it with {ctx.prefix}settings mute_role role name')
if not list(filter(lambda r: r.id == muted_role, member.roles)):
return await ctx.send('%s is not muted' % member)
sql = 'SELECT expires_on, reason FROM `timeouts` WHERE guild=%s AND user=%s' % (guild.id, member.id)
try:
row = (await self.bot.dbutil.execute(sql)).first()
except SQLAlchemyError:
return await ctx.send('Failed to check mute status')
if not row:
return await ctx.send('User %s is permamuted' % str(member))
delta = row['expires_on'] - datetime.utcnow()
reason = row['reason']
s = 'Timeout for %s expires in %s\n' % (member, seconds2str(delta.total_seconds(), False))
reason_s = 'Timeout reason: %s' % reason
if embed:
embed = discord.Embed(title='Unmute when', description=s, timestamp=row['expires_on'])
embed.add_field(name='Reason', value=reason_s)
embed.set_footer(text='Expires at')
await ctx.send(embed=embed)
else:
await ctx.send(s)
@unmute.command(no_pm=True)
@cooldown(1, 3, BucketType.user)
async def when(self, ctx, *user):
"""Shows how long you are still muted for"""
await self._unmute_when(ctx, user, embed=check_botperm('embed_links', ctx=ctx))
@command(no_pm=True)
@cooldown(1, 3, BucketType.user)
async def unmute_when(self, ctx, *user):
"""Shows how long you are still muted for"""
await self._unmute_when(ctx, user, embed=check_botperm('embed_links', ctx=ctx))
# Only use this inside commands
@staticmethod
async def _set_channel_lock(ctx, locked: bool, zawarudo=False):
channel = ctx.channel
everyone = ctx.guild.default_role
overwrite = channel.overwrites_for(everyone)
overwrite.send_messages = False if locked else None
try:
await channel.set_permissions(everyone, overwrite=overwrite, reason=f'Responsible user {ctx.author}')
except discord.HTTPException as e:
return await ctx.send('Failed to lock channel because of an error: %s. '
'Bot might lack the permissions to do so' % e)
try:
if locked:
if not zawarudo:
await ctx.send('Locked channel %s' % channel.name)
else:
await ctx.send(f'Time has stopped in {channel.mention}')
else:
if not zawarudo:
await ctx.send('Unlocked channel %s' % channel.name)
else:
await ctx.send('Soshite toki wo ugokidasu')
except discord.HTTPException:
pass
@staticmethod
def purge_embed(ctx, messages, users: set=None, multiple_channels=False):
author = ctx.author
if not multiple_channels:
d = '%s removed %s messages in %s' % (author.mention, len(messages), ctx.channel.mention)
else:
d = '%s removed %s messages' % (author.mention, len(messages))
if users is None:
users = set()
for m in messages:
if isinstance(m, discord.Message):
users.add(m.author.mention)
elif isinstance(m, dict):
try:
users.add('<@!{}>'.format(m['user_id']))
except KeyError:
pass
value = ''
last_index = len(users) - 1
for idx, u in enumerate(list(users)):
if idx == 0:
value += u
continue
if idx == last_index:
user = ' and ' + u
else:
user = ', ' + u
if len(user) + len(value) > 1000:
value += 'and %s more users' % len(users)
break
else:
value += user
users.remove(u)
embed = discord.Embed(title='🗑 Moderation action [PURGE]', timestamp=datetime.utcnow(), description=d)
embed.add_field(name='Deleted messages from', value=value)
embed.set_thumbnail(url=get_avatar(author))
embed.set_footer(text=str(author), icon_url=get_avatar(author))
return embed
@group(invoke_without_command=True, no_pm=True)
@cooldown(2, 4, BucketType.guild)
@bot_has_permissions(manage_messages=True)
@has_permissions(manage_messages=True)
async def purge(self, ctx, max_messages: int=10):
"""Purges n amount of messages from a channel.
maximum value of max_messages is 500 and the default is 10"""
channel = ctx.channel
if max_messages > 1000000:
return await ctx.send("Either you tried to delete over 1 million messages or just put it there as an accident. "
"Either way that's way too much for me to handle")
max_messages = min(500, max_messages)
# purge doesn't support reasons yet
messages = await channel.purge(limit=max_messages) # , reason=f'{ctx.author} purged messages')
modlog = self.get_modlog(channel.guild)
if not modlog:
return
embed = self.purge_embed(ctx, messages)
await self.send_to_modlog(channel.guild, embed=embed)
@purge.command(name='from', no_pm=True, ignore_extra=True)
@cooldown(2, 4, BucketType.guild)
@bot_has_permissions(manage_messages=True)
@has_permissions(manage_messages=True)
async def from_(self, ctx, user: PossibleUser, max_messages: int=10, channel: discord.TextChannel=None):
"""
Delete messages from a user
`user` The user mention or id of the user we want to purge messages from
[OPTIONAL]
`max_messages` Maximum amount of messages that can be deleted. Defaults to 10 and max value is 300.
`channel` Channel if or mention where you want the messages to be purged from. If not set will delete messages from any channel the bot has access to.
"""
guild = ctx.guild
# We have checked the members channel perms but we need to be sure the
# perms are global when no channel is specified
if channel is None and not ctx.author.guild_permissions.manage_messages and not ctx.override_perms:
return await ctx.send("You don't have the permission to purge from all channels")
max_messages = min(300, max_messages)
modlog = self.get_modlog(guild)
if isinstance(user, discord.User):
user = user.id
if channel is not None:
messages = await channel.purge(limit=max_messages, check=lambda m: m.author.id == user)
if modlog and messages:
embed = self.purge_embed(ctx, messages, users={'<@!%s>' % user})
await self.send_to_modlog(guild, embed=embed)
return
t = datetime.utcnow() - timedelta(days=14)
t = datetime2sql(t)
sql = 'SELECT `message_id`, `channel` FROM `messages` WHERE guild=%s AND user_id=%s AND DATE(`time`) > "%s" ' % (guild.id, user, t)
if channel is not None:
sql += 'AND channel=%s ' % channel.id
sql += 'ORDER BY `message_id` DESC LIMIT %s' % max_messages
rows = (await self.bot.dbutil.execute(sql)).fetchall()
channel_messages = {}
for r in rows:
if r['channel'] not in channel_messages:
message_ids = []
channel_messages[r['channel']] = message_ids
else:
message_ids = channel_messages[r['channel']]
message_ids.append(Snowflake(r['message_id']))
ids = []
bot_member = guild.get_member(self.bot.user.id)
for k in channel_messages:
channel = self.bot.get_channel(k)
if not (channel and channel.permissions_for(bot_member).manage_messages):
continue
try:
await self.delete_messages(channel, channel_messages[k])
except discord.HTTPException:
logger.exception('Could not delete messages')
else:
ids.extend(channel_messages[k])
if ids:
sql = 'DELETE FROM `messages` WHERE `message_id` IN (%s)' % ', '.join([str(i.id) for i in ids])
try:
await self.bot.dbutil.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Could not delete messages from database')
if modlog:
embed = self.purge_embed(ctx, ids, users={'<@!%s>' % user}, multiple_channels=len(channel_messages.keys()) > 1)
await self.send_to_modlog(guild, embed=embed)
@purge.command(name='until', no_pm=True, ignore_extra=True)
@cooldown(2, 4, BucketType.guild)
@bot_has_permissions(manage_messages=True)
@has_permissions(manage_messages=True)
async def purge_until(self, ctx, message_id: int, limit: int=100):
"""Purges messages until the specified message is reached or the limit is exceeded
limit the max limit is 500 is the specified message is under 2 weeks old
otherwise the limit is 100"""
channel = ctx.channel
try:
message = await channel.get_message(message_id)
except discord.NotFound:
return await ctx.send(f'Message {message_id} not found in this channel')
days = (datetime.utcnow() - message.created_at).days
max_limit = 100 if days >= 14 else 500
if limit >= max_limit:
return await ctx.send(f'Maximum limit is {max_limit}')
def check(msg):
if msg.id <= message_id:
return False
return True
try:
deleted = await channel.purge(limit=limit, check=check, before=ctx.message)
except discord.HTTPException as e:
await ctx.send(f'Failed to delete messages because of an error\n{e}')
else:
await ctx.send(f'Deleted {len(deleted)} messages')
@command(no_pm=True, ignore_extra=True, aliases=['softbab'])
@bot_has_permissions(ban_members=True)
@has_permissions(ban_members=True)
async def softban(self, ctx, user: PossibleUser, message_days: int=1):
"""Ban and unban a user from the server deleting that users messages from
n amount of days in the process"""
guild = ctx.guild
if not (1 <= message_days <= 7):
return await ctx.send('Message days must be between 1 and 7')
user_name = str(user)
if isinstance(user, discord.User):
user = user.id
user_name += f' `{user}`'
try:
await guild.ban(Snowflake(user), reason=f'{ctx.author} softbanned', delete_message_days=message_days)
except discord.Forbidden:
return await ctx.send("The bot doesn't have ban perms")
except discord.HTTPException:
return await ctx.send('Something went wrong while trying to ban. Try again')
try:
await guild.unban(Snowflake(user), reason=f'{ctx.author} softbanned')
except discord.HTTPException:
return await ctx.send('Failed to unban after ban')
s = f'Softbanned user {user_name}'
await ctx.send(s)
@command(ignore_extra=True, aliases=['zawarudo'], no_pm=True)
@cooldown(1, 5, BucketType.guild)
@bot_has_permissions(manage_channels=True, manage_roles=True)
@has_permissions(manage_channels=True, manage_roles=True)
async def lock(self, ctx):
"""Set send_messages permission override of everyone to false on current channel"""
await self._set_channel_lock(ctx, True, zawarudo=ctx.invoked_with == 'zawarudo')
@command(ignore_extra=True, aliases=['tokiwougokidasu'], no_pm=True)
@cooldown(1, 5, BucketType.guild)
@bot_has_permissions(manage_channels=True, manage_roles=True)
@has_permissions(manage_channels=True, manage_roles=True)
async def unlock(self, ctx):
"""Set send_messages permission override on current channel to default position"""
await self._set_channel_lock(ctx, False, zawarudo=ctx.invoked_with == 'tokiwougokidasu')
def get_temproles(self, guild: int):
temproles = self.temproles.get(guild, None)
if temproles is None:
temproles = {}
self.temproles[guild] = temproles
return temproles
async def remove_role(self, user, role, guild):
guild = self.bot.get_guild(guild)
if not guild:
await self.bot.dbutil.remove_temprole(user, role)
return
user = guild.get_member(user)
if not user:
await self.bot.dbutil.remove_temprole(user, role)
return
try:
await user.remove_roles(Snowflake(role), reason='Removed temprole')
except discord.HTTPException:
pass
await self.bot.dbutil.remove_temprole(user, role)
def register_temprole(self, user: int, role: int, guild: int, time):
temproles = self.get_temproles(guild)
old = temproles.get(user)
if old:
old.cancel()
if time <= 1:
time = 1
task = call_later(self.remove_role, self.bot.loop, time,
user, role, guild, after=lambda _: temproles.pop(user))
temproles[user] = task
@command(ignore_extra=True, no_pm=True)
@has_permissions(manage_roles=True)
@bot_has_permissions(manage_roles=True)
@cooldown(1, 5, BucketType.guild)
async def temprole(self, ctx, time: TimeDelta, user: discord.Member, *, role: discord.Role):
if time.days > 7:
return await ctx.send('Max days is 7')
total_seconds = time.total_seconds()
if total_seconds < 60:
return await ctx.send('Must be over minute')
bot = ctx.guild.me
if role > bot.top_role:
return await ctx.send('Role is higher than my top role')
if role > ctx.author.top_role:
return await ctx.send('Role is higher than your top role')
expires_at = datetime.utcnow() + time
self.register_temprole(user.id, role.id, user.guild.id, total_seconds)
expires_at = datetime2sql(expires_at)
await self.bot.dbutil.add_temprole(user.id, role.id, user.guild.id,
expires_at)
try:
await user.add_roles(role, reason=f'{ctx.author} temprole {seconds2str(total_seconds, long_def=False)}')
except discord.HTTPException as e:
await ctx.send('Failed to add role because of an error\n%s' % e)
return
except:
logger.exception('Failed to add role')
await ctx.send('Failed to add role. An exception has been logged')
return
await ctx.send(f'Added {role} to {user} for {seconds2str(total_seconds, long_def=False)}')
@command(no_pm=True)
@cooldown(1, 4, BucketType.user)
async def reason(self, ctx, message_id: int, *, reason):
modlog = self.get_modlog(ctx.guild)
if not modlog:
return await ctx.send('Modlog not found')
try:
msg = await modlog.get_message(message_id)
except discord.HTTPException as e:
return await ctx.send('Failed to get message\n%s' % e)
if msg.author.id != self.bot.user.id:
return await ctx.send('Modlog entry not by this bot')
if not msg.embeds:
return await ctx.send('Embed not found')
embed = msg.embeds[0]
if not embed.footer or str(ctx.author.id) not in embed.footer.icon_url:
return await ctx.send("You aren't responsible for this mod action")
idx = -1
for idx, field in enumerate(embed.fields):
if field.name == 'Reason':
break
if idx < 0:
return await ctx.send('No reason found')
embed.set_field_at(idx, name='Reason', value=reason)
await msg.edit(embed=embed)
user_id = re.findall(r'(\d+)', msg.embeds[0].description)
if user_id:
user_id = int(user_id[-1])
try:
await self.bot.dbutil.edit_timeout(ctx.guild.id, user_id, reason)
except SQLAlchemyError:
logger.exception('Failed to change modlog reason')
await ctx.send('Reason edited')
@staticmethod
async def delete_messages(channel, message_ids):
"""Delete messages in bulk and take the message limit into account"""
step = 100
for _ in range(0, len(message_ids), step):
await channel.delete_messages(message_ids)
def get_modlog(self, guild):
return guild.get_channel(self.bot.guild_cache.modlog(guild.id))
def setup(bot):
bot.add_cog(Moderator(bot))
<file_sep>import logging
import time
import discord
from discord.errors import InvalidArgument
from sqlalchemy.exc import SQLAlchemyError, DBAPIError
from bot.globals import BlacklistTypes
from utils.utilities import check_perms
logger = logging.getLogger('debug')
class DatabaseUtils:
def __init__(self, bot):
self._bot = bot
@property
def bot(self):
return self._bot
async def execute(self, sql, *args, commit=False, measure_time=False, **params):
"""
Asynchronously run an sql query using loop.run_in_executor
Args:
sql: sql query
*args: args passed to execute
commit: Should we commit after query
measure_time: Return time it took to run query as well as ResultProxy
**params: params passed to execute
Returns:
ResultProxy or ResultProxy, int depending of the value of measure time
"""
def _execute():
session = self.bot.get_session
try:
t = time.perf_counter()
row = session.execute(sql, *args, **params)
if commit:
session.commit()
if measure_time:
return row, time.perf_counter() - t
except DBAPIError as e:
if e.connection_invalidated:
logger.exception('CONNECTION INVALIDATED')
self.bot.engine.connect()
raise e
except SQLAlchemyError as e:
session.rollback()
raise e
return row
return await self.bot.loop.run_in_executor(self.bot.threadpool, _execute)
async def index_guild_member_roles(self, guild):
import time
t = time.time()
default_role = guild.default_role.id
async def execute(sql_, commit=True):
try:
await self.execute(sql_, commit=commit)
except SQLAlchemyError:
logger.exception('Failed to execute sql')
return False
return True
success = await self.index_guild_roles(guild)
if not success:
return success
logger.info('added roles in %s' % (time.time() - t))
t1 = time.time()
try:
await self.bot.request_offline_members(guild)
logger.info('added offline users in %s' % (time.time() - t1))
except InvalidArgument:
pass
_m = list(guild.members)
members = list(filter(lambda u: len(u.roles) > 1, _m))
all_members = [str(u.id) for u in _m]
t1 = time.time()
sql = 'DELETE `userRoles` FROM `userRoles` INNER JOIN `roles` ON roles.id=userRoles.role WHERE roles.guild={} AND userRoles.user IN ({})'.format(guild.id, ', '.join(all_members))
# Deletes all server records
# sql = 'DELETE `userRoles` FROM `userRoles` INNER JOIN `roles` WHERE roles.server=%s AND userRoles.role_id=roles.id'
if not await execute(sql):
return False
logger.info('Deleted old records in %s' % (time.time() - t1))
t1 = time.time()
sql = 'INSERT IGNORE INTO `userRoles` (`user`, `role`) VALUES '
for u in members:
for r in u.roles:
if r.id == default_role:
continue
sql += f' ({u.id}, {r.id}),'
sql = sql.rstrip(',')
if not await execute(sql):
return False
logger.info('added user roles in %s' % (time.time() - t1))
logger.info('indexed users in %s seconds' % (time.time() - t))
return True
async def index_guild_roles(self, guild):
roles = [{'id': r.id, 'guild': guild.id} for r in guild.roles]
role_ids = [str(r.id) for r in guild.roles]
sql = 'INSERT IGNORE INTO `roles` (`id`, `guild`) VALUES (:id, :guild)'
try:
await self.execute(sql, roles, commit=True)
sql = 'DELETE FROM `roles` WHERE guild={} AND NOT id IN ({})'.format(guild.id, ', '.join(role_ids))
await self.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to index guild roles')
return False
return True
async def add_guilds(self, *ids):
if not ids:
return
ids = [{'guild': i} for i in ids]
sql = 'INSERT IGNORE INTO `guilds` (`guild`) VALUES (:guild)'
try:
await self.execute(sql, ids, commit=True)
sql = 'INSERT IGNORE INTO `prefixes` (`guild`) VALUES (:guild)'
await self.execute(sql, ids, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add new servers to db')
return False
return True
async def add_roles(self, guild_id, *role_ids):
sql = 'INSERT IGNORE INTO `roles` (`id`, `guild`) VALUES '
l = len(role_ids) - 1
for idx, r in enumerate(role_ids):
sql += f'({r}, {guild_id})'
if idx != l:
sql += ', '
try:
await self.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add roles')
return False
return True
async def add_user(self, user_id):
sql = f'INSERT IGNORE INTO `users` (`id`) VALUES ({user_id})'
try:
self.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add user')
return False
return True
async def add_users(self, *user_ids):
sql = 'INSERT IGNORE INTO `users` (`id`) VALUES '
l = len(user_ids) - 1
for idx, uid in enumerate(user_ids):
sql += f'({uid})'
if idx != l:
sql += ', '
try:
await self.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add users')
return False
return True
async def add_user_roles(self, role_ids, user_id, guild_id):
if not await self.add_roles(guild_id, *role_ids):
return
sql = 'INSERT IGNORE INTO `userRoles` (`user`, `role`) VALUES '
l = len(role_ids) - 1
for idx, r in enumerate(role_ids):
sql += f'({user_id}, {r})'
if idx != l:
sql += ', '
try:
await self.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add roles foreign keys')
return False
return True
async def remove_user_roles(self, role_ids, user_id):
sql = 'DELETE FROM `userRoles` WHERE user=%s and role IN (%s)' % (user_id, ', '.join(map(lambda i: str(i), role_ids)))
try:
await self.execute(sql, commit=True)
return True
except SQLAlchemyError:
logger.exception('Failed to delete roles')
return False
async def add_prefix(self, guild_id, prefix):
sql = 'INSERT INTO `prefixes` (`guild`, `prefix`) VALUES (:guild, :prefix)'
try:
await self.execute(sql, params={'guild': guild_id, 'prefix': prefix}, commit=True)
return True
except SQLAlchemyError:
logger.exception('Failed to add prefix')
return False
async def remove_prefix(self, guild_id, prefix):
sql = 'DELETE FROM `prefixes` WHERE guild=:guild AND prefix=:prefix'
try:
await self.execute(sql, params={'guild': guild_id, 'prefix': prefix}, commit=True)
return True
except SQLAlchemyError:
logger.exception('Failed to remove prefix')
return False
async def delete_role(self, role_id, guild_id):
sql = f'DELETE FROM `roles` WHERE id={role_id} AND guild={guild_id}'
try:
await self.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception(f'Could not delete role {role_id}')
async def delete_user_roles(self, guild_id, user_id):
try:
sql = f'DELETE `userRoles` FROM `userRoles` INNER JOIN `roles` ON roles.id=userRoles.role WHERE roles.guild={guild_id} AND userRoles.user={user_id}'
await self.execute(sql, commit=True)
except SQLAlchemyError:
logger.exception('Could not delete user roles')
async def add_automute_blacklist(self, guild_id, *channel_ids):
sql = 'INSERT IGNORE INTO `automute_blacklist` (`guild`, `channel`) VALUES '
sql += ', '.join(map(lambda cid: f'({guild_id}, {cid})', channel_ids))
try:
await self.execute(sql, commit=True)
success = True
except SQLAlchemyError:
success = False
return success
async def remove_automute_blacklist(self, guild_id, *channel_ids):
if not channel_ids:
return True
channel_ids = ', '.join(map(str, channel_ids))
sql = f'DELETE FROM `automute_blacklist` WHERE guild={guild_id} AND channel IN ({channel_ids}) '
try:
await self.execute(sql, commit=True)
success = True
except SQLAlchemyError:
success = False
return success
async def add_automute_whitelist(self, guild_id, *role_ids):
if not role_ids:
return True
sql = 'INSERT IGNORE INTO `automute_whitelist` (`guild`, `role`) VALUES '
sql += ', '.join(map(lambda rid: f'({guild_id}, {rid})', role_ids))
try:
await self.execute(sql, commit=True)
success = True
except SQLAlchemyError:
success = False
return success
async def remove_automute_whitelist(self, guild_id, *role_ids):
if not role_ids:
return True
role_ids = ', '.join(map(str, role_ids))
sql = f'DELETE FROM `automute_whitelist` WHERE guild={guild_id} AND role IN ({role_ids})'
try:
await self.execute(sql, commit=True)
success = True
except SQLAlchemyError:
success = False
return success
async def multiple_last_seen(self, user_ids, usernames, guild_id, timestamps):
sql = 'INSERT INTO `last_seen_users` (`user`, `username`, `guild`, `last_seen`) VALUES (:user, :username, :guild, :time) ON DUPLICATE KEY UPDATE last_seen=VALUES(`last_seen`), username=VALUES(`username`)'
data = [{'user': uid, 'username': u, 'guild': s, 'time': t} for uid, u, s, t in zip(user_ids, usernames, guild_id, timestamps)]
try:
await self.execute(sql, data, commit=True)
except SQLAlchemyError:
logger.exception('Failed to set last seen')
return False
return True
async def add_command(self, parent, name=""):
sql = 'INSERT IGNORE INTO `command_stats` (`parent`, `cmd`) VALUES (:parent, :cmd)'
try:
await self.execute(sql, params={'parent': parent, 'cmd': name}, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add command {} {}'.format(parent, name))
return False
return True
async def add_commands(self, values):
"""
Inserts multiple commands to the db
Args:
values: A list of dictionaries with keys `parent` and `cmd`
Returns:
bool based on success
"""
if not values:
return
sql = 'INSERT IGNORE INTO `command_stats` (`parent`, `cmd`) VALUES (:parent, :cmd)'
try:
await self.execute(sql, values, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add commands {}'.format(values))
return False
return True
async def command_used(self, parent, name=""):
if name is None:
name = ""
sql = 'UPDATE `command_stats` SET `uses`=(`uses`+1) WHERE parent=:parent AND cmd=:cmd'
try:
await self.execute(sql, params={'parent': parent, 'cmd': name}, commit=True)
except SQLAlchemyError:
logger.exception('Failed to update command {} {} usage'.format(parent, name))
return False
return True
async def get_command_stats(self, parent=None, name=""):
sql = 'SELECT * FROM command_stats'
if parent:
sql += ' WHERE parent=:parent AND cmd=:name'
sql += ' ORDER BY uses DESC'
try:
return (await self.execute(sql, params={'parent': parent, 'name': name})).fetchall()
except SQLAlchemyError:
logger.exception('Failed to get command stats')
return False
async def increment_mute_roll(self, guild: int, user: int, win: bool):
if win:
sql = 'INSERT INTO `mute_roll_stats` (`guild`, `user`, `wins`, `current_streak`, `biggest_streak`) VALUES (:guild, :user, 1, 1, 1)'
sql += ' ON DUPLICATE KEY UPDATE wins=wins + 1, games=games + 1, current_streak=current_streak + 1, biggest_streak=GREATEST(current_streak, biggest_streak)'
else:
sql = 'INSERT INTO `mute_roll_stats` (`guild`, `user`) VALUES (:guild, :user)'
sql += ' ON DUPLICATE KEY UPDATE games=games+1, current_streak=0'
try:
await self.execute(sql, {'guild': guild, 'user': user}, commit=True)
except SQLAlchemyError:
logger.exception('Failed to update mute roll stats')
return False
return True
async def get_mute_roll(self, guild: int, sort=None):
if sort is None:
# Algorithm based on https://stackoverflow.com/a/27710046
# Gives priority to games played then wins and then winrate
sort = '1/SQRT(POW(wins/games-1, 2)*0.7 + POW(1/games, 2)*3 + POW(1/wins, 2)*2)'
sql = 'SELECT * FROM `mute_roll_stats` WHERE guild=%s ORDER BY %s DESC' % (guild, sort)
rows = (await self.execute(sql)).fetchall()
return rows
async def botban(self, user_id, reason):
sql = 'INSERT INTO `banned_users` (`user`, `reason`) VALUES (:user, :reason)'
await self.execute(sql, {'user': user_id, 'reason': reason}, commit=True)
async def botunban(self, user_id):
sql = 'DELETE FROM `banned_users` WHERE user=%s' % user_id
await self.execute(sql, commit=True)
async def blacklist_guild(self, guild_id, reason):
sql = 'INSERT INTO `guild_blacklist` (`guild`, `reason`) VALUES (:guild, :reason)'
await self.execute(sql, {'guild': guild_id, 'reason': reason}, commit=True)
async def unblacklist_guild(self, guild_id):
sql = 'DELETE FROM `guild_blacklist` WHERE guild=%s' % guild_id
await self.execute(sql, commit=True)
async def is_guild_blacklisted(self, guild_id):
sql = 'SELECT 1 FROM `guild_blacklist` WHERE guild=%s' % guild_id
r = await self.execute(sql)
r = r.first()
return r is not None and r[0] == 1
async def add_multiple_activities(self, data):
"""
data is a list of dicts with each dict containing user, game and time
"""
sql = 'INSERT INTO `activity_log` (`user`, `game`, `time`) VALUES (:user, :game, :time) ON DUPLICATE KEY UPDATE time=VALUES(`time`)'
try:
await self.execute(sql, data, commit=True)
except SQLAlchemyError:
logger.exception('Failed to log activities')
return False
return True
async def get_activities(self, user):
sql = 'SELECT * FROM `activity_log` WHERE user=:user ORDER BY time DESC LIMIT 5'
try:
rows = await self.execute(sql, {'user': user})
rows = rows.fetchall()
except SQLAlchemyError:
logger.exception('Failed to log activities')
return False
return rows
async def delete_activities(self, user):
sql = 'DELETE FROM `activity_log` WHERE user=:user'
try:
await self.execute(sql, {'user': user}, commit=True)
except SQLAlchemyError:
logger.exception('Failed to log activities')
return False
return True
async def log_pokespawn(self, name, guild):
sql = 'INSERT INTO `pokespawns` (`name`, `guild`) VALUES (:name, :guild) ON DUPLICATE KEY UPDATE count=count+1'
try:
await self.execute(sql, {'name': name, 'guild': guild}, commit=True)
except SQLAlchemyError:
logger.exception('Failed to log pokespawn')
return False
return True
async def add_timeout(self, guild, user, expires_on, reason):
sql = 'INSERT INTO `timeouts` (`guild`, `user`, `expires_on`, `reason`) VALUES ' \
'(:guild, :user, :expires_on, :reason) ON DUPLICATE KEY UPDATE expires_on=VALUES(expires_on), reason=VALUES(reason)'
params = {'guild': guild, 'user': user, 'expires_on': expires_on, 'reason': reason}
await self.execute(sql, params=params, commit=True)
async def edit_timeout(self, guild, user, reason):
sql = 'UPDATE `timeouts` SET reason=:reason WHERE guild=:guild AND user=:user'
params = {'reason': reason, 'guild': guild, 'user': user}
await self.execute(sql, params=params, commit=True)
async def add_todo(self, todo, priority=0):
sql = 'INSERT INTO `todo` (`todo`, `priority`) VALUES (:todo, :priority)'
rowid = (await self.execute(sql, {'todo': todo, 'priority': priority}, commit=True)).lastrowid
return rowid
async def get_todo(self, limit):
sql = 'SELECT * FROM `todo` WHERE `completed` IS FALSE ORDER BY priority DESC LIMIT %s' % limit
return await self.execute(sql)
async def add_temprole(self, user, role, guild, expires_at):
sql = 'INSERT INTO `temproles` (`user`, `role`, `guild`, `expires_at`) VALUES ' \
'(:user, :role, :guild, :expires_at) ON DUPLICATE KEY UPDATE expires_at=:expires_at'
try:
await self.execute(sql, {'user': user, 'role': role,
'guild': guild, 'expires_at': expires_at})
except SQLAlchemyError:
logger.exception('Failed to add temprole')
async def remove_temprole(self, user: int, role: int):
sql = 'DELETE FROM `temproles` WHERE user=:user AND role=:role'
try:
await self.execute(sql, {'user': user, 'role': role})
except SQLAlchemyError:
logger.exception('Failed to remove temprole')
async def add_changes(self, changes):
sql = 'INSERT INTO `changelog` (`changes`) VALUES (:changes)'
rowid = (await self.execute(sql, {'changes': changes}, commit=True)).lastrowid
return rowid
async def check_blacklist(self, command, user, ctx, fetch_raw: bool=False):
"""
Args:
command: Name of the command
user: member/user object
ctx: The context
fetch_raw: if True the value of the active permission override is returned
if False will return a bool when the users permissions will be overridden
or None when no entries were found
Returns: int, bool, None
See fetch_raw to see possible return values
"""
sql = 'SELECT * FROM `command_blacklist` WHERE type=%s AND %s ' \
'AND (user=%s OR user IS NULL) LIMIT 1' % (BlacklistTypes.GLOBAL, command, user.id)
rows = await self.execute(sql)
if rows.first():
return False
if ctx.guild is None:
return True
channel = ctx.channel
if isinstance(user, discord.Member) and user.roles:
roles = '(role IS NULL OR role IN ({}))'.format(', '.join(map(lambda r: str(r.id), user.roles)))
else:
roles = 'role IS NULL'
sql = f'SELECT `type`, `role`, `user`, `channel` FROM `command_blacklist` WHERE guild={user.guild.id} AND {command} ' \
f'AND (user IS NULL OR user={user.id}) AND {roles} AND (channel IS NULL OR channel={channel.id})'
rows = (await self.execute(sql)).fetchall()
if not rows:
return None
"""
Here are the returns
1 user AND whitelist
3 user AND blacklist
4 whitelist AND role
6 blacklist AND role
8 channel AND whitelist
10 channel AND blacklist
16 whitelist AND server
18 blacklist AND server
"""
return check_perms(rows, return_raw=fetch_raw)
<file_sep>"""
MIT License
Copyright (c) 2017 s0hvaperuna
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.
"""
import logging
from collections import deque
from aiohttp import ClientSession
from discord.ext.commands import cooldown
from bot.bot import command
from utils.utilities import send_paged_message
logger = logging.getLogger('debug')
class SearchItem:
def __init__(self, **kwargs):
self.url = kwargs.pop('link', 'None')
self.title = kwargs.pop('title', 'Untitled')
def __str__(self):
return '{0.url}'.format(self)
class Search:
def __init__(self, bot, client: ClientSession):
self.bot = bot
self.client = client
self.last_search = deque()
self.key = bot.config.google_api_key
self.cx = self.bot.config.custom_search
@command(aliases=['im', 'img'])
@cooldown(2, 5)
async def image(self, ctx, *, query):
"""Google search an image"""
#logger.debug('Image search query: {}'.format(query))
return await self._search(ctx, query, True, safe='off' if ctx.channel.nsfw else 'high')
@command()
@cooldown(2, 5)
async def google(self, ctx, *, query):
#logger.debug('Web search query: {}'.format(query))
return await self._search(ctx, query, safe='off' if ctx.channel.nsfw else 'medium')
async def _search(self, ctx, query, image=False, safe='off'):
params = {'key': self.key,
'cx': self.cx,
'q': query,
'safe': safe}
if image:
params['searchType'] = 'image'
async with self.client.get('https://www.googleapis.com/customsearch/v1', params=params) as r:
if r.status == 200:
json = await r.json()
if 'error' in json:
reason = json['error'].get('message', 'Unknown reason')
return await ctx.send('Failed to search because of an error\n```{}```'.format(reason))
#logger.debug('Search result: {}'.format(json))
total_results = json['searchInformation']['totalResults']
if int(total_results) == 0:
return await ctx.send('No results with the keywords "{}"'.format(query))
if 'items' in json:
items = []
for item in json['items']:
items.append(SearchItem(**item))
return await send_paged_message(ctx, items,
page_method=lambda p,
i: str(
p))
else:
return await ctx.send('Http error {}'.format(r.status))
def setup(bot):
bot.add_cog(Search(bot, bot.aiohttp_client))
<file_sep>import inspect
import logging
import os
import shlex
import subprocess
import sys
import textwrap
import time
from datetime import datetime
from email.utils import formatdate as format_rfc2822
from io import StringIO
from urllib.parse import quote
import discord
import psutil
from discord.ext.commands import (BucketType, bot_has_permissions, Group,
clean_content)
from discord.ext.commands.errors import BadArgument
from bot.converters import FuzzyRole
try:
from pip.commands import SearchCommand
except ImportError:
try:
from pip._internal.commands.search import SearchCommand
except (ImportError, TypeError):
SearchCommand = None
from sqlalchemy.exc import SQLAlchemyError
from bot.bot import command, cooldown
from cogs.cog import Cog
from utils.unzalgo import unzalgo, is_zalgo
from utils.utilities import (random_color, get_avatar, split_string,
get_emote_url,
send_paged_message)
logger = logging.getLogger('debug')
terminal = logging.getLogger('terminal')
class Utilities(Cog):
def __init__(self, bot):
super().__init__(bot)
@command(ignore_extra=True)
@cooldown(1, 10, BucketType.guild)
async def changelog(self, ctx, page: int=1):
sql = 'SELECT * FROM changelog ORDER BY `time` DESC'
rows = list(await self.bot.dbutil.execute(sql))
def create_embed(row):
embed = discord.Embed(title='Changelog', description=row['changes'],
timestamp=row['time'])
return embed
def get_page(page, idx):
if not isinstance(page, discord.Embed):
page = create_embed(page)
page.set_footer(text=f'Page {idx+1}/{len(rows)}')
rows[idx] = page
return page
if page > 0:
page -= 1
elif page == 0:
page = 1
await send_paged_message(ctx, rows, True, page, get_page)
@command(ignore_extra=True, aliases=['pong'])
@cooldown(1, 5, BucketType.guild)
async def ping(self, ctx):
"""Ping pong"""
t = time.perf_counter()
if ctx.received_at:
local_delay = t - ctx.received_at
else:
local_delay = datetime.utcnow().timestamp() - ctx.message.created_at.timestamp()
await ctx.trigger_typing()
t = time.perf_counter() - t
message = 'Pong!\n🏓 took {:.0f}ms\nLocal delay {:.0f}ms\nWebsocket ping {:.0f}ms'.format(t*1000, local_delay*1000, self.bot.latency*1000)
if hasattr(self.bot, 'get_session'):
sql_t = time.time()
try:
self.bot.get_session.execute('SELECT 1').fetchall()
sql_t = time.time() - sql_t
message += '\nDatabase ping {:.0f}ms'.format(sql_t * 1000)
except SQLAlchemyError:
message += '\nDatabase could not be reached'
await ctx.send(message)
@command(aliases=['e', 'emoji'])
@cooldown(1, 5, BucketType.channel)
async def emote(self, ctx, emote: str):
"""Get the link to an emote"""
emote = get_emote_url(emote)
if emote is None:
return await ctx.send('You need to specify an emote. Default (unicode) emotes are not supported ~~yet~~')
await ctx.send(emote)
@command(aliases=['roleping'])
@cooldown(1, 4, BucketType.channel)
async def how2role(self, ctx, *, role: FuzzyRole):
"""Searches a role and tells you how to ping it"""
name = role.name.replace('@', '@\u200b')
await ctx.send(f'`{role.mention}` {name}')
@command(aliases=['howtoping'])
@cooldown(1, 4, BucketType.channel)
async def how2ping(self, ctx, *, user):
"""Searches a user by their name and get the string you can use to ping them"""
if ctx.guild:
members = ctx.guild.members
else:
members = self.bot.get_all_members()
def filter_users(predicate):
for member in members:
if predicate(member):
return member
if member.nick and predicate(member.nick):
return member
if ctx.message.raw_role_mentions:
i = len(ctx.invoked_with) + len(ctx.prefix) + 1
user = ctx.message.clean_content[i:]
user = user[user.find('@')+1:]
found = filter_users(lambda u: str(u).startswith(user))
s = '`<@!{}>` {}'
if found:
return await ctx.send(s.format(found.id, str(found)))
found = filter_users(lambda u: user in str(u))
if found:
return await ctx.send(s.format(found.id, str(found)))
else:
return await ctx.send('No users found with %s' % user)
@command(aliases=['src', 'source_code', 'sauce'])
@cooldown(1, 5, BucketType.user)
async def source(self, ctx, *cmd):
"""Link to the source code for this bot
You can also get the source code of commands by doing {prefix}{name} cmd_name"""
if cmd:
full_name = ' '.join(cmd)
cmnd = self.bot.all_commands.get(cmd[0])
if cmnd is None:
raise BadArgument(f'Command "{full_name}" not found')
for c in cmd[1:]:
if not isinstance(cmnd, Group):
raise BadArgument(f'Command "{full_name}" not found')
cmnd = cmnd.get_command(c)
cmd = cmnd
if not cmd:
await ctx.send('You can find the source code for this bot here https://github.com/s0hv/Not-a-bot')
return
source = inspect.getsource(cmd.callback)
original_source = textwrap.dedent(source)
source = original_source.replace('```', '`\u200b`\u200b`') # Put zero width space between backticks so they can be within a codeblock
source = f'```py\n{source}\n```'
if len(source) > 2000:
file = discord.File(StringIO(original_source), filename=f'{full_name}.py')
await ctx.send(f'Content was longer than 2000 ({len(source)} > 2000)', file=file)
return
await ctx.send(source)
@command(ignore_extra=True)
@cooldown(1, 10, BucketType.user)
async def invite(self, ctx):
"""This bots invite link"""
await ctx.send(f'https://discordapp.com/api/oauth2/authorize?client_id={self.bot.user.id}&permissions=1342557248&scope=bot')
@staticmethod
def _unpad_zero(value):
if not isinstance(value, str):
return
return value.lstrip('0')
@command(ignore_extra=True, aliases=['bot', 'botinfo'])
@cooldown(2, 5, BucketType.user)
@bot_has_permissions(embed_links=True)
async def stats(self, ctx):
"""Get stats about this bot"""
pid = os.getpid()
process = psutil.Process(pid)
uptime = time.time() - process.create_time()
d = datetime.utcfromtimestamp(uptime)
uptime = f'{d.day-1}d {d.hour}h {d.minute}m {d.second}s'
current_memory = round(process.memory_info().rss / 1048576, 2)
memory_usage = f' Current: {current_memory}MB'
if sys.platform == 'linux':
try:
# use pmap to find the memory usage of this process and turn it to megabytes
# Since shlex doesn't care about pipes | I have to do this
s1 = subprocess.Popen(shlex.split('pmap %s' % os.getpid()),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
s2 = subprocess.Popen(
shlex.split('grep -Po "total +\K([0-9])+(?=K)"'),
stdin=s1.stdout, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
s1.stdin.close()
memory = round(int(s2.communicate()[0].decode('utf-8')) / 1024, 1)
usable_memory = str(memory) + 'MB'
memory_usage = f'{current_memory}MB/{usable_memory} ({(current_memory/memory*100):.1f}%)'
except:
logger.exception('Failed to get extended mem usage')
users = 0
for _ in self.bot.get_all_members():
users += 1
guilds = len(self.bot.guilds)
try:
# Get the last time the bot was updated
last_updated = format_rfc2822(os.stat('.git/refs/heads/master').st_mtime, localtime=True)
except OSError:
logger.exception('Failed to get last updated')
last_updated = 'N/A'
sql = 'SELECT * FROM `command_stats` ORDER BY `uses` DESC LIMIT 3'
try:
rows = await self.bot.dbutil.execute(sql)
except SQLAlchemyError:
logger.exception('Failed to get command stats')
top_cmd = 'Failed to get command stats'
else:
top_cmd = ''
i = 1
for row in rows:
name = row['parent']
cmd = row['cmd']
if cmd:
name += ' ' + cmd
top_cmd += f'{i}. `{name}` with {row["uses"]} uses\n'
i += 1
embed = discord.Embed(title='Stats', colour=random_color())
embed.add_field(name='discord.py version', value=discord.__version__)
embed.add_field(name='Uptime', value=uptime)
embed.add_field(name='Servers', value=str(guilds))
embed.add_field(name='Users', value=str(users))
embed.add_field(name='Memory usage', value=memory_usage)
embed.add_field(name='Last updated', value=last_updated)
embed.add_field(name='Most used commands', value=top_cmd, inline=False)
embed.set_thumbnail(url=get_avatar(self.bot.user))
embed.set_author(name=self.bot.user.name, icon_url=get_avatar(self.bot.user))
await ctx.send(embed=embed)
@command(name='roles', ignore_extra=True, no_pm=True)
@cooldown(1, 10, type=BucketType.guild)
async def get_roles(self, ctx, page=''):
"""Get roles on this server"""
guild_roles = sorted(ctx.guild.roles, key=lambda r: r.name)
idx = 0
if page:
try:
idx = int(page) - 1
if idx < 0:
return await ctx.send('Index must be bigger than 0')
except ValueError:
return await ctx.send('%s is not a valid integer' % page, delete_after=30)
roles = 'A total of %s roles\n' % len(guild_roles)
for role in guild_roles:
roles += '{}: {}\n'.format(role.name, role.mention)
roles = split_string(roles, splitter='\n', maxlen=1000)
await send_paged_message(ctx, roles, starting_idx=idx,
page_method=lambda p, i: '```{}```'.format(p))
@command(aliases=['created_at', 'snowflake', 'snoflake'], ignore_extra=True)
@cooldown(1, 5, type=BucketType.guild)
async def snowflake_time(self, ctx, id: int):
"""Gets creation date from the specified discord id in UTC"""
try:
int(id)
except ValueError:
return await ctx.send("{} isn't a valid integer".format(id))
await ctx.send(str(discord.utils.snowflake_time(id)))
@command()
@cooldown(1, 5, BucketType.user)
async def birthday(self, ctx, *, user: clean_content):
url = 'http://itsyourbirthday.today/#' + quote(user)
await ctx.send(url)
@command(name='unzalgo')
@cooldown(2, 5, BucketType.guild)
async def unzalgo_(self, ctx, *, text=None):
"""Unzalgo text
if text is not specified a cache lookup on zalgo text is done for the last 100 msgs
and the first found zalgo text is unzalgo'd"""
if text is None:
messages = self.bot._connection._messages
for i in range(-1, -100, -1):
try:
msg = messages[i]
except IndexError:
break
if msg.channel.id != ctx.channel.id:
continue
if is_zalgo(msg.content):
text = msg.content
break
if text is None:
await ctx.send("Didn't find a zalgo message")
return
await ctx.send(unzalgo(text))
@command()
@cooldown(1, 120, BucketType.user)
async def feedback(self, ctx, *, feedback):
"""
Send feedback of the bot.
Bug reports should go to https://github.com/s0hvaperuna/Not-a-bot/issues
"""
webhook = self.bot.config.feedback_webhook
if not webhook:
return await ctx.send('This command is unavailable atm')
json = {'content': feedback,
'avatar_url': ctx.author.avatar_url,
'username': ctx.author.name}
headers = {'Content-type': 'application/json'}
await self.bot.aiohttp_client.post(webhook, json=json, headers=headers)
await ctx.send('Feedback sent')
@command(aliases=['bug'], ignore_extra=True)
@cooldown(1, 10, BucketType.user)
async def bugreport(self, ctx):
"""For reporting bugs"""
await ctx.send('If you have noticed a bug in my bot report it here https://github.com/s0hv/Not-a-bot/issues\n'
f"If you don't have a github account or are just too lazy you can use {ctx.prefix}feedback for reporting as well")
@command(ingore_extra=True)
@cooldown(1, 10, BucketType.guild)
async def vote(self, ctx):
"""Pls vote thx"""
await ctx.send('https://discordbots.org/bot/214724376669585409/vote')
@command(aliases=['sellout'], ignore_extra=True)
@cooldown(1, 10)
async def donate(self, ctx):
"""
Bot is not free to host. Donations go straight to server costs
"""
await ctx.send('If you want to support bot in server costs donate to https://www.paypal.me/s0hvaperuna\n'
'Alternatively you can use my DigitalOcean referral link https://m.do.co/c/84da65db5e5b')
@staticmethod
def find_emoji(emojis, name):
for e in emojis:
if e.name.lower() == name:
return e
@command()
@cooldown(1, 5, BucketType.user)
async def emojify(self, ctx, *, text: str):
"""Turns your text without emotes to text with discord custom emotes
To blacklist words from emoji search use a quoted string at the
beginning of the command denoting those words
e.g. emojify "blacklisted words here" rest of the sentence"""
emojis = ctx.bot.emojis
new_text = ''
word_blacklist = None
# Very simple method to parse word blacklist
if text.startswith('"'):
idx = text.find('"', 1) # Find second quote idx
word_blacklist = text[1:idx]
if word_blacklist:
text = text[idx+1:]
word_blacklist = [s.lower().strip(',.') for s in word_blacklist.split(' ')]
emoji_cache = {}
for s in text.split(' '):
es = s.lower().strip(',.')
# We don't want to look for emotes that are only a couple characters long
if len(s) < 3 or (word_blacklist and es in word_blacklist):
new_text += s + ' '
continue
e = emoji_cache.get(es)
if not e:
e = self.find_emoji(emojis, es)
if e is None:
e = s
else:
e = str(e)
emoji_cache[es] = e
new_text += e + ' '
await ctx.send(new_text)
@command(name='pip')
@cooldown(1, 5, BucketType.channel)
@bot_has_permissions(embed_links=True)
async def get_package(self, ctx, *, name):
"""Get a package from pypi"""
if SearchCommand is None:
return await ctx.send('Not supported')
def search():
try:
search_command = SearchCommand()
options, _ = search_command.parse_args([])
hits = search_command.search(name, options)
if hits:
return hits[0]
except:
logger.exception('Failed to search package from PyPi')
return
hit = await self.bot.loop.run_in_executor(self.bot.threadpool, search)
if not hit:
return await ctx.send('No matches')
async with self.bot.aiohttp_client.get(f'https://pypi.org/pypi/{quote(hit["name"])}/json') as r:
if r.status != 200:
return await ctx.send(f'HTTP error {r.status}')
json = await r.json()
info = json['info']
description = info['description']
if len(description) > 1000:
description = split_string(description, splitter='\n', maxlen=1000)[0] + '...'
embed = discord.Embed(title=hit['name'],
description=description,
url=info["package_url"])
embed.add_field(name='Author', value=info['author'])
embed.add_field(name='Version', value=info['version'])
embed.add_field(name='License', value=info['license'])
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Utilities(bot))
<file_sep>"""
MIT License
Copyright (c) 2017 s0hvaperuna
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.
"""
import asyncio
import logging
import mimetypes
import os
import re
import shlex
import subprocess
import sys
import time
from collections import OrderedDict, Iterable
from datetime import timedelta, datetime
from enum import Enum
from random import randint
import discord
import numpy
from discord import abc
from discord.ext.commands.errors import MissingPermissions
from sqlalchemy.exc import SQLAlchemyError
from validators import url as test_url
from bot.exceptions import NoCachedFileException, CommandBlacklisted, NotOwner
from bot.globals import BlacklistTypes, PermValues
from bot.paged_message import PagedMessage
# Support for recognizing webp images used in many discord avatars
mimetypes.add_type('image/webp', '.webp')
logger = logging.getLogger('debug')
audio = logging.getLogger('audio')
terminal = logging.getLogger('terminal')
# https://stackoverflow.com/a/4628148/6046713
# Added days and and aliases for names
# Also fixed any string starting with the first option (e.g. 10dd would count as 10 days) being accepted
time_regex = re.compile(r'((?P<days>\d+?) ?(d|days)( |$))?((?P<hours>\d+?) ?(h|hours)( |$))?((?P<minutes>\d+?) ?(m|min|minutes)( |$))?((?P<seconds>\d+?) ?(s|sec|seconds)( |$))?')
timeout_regex = re.compile(r'((?P<days>\d+?) ?(d|days)( |$))?((?P<hours>\d+?) ?(h|hours)( |$))?((?P<minutes>\d+?) ?(m|min|minutes)( |$))?((?P<seconds>\d+?) ?(s|sec|seconds)( |$))?(?P<reason>.*)+?',
re.DOTALL)
timedelta_regex = re.compile(r'((?P<days>\d+?) )?(?P<hours>\d+?):(?P<minutes>\d+?):(?P<seconds>\d+?)')
seek_regex = re.compile(r'((?P<h>\d+)*(?:h ?))?((?P<m>\d+)*(?:m[^s]? ?))?((?P<s>\d+)*(?:s ?))?((?P<ms>\d+)*(?:ms ?))?')
FORMAT_BLACKLIST = ['mentions', 'channel_mentions', 'reactions', 'call',
'embeds', 'attachments', 'role_mentions', 'application',
'raw_channel_mentions', 'raw_role_mentions', 'raw_mentions']
class Object:
# Empty class to store variables
def __init__(self):
pass
class DateAccuracy(Enum):
Second = 0
Minute = 1
Hour = 2
Day = 3
Week = -1 # Special case
Month = 4
Year = 5
class CallLater:
def __init__(self, future, runs_at):
self._future = future
self.runs_at = runs_at
@property
def future(self):
return self._future
def cancel(self):
self.future.cancel()
# Made so only ids can be used
class Snowflake(abc.Snowflake):
def __init__(self, id):
self.id = id
@property
def created_at(self):
return discord.utils.snowflake_time(self.id)
def split_string(to_split, list_join='', maxlen=2000, splitter=' ', max_word: int=None):
"""
Args:
to_split: str, dict or iterable to be split
list_join: the character that's used in joins
maxlen: maximum line length
splitter: what character are the lines split by
max_word: if set will split words longer than this that go over the max
line length. Currently only supported in str mode
Returns:
list of strings or list of dicts
"""
if isinstance(to_split, str):
if len(to_split) < maxlen:
return [to_split]
to_split = [s + splitter for s in to_split.split(splitter)]
to_split[-1] = to_split[-1][:-len(splitter)]
length = 0
split = ''
splits = []
for s in to_split:
l = len(s)
if length + l > maxlen:
if max_word and l > max_word:
delta = maxlen - length
if delta > 3:
split += s[:delta]
splits.append(split)
s = s[delta:]
l = len(s)
while l > maxlen:
splits.append(s[:maxlen])
s = s[maxlen:]
l = len(s)
split = s
length = l
else:
splits.append(split)
split = s
length = l
else:
split += s
length += l
splits.append(split)
return splits
elif isinstance(to_split, dict):
splits_dict = OrderedDict()
splits = []
length = 0
for key in to_split:
joined = list_join.join(to_split[key])
if length + len(joined) > maxlen:
splits += [splits_dict]
splits_dict = OrderedDict()
splits_dict[key] = joined
length = len(joined)
else:
splits_dict[key] = joined
length += len(joined)
if length > 0:
splits += [splits_dict]
return splits
elif isinstance(to_split, Iterable):
splits = []
chunk = ''
for s in to_split:
if len(chunk) + len(s) <= maxlen:
chunk += list_join + s
elif chunk:
splits.append(chunk)
if len(s) > maxlen:
s = s[:maxlen-3] + '...'
splits.append(s)
chunk = ''
elif not chunk:
splits.append(s[:maxlen-3] + '...')
if chunk:
splits.append(chunk)
return splits
logger.debug('Could not split string {}'.format(to_split))
raise NotImplementedError('This only works with dicts and strings for now')
async def mean_volume(file, loop, threadpool, avconv=False, duration=0):
"""Gets the mean volume from"""
audio.debug('Getting mean volume')
ffmpeg = 'ffmpeg' if not avconv else 'avconv'
file = '"{}"'.format(file)
if not duration:
start, stop = 0, 180
else:
start = int(duration * 0.2)
stop = start + 180
cmd = '{0} -i {1} -ss {2} -t {3} -filter:a "volumedetect" -vn -sn -f null /dev/null'.format(ffmpeg, file, start, stop)
audio.debug(cmd)
args = shlex.split(cmd)
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = await loop.run_in_executor(threadpool, process.communicate)
out += err
matches = re.findall('mean_volume: [\-\d.]+ dB', str(out))
if not matches:
return
try:
volume = float(matches[0].split(' ')[1])
audio.debug('Parsed volume is {}'.format(volume))
return volume
except ValueError:
return
def get_cached_song(name):
if os.path.isfile(name):
return name
else:
raise NoCachedFileException
# Write the contents of an iterable or string to a file
def write_playlist(file, contents, mode='w'):
if not isinstance(contents, str):
contents = '\n'.join(contents) + '\n'
if contents == '\n':
return
with open(file, mode, encoding='utf-8') as f:
f.write(contents)
# Read lines from a file and put them to a list without newlines
def read_lines(file):
if not os.path.exists(file):
return []
with open(file, 'r', encoding='utf-8') as f:
songs = f.read().splitlines()
return songs
# Empty the contents of a file
def empty_file(file):
with open(file, 'w', encoding='utf-8'):
pass
def timestamp():
return time.strftime('%d-%m-%Y--%H-%M-%S')
def get_config_value(config, section, option, option_type=None, fallback=None):
try:
if option_type is None:
return config.get(section, option, fallback=fallback)
if issubclass(option_type, bool):
return config.getboolean(section, option, fallback=fallback)
elif issubclass(option_type, str):
return str(config.get(section, option, fallback=fallback))
elif issubclass(option_type, int):
return config.getint(section, option, fallback=fallback)
elif issubclass(option_type, float):
return config.getfloat(section, option, fallback=fallback)
else:
return config.get(section, option, fallback=fallback)
except ValueError as e:
terminal.error('{0}\n{1} value is not {2}. {1} set to {3}'.format(e, option, str(option_type), str(fallback)))
return fallback
def write_wav(stdout, filename):
with open(filename, 'wb') as f:
f.write(stdout.read(36))
# ffmpeg puts metadata that breaks bpm detection. We are going to remove that
stdout.read(34)
while True:
data = stdout.read(100000)
if len(data) == 0:
break
f.write(data)
return filename
def y_n_check(msg):
msg = msg.content.lower().strip()
return msg in ['y', 'yes', 'n', 'no']
def y_check(s):
s = s.lower().strip()
return is_true(s)
def bool_check(s):
msg = s.lower().strip()
return is_true(msg) or is_false(msg)
def is_true(s):
return s in ['y', 'yes', 'true', 'on']
def is_false(s):
return s in ['n', 'false', 'no', 'stop']
def check_negative(n):
if n < 0:
return -1
else:
return 1
def get_emote_url(emote):
match = re.findall(r'(https://cdn.discordapp.com/emojis/\d+.(?:gif|png))(?:\?v=1)?', emote)
if match:
return match[0]
animated, emote_id = get_emote_id(emote)
if emote_id is None:
return
extension = 'png' if not animated else 'gif'
return 'https://cdn.discordapp.com/emojis/{}.{}'.format(emote_id, extension)
def emote_url_from_id(id):
return 'https://cdn.discordapp.com/emojis/%s.png' % id
def get_picture_from_msg(msg):
if msg is None:
return
if len(msg.attachments) > 0:
return msg.attachments[0].url
words = msg.content.split(' ')
for word in words:
if test_url(word):
return word
def normalize_text(s):
# Get cleaned emotes
matches = re.findall('<:\w+:\d+>', s)
for match in matches:
s = s.replace(match, match.split(':')[1])
# matches = re.findall('<@\d+>')
return s
def slots2dict(obj, d: dict=None, replace=True):
# Turns slots and @properties to a dict
if d is None:
d = {k: getattr(obj, k, None) for k in obj.__slots__ if not k.startswith('_')}
else:
for k in obj.__slots__:
if k.startswith('_'):
continue
if not replace and k in d:
continue
d[k] = getattr(obj, k, None)
for k in dir(obj):
if k.startswith('_'): # We don't want any private variables
continue
v = getattr(obj, k, None)
if not callable(v): # Don't need methods here
if not replace and k in d:
continue
d[k] = v
return d
async def retry(f, *args, retries_=3, break_on=(), **kwargs):
e = None
for i in range(0, retries_):
try:
retval = await f(*args, **kwargs)
except break_on as e:
break
except Exception as e_:
e = e_
else:
return retval
return e
def get_emote_id(s):
emote = re.match('(?:<(a)?:\w+:)(\d+)(?=>)', s)
if emote:
return emote.groups()
return None, None
def get_emote_name(s):
emote = re.match('(?:<(a)?:)(\w+)(?::\d+)(?=>)', s)
if emote:
return emote.groups()
return None, None
def get_emote_name_id(s):
emote = re.match('(?:<(a)?:)(\w+)(?::)(\d+)(?=>)', s)
if emote:
return emote.groups()
return None, None, None
async def get_image_from_message(ctx, *messages):
image = None
if len(ctx.message.attachments) > 0 and isinstance(ctx.message.attachments[0].width, int):
image = ctx.message.attachments[0].url
elif messages and messages[0] is not None:
image = str(messages[0])
if not test_url(image):
if re.match('<@!?\d+>', image) and ctx.message.mentions:
image = get_avatar(ctx.message.mentions[0])
elif get_emote_id(image)[1]:
image = get_emote_url(image)
else:
try:
image = int(image)
except ValueError:
pass
else:
user = discord.utils.find(lambda u: u.id == image, ctx.bot.get_all_members())
if user:
image = get_avatar(user)
dbutil = ctx.bot.dbutil
if image is None or not isinstance(image, str):
if isinstance(image, int):
sql = 'SELECT attachment FROM `messages` WHERE message_id=%s' % image
else:
channel = ctx.channel
guild = channel.guild
sql = 'SELECT attachment FROM `messages` WHERE guild={} AND channel={} ORDER BY `message_id` DESC LIMIT 25'.format(guild.id, channel.id)
try:
rows = (await dbutil.execute(sql)).fetchall()
for row in rows:
attachment = row['attachment']
if not attachment:
continue
if is_image_url(attachment):
image = attachment
break
# This is needed because some images like from twitter
# are usually in the format of someimage.jpg:large
# and mimetypes doesn't recognize that
elif is_image_url(':'.join(attachment.split(':')[:-1])):
image = attachment
break
except SQLAlchemyError:
pass
if image is not None:
image = None if not test_url(image) else image
return image
def random_color():
"""
Create a random color to be used in discord
Returns:
discord.Color
"""
return discord.Color(randint(0, 16777215))
# https://stackoverflow.com/a/4628148/6046713
def parse_time(time_str):
parts = time_regex.match(time_str)
if not parts:
return
parts = parts.groupdict()
time_params = {name: int(param) for name, param in parts.items() if param}
return timedelta(**time_params)
def parse_timeout(time_str):
parts = timeout_regex.match(time_str)
if not parts:
return
parts = parts.groupdict()
reason = parts.pop('reason')
time_params = {name: int(param) for name, param in parts.items() if param}
return timedelta(**time_params), reason
def datetime2sql(datetime):
return '{0.year}-{0.month}-{0.day} {0.hour}:{0.minute}:{0.second}'.format(datetime)
def timedelta2sql(timedelta):
return f'{timedelta.days} {timedelta.seconds//3600}:{(timedelta.seconds//60)%60}:{timedelta.seconds%60}'
def sql2timedelta(value):
return timedelta(**{k: int(v) if v else 0 for k, v in timedelta_regex.match(value).groupdict().items()})
def call_later(func, loop, timeout, *args, after=None, **kwargs):
"""
Call later for async functions
Args:
func: async function
loop: asyncio loop
timeout: how long to wait
after: Func to pass to future.add_done_callback
Returns:
asyncio.Task
"""
async def wait():
if timeout > 0:
try:
await asyncio.sleep(timeout, loop=loop)
except asyncio.CancelledError:
return
await func(*args, **kwargs)
fut = asyncio.run_coroutine_threadsafe(wait(), loop)
if callable(after):
fut.add_done_callback(after)
return CallLater(fut, datetime.utcnow() + timedelta(seconds=timeout))
def get_users_from_ids(guild, *ids):
users = []
for i in ids:
user = guild.get_member(i)
if user:
users.append(user)
return users
def check_channel_mention(msg, word):
if msg.channel_mentions:
if word != msg.channel_mentions[0].mention:
return False
return True
return False
def get_channel(channels, s, name_matching=False, only_text=True):
channel = get_channel_id(s)
if channel:
channel = discord.utils.find(lambda c: c.id == s, channels)
if channel:
return channel
try:
s = int(s)
except ValueError:
pass
else:
channel = discord.utils.find(lambda c: c.id == s, channels)
if not channel and name_matching:
s = str(s)
channel = discord.utils.find(lambda c: c.name == s, channels)
if not channel:
return
else:
return
if only_text and not isinstance(channel, discord.TextChannel):
return
return channel
def check_role_mention(msg, word, guild):
if msg.raw_role_mentions:
id = msg.raw_role_mentions[0]
if str(id) not in word:
return False
role = list(filter(lambda r: r.id == id, guild.roles))
if not role:
return False
return role[0]
return False
def get_role(role, roles, name_matching=False):
try:
role_id = int(role)
except ValueError:
role_id = get_role_id(role)
if role_id is None and name_matching:
for role_ in roles:
if role_.name == role:
return role_
elif role_id is None:
return
return discord.utils.find(lambda r: r.id == role_id, roles)
def check_user_mention(msg, word):
if msg.mentions:
if word != msg.mentions[0].mention:
return False
return True
return False
def get_avatar(user):
return user.avatar_url or user.default_avatar_url
def get_role_id(s):
regex = re.compile(r'(?:<@&)?(\d+)(?:>)?(?: |$)')
match = regex.match(s)
if match:
return int(match.groups()[0])
def get_user_id(s):
regex = re.compile(r'(?:<@!?)?(\d+)(?:>)?(?: |$)')
match = regex.match(s)
if match:
return int(match.groups()[0])
def get_channel_id(s):
regex = re.compile(r'(?:<#)?(\d+)(?:>)?')
match = regex.match(s)
if match:
return int(match.groups()[0])
def check_plural(string, i):
if i != 1:
return '%s %ss ' % (str(i), string)
return '%s %s ' % (str(i), string)
def format_timedelta(td, accuracy=3, include_weeks=False, long_format=True):
"""
Formats timedelta object to string with support for longer durations
Args:
td (timedelta):
timedelta object to be formatted
accuracy (int or DateAccuracy):
The accuracy of the function. If set to 1 will give
most inaccurate result rounded down. If 7 will give out result
with precision to seconds. So the bigger the number, the more
verbose the result.
e.g. a timedelta of 13 days would give a result looking something like
this with an accuracy of 2 and weeks on
1 week 6 days
If set to DateAccuracy will only provide accuracy in that format
include_weeks (bool):
Whether to include weeks or just count them as days
long_format (bool):
Whether to use long names or shortened names for time definitions
Returns:
str: formatted time
"""
sec = int(td.total_seconds())
if sec == 0:
return '0 seconds' if long_format else '0s'
if long_format:
names = ['year', 'month', 'week', 'day', 'hour', 'minute', 'second']
else:
names = ['yr', 'mo', 'wk', 'd', 'h', 'min', 's']
if accuracy == DateAccuracy.Week:
include_weeks = True
elif isinstance(accuracy, DateAccuracy) and accuracy != DateAccuracy.Week:
include_weeks = False
if not include_weeks:
divs = [60, 60, 24, 30, 12]
names.pop(2)
else:
divs = [60, 60, 24, 7, 30, 12]
last = sec
times = []
if isinstance(accuracy, int):
for d in divs:
last, val = divmod(last, d)
times.insert(0, val)
# appendleft
times.insert(0, last)
for i in range(len(times)):
if times[i] == 0:
continue
times = times[i:i + accuracy]
names = names[i:i + accuracy]
break
elif isinstance(accuracy, DateAccuracy):
idx = 0
# Week is an exception and we want to keep it out of calculations
# unless it is the requested accuracy. We use day here since we count
# weeks using days in the end
if include_weeks:
accuracy = DateAccuracy.Day
for d in divs:
last, val = divmod(last, d)
times.append(val)
if len(times)-1 >= accuracy.value:
last = last*d+val
times[-1] = last
break
if last == 0:
break
idx += 1
# Exception. We want to exclude weeks when possible to increase accuracy
# of years and months. When using DateAccuracy include_weeks will be
# True only when week is the requested format
if include_weeks and len(times)-1 >= accuracy.value:
val = last//7
if val == 0:
names.pop(2) # Index of week
val = last
else:
names.pop(3) # Index of day
else:
val = last
# Fallback to the closest non zero value
if val == 0:
val = times[-1]
names = [names[len(names)-1-idx]]
times = [val]
else:
raise TypeError('Accuracy must be of instance int or DateAccuracy')
s = ''
for i in range(len(times)):
if times[i] == 0:
continue
if long_format:
s += check_plural(names[i], times[i])
else:
s += f'{times[i]}{names[i]} '
return s.strip()
def seconds2str(seconds, long_def=True):
seconds_ = int(round(seconds, 0))
if not seconds_:
return f'{round(seconds, 2)}s'
seconds = seconds_
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if long_def:
d = check_plural('day', d) if d else ''
h = check_plural('hour', h) if h else ''
m = check_plural('minute', m) if m else ''
s = check_plural('second', s) if s else ''
else:
d = str(d) + 'd ' if d else ''
h = str(h) + 'h ' if h else ''
m = str(m) + 'm ' if m else ''
s = str(s) + 's' if s else ''
return (d + h + m + s).strip()
def find_user(s, members, case_sensitive=False, ctx=None):
if not s:
return
if ctx:
# if ctx is present check mentions first
if ctx.message.mentions and ctx.message.mentions[0].mention.replace('!', '') == s.replace('!', ''):
return ctx.message.mentions[0]
try:
uid = int(s)
except ValueError:
pass
else:
for user in members:
if user.id == uid:
return user
def filter_users(predicate):
for member in members:
if predicate(member):
return member
if member.nick and predicate(member.nick):
return member
p = lambda u: str(u).startswith(s) if case_sensitive else lambda u: str(u).lower().startswith(s)
found = filter_users(p)
s = '`<@!{}>` {}'
if found:
return found
p = lambda u: s in str(u) if case_sensitive else lambda u: s in str(u).lower()
found = filter_users(p)
return found
def is_image_url(url):
if url is None:
return
if not test_url(url):
return False
mimetype, encoding = mimetypes.guess_type(url)
return mimetype and mimetype.startswith('image')
def msg2dict(msg):
d = {}
attachments = [attachment.url for attachment in msg.attachments]
d['attachments'] = ', '.join(attachments)
return d
def format_message(d):
for k in FORMAT_BLACKLIST:
d.pop(k, None)
for k in d:
v = d[k]
if isinstance(v, str):
continue
if isinstance(v, discord.MessageType):
d[k] = str(v.name)
else:
d[k] = str(v)
return d
def format_on_edit(before, after, message, check_equal=True):
bef_content = before.content
aft_content = after.content
if check_equal:
if bef_content == aft_content:
return
user = before.author
d = format_member(user)
d['user_id'] = d['id']
d = slots2dict(after, d)
d['channel_id'] = d.pop('id', None)
d = format_message(d)
for e in ['name', 'before', 'after']:
d.pop(e, None)
d['channel'] = after.channel.mention
message = message.format(name=str(user), **d,
before=bef_content, after=aft_content)
return message
def test_message(msg, is_edit=False):
d = format_member(msg.author)
d = slots2dict(msg, d)
d = format_message(d)
removed = ['name', 'before', 'after'] if is_edit else ['name', 'message']
for e in removed:
d.pop(e, None)
d['channel'] = msg.channel.mention
d['name'] = str(msg.author)
d['system_content'] = d['system_content'][:10]
d['clean_content'] = d['clean_content'][:10]
if is_edit:
d['before'] = msg.content[:10]
d['after'] = msg.content[:10]
else:
d['message'] = msg.content[:10]
s = ''
for k, v in d.items():
s += '{%s}: %s\n' % (k, v)
return remove_everyone(s)
def remove_everyone(s):
return re.sub(r'@(everyone|here)', '@\u200b\\1', s)
def format_activity(activity):
# Maybe put more advanced formatting here in future
return activity.name
def format_member(member):
d = slots2dict(member)
d['user'] = str(member)
d.pop('roles')
d.pop('voice')
d.pop('dm_channel')
for k in d:
v = d[k]
if isinstance(v, discord.Activity):
d[k] = format_activity(v)
elif isinstance(v, discord.Permissions):
d[k] = str(v.value)
else:
d[k] = str(v)
return d
def format_join_leave(member, message):
d = format_member(member)
message = message.format(**d)
return remove_everyone(message)
def test_member(member):
d = format_member(member)
s = ''
for k, v in d.items():
s += '{%s}: %s\n' % (k, v)
return remove_everyone(s)
def format_on_delete(msg, message):
content = msg.content
user = msg.author
d = format_member(user)
d['user_id'] = d['id']
d = slots2dict(msg, d)
d['channel_id'] = d.pop('id', None)
d = format_message(d)
for e in ['name', 'message']:
d.pop(e, None)
d['channel'] = msg.channel.mention
message = message.format(name=str(user), message=content, **d)
return message
# https://stackoverflow.com/a/14178717/6046713
def find_coeffs(pa, pb):
matrix = []
for p1, p2 in zip(pa, pb):
matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])
A = numpy.matrix(matrix, dtype=numpy.float)
B = numpy.array(pb).reshape(8)
res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)
return numpy.array(res).reshape(8)
def check_perms(values, return_raw=False):
# checks if the command can be used based on what rows are given
# ONLY GIVE this function rows of one command or it won't work as intended
smallest = 18
for value in values:
if value['type'] == BlacklistTypes.WHITELIST:
v1 = PermValues.VALUES['whitelist']
else:
v1 = PermValues.VALUES['blacklist']
if value['user'] is not None:
v2 = PermValues.VALUES['user']
elif value['role'] is not None:
v2 = PermValues.VALUES['role']
elif value['channel'] is not None:
v2 = PermValues.VALUES['channel']
else:
v2 = PermValues.VALUES['guild']
v = v1 | v2
if v < smallest:
smallest = v
return PermValues.RETURNS.get(smallest, False) if not return_raw else smallest
def is_superset(ctx):
if ctx.override_perms is None and ctx.command.required_perms is not None:
perms = ctx.message.channel.permissions_for(ctx.message.author)
if not perms.is_superset(ctx.command.required_perms):
req = [r[0] for r in ctx.command.required_perms if r[1]]
raise MissingPermissions(req)
return True
async def send_paged_message(ctx, pages, embed=False, starting_idx=0, page_method=None, timeout=60):
bot = ctx.bot
try:
if callable(page_method):
page = page_method(pages[starting_idx], starting_idx)
else:
page = pages[starting_idx]
except IndexError:
return await ctx.channel.send(f'Page index {starting_idx} is out of bounds')
if embed:
message = await ctx.channel.send(embed=page)
else:
message = await ctx.channel.send(page)
if len(pages) == 1:
return
await message.add_reaction('◀')
await message.add_reaction('▶')
paged = PagedMessage(pages, starting_idx=starting_idx)
if callable(page_method):
async def send():
if embed:
await message.edit(embed=page_method(page, paged.index))
else:
await message.edit(content=page_method(page, paged.index))
else:
async def send():
if embed:
await message.edit(embed=page)
else:
await message.edit(content=page)
def check(reaction, user):
return paged.check(reaction, user) and ctx.author.id == user.id and reaction.message.id == message.id
while True:
try:
result = await bot.wait_for('reaction_changed', check=check, timeout=timeout)
except asyncio.TimeoutError:
return
page = paged.reaction_changed(*result)
if page is None:
continue
try:
await send()
# Wait for a bit so the bot doesn't get ratelimited from reaction spamming
await asyncio.sleep(1)
except discord.HTTPException:
return
async def get_all_reaction_users(reaction, limit=100):
users = []
limits = [100 for i in range(limit // 100)]
remainder = limit % 100
if remainder > 0:
limits.append(remainder)
for limit in limits:
if users:
user = users[-1]
else:
user = None
_users = await reaction.users(limit=limit, after=user)
users.extend(_users)
return users
async def create_custom_emoji(guild, name, image, already_b64=False, reason=None, **kwargs):
"""Same as the base method but supports giving your own b64 encoded data"""
if not already_b64:
img = discord.utils._bytes_to_base64_data(image)
else:
img = image
data = await guild._state.http.create_custom_emoji(guild.id, name, img, reason=reason, **kwargs)
return guild._state.store_emoji(guild, data)
def is_owner(ctx):
if ctx.command.owner_only and ctx.bot.owner_id != ctx.original_user.id:
raise NotOwner
ctx.skip_check = True
return True
async def check_blacklist(ctx):
if getattr(ctx, 'skip_check', False):
return True
bot = ctx.bot
if not hasattr(bot, 'check_auth'):
# No database blacklisting detected
return True
if not await bot.check_auth(ctx):
return False
overwrite_perms = await bot.dbutil.check_blacklist('(command="%s" OR command IS NULL)' % ctx.command, ctx.author, ctx, True)
msg = PermValues.BLACKLIST_MESSAGES.get(overwrite_perms, None)
if isinstance(overwrite_perms, int):
if ctx.guild and ctx.guild.owner.id == ctx.author.id:
overwrite_perms = True
else:
overwrite_perms = PermValues.RETURNS.get(overwrite_perms, False)
ctx.override_perms = overwrite_perms
if overwrite_perms is False:
if msg is not None:
raise CommandBlacklisted(msg)
return False
return True
async def search(s, ctx, site, downloader, on_error=None):
search_keys = {'yt': 'ytsearch', 'sc': 'scsearch'}
urls = {'yt': 'https://www.youtube.com/watch?v=%s'}
max_results = 20
search_key = search_keys.get(site, 'ytsearch')
channel = ctx.channel
query = '{0}{1}:{2}'.format(search_key, max_results, s)
info = await downloader.extract_info(ctx.bot.loop, url=query,
on_error=on_error,
download=False)
if info is None or 'entries' not in info:
return await channel.send('Search gave no results', delete_after=60)
url = urls.get(site, 'https://www.youtube.com/watch?v=%s')
def get_page(page, index):
id = page.get('id')
if id is None:
return page.get('url')
return url % id
await send_paged_message(ctx, info['entries'], page_method=get_page)
def basic_check(author=None, channel=None):
def check(msg):
if author and author.id != msg.author.id:
return False
if channel and channel.id != msg.channel.id:
return False
return True
return check
def parse_seek(s):
match = seek_regex.match(s)
if not match:
return
return {k: v or '0' for k, v in match.groupdict().items()}
def seek_to_sec(seek_dict):
return int(seek_dict['h'])*3600 + int(seek_dict['m'])*60 + int(seek_dict['s'])
def check_import(module_name):
"""
This function is responsible for checking for errors in python code
It does not check imports
Returns:
Empty string if nothing was found. Otherwise the error
"""
module_name = module_name.split('.')
module_name[-1] = module_name[-1] + '.py'
module_name = os.path.join(os.getcwd(), *module_name)
cmd = f'"{sys.executable}" -m compileall "{module_name}"'
p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
out, _ = p.communicate()
out = out.decode('utf-8')
if out.lower().startswith('compiling'):
out = '\n'.join(out.split('\n')[1:]).strip('* ')
return out
def check_botperm(*perms, ctx=None, channel=None, guild=None, me=None, raise_error=None):
if not perms:
return True
if not me:
if not guild and ctx:
guild = ctx.guild
me = guild.me if guild is not None else ctx.bot.user
channel = channel if channel else ctx.channel
permissions = channel.permissions_for(me)
missing = [perm for perm in perms if
getattr(permissions, perm) is False]
if not missing:
return True
if raise_error:
raise raise_error(missing)
return False
def no_dm(ctx):
if ctx.guild is None:
raise discord.ext.commands.NoPrivateMessage('This command cannot be used in private messages.')
return True
async def wait_for_yes(ctx, timeout=60):
_check = basic_check(ctx.author, ctx.channel)
def check(msg):
return _check(msg) and bool_check(msg.content)
try:
msg = await ctx.bot.wait_for('message', check=check, timeout=timeout)
except asyncio.TimeoutError:
await ctx.send('Took too long')
return
if not y_check(msg.content):
await ctx.send('Cancelling')
return
return msg
<file_sep>import asyncio
import json
import logging
import os
import re
import shlex
from io import BytesIO
from math import ceil, sqrt
import discord
from PIL import Image, ImageDraw, ImageFont
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
from colormath.color_objects import LabColor, sRGBColor
from colour import Color as Colour
from discord.errors import InvalidArgument
from discord.ext.commands import (BucketType, bot_has_permissions, BadArgument,
clean_content)
from numpy.random import choice
from sqlalchemy.exc import SQLAlchemyError
from bot.bot import command, has_permissions, cooldown, group
from bot.globals import WORKING_DIR
from cogs.cog import Cog
from utils.utilities import (split_string, get_role, y_n_check, y_check,
Snowflake, check_botperm)
logger = logging.getLogger('debug')
terminal = logging.getLogger('terminal')
rgb_splitter = re.compile(r'^(\d{1,3})([, ])(\d{1,3})\2(\d{1,3})$')
class Color:
def __init__(self, role_id, name, value, guild_id, lab):
self.role_id = role_id
self.name = name
self.value = value
if isinstance(lab, LabColor):
self.lab = lab
else:
self.lab = LabColor(*lab)
self.guild_id = guild_id
def __str__(self):
return self.name
# https://stackoverflow.com/a/2262152/6046713
def to_rgb(self):
return (self.value >> 16) & 255, (self.value >> 8) & 255, self.value & 255
@property
def rgb(self):
return self.to_rgb()
class Colors(Cog):
def __init__(self, bot):
super().__init__(bot)
self._colors = {}
self.bot.colors = self._colors
asyncio.run_coroutine_threadsafe(self._cache_colors(), self.bot.loop)
with open(os.path.join(os.getcwd(), 'data', 'color_names.json'), 'r', encoding='utf-8') as f:
self._color_names = json.load(f)
async def _cache_colors(self):
sql = 'SELECT colors.id, colors.name, colors.value, roles.guild, colors.lab_l, colors.lab_a, colors.lab_b FROM ' \
'colors LEFT OUTER JOIN roles on roles.id=colors.id'
try:
rows = (await self.bot.dbutil.execute(sql)).fetchall()
except SQLAlchemyError:
logger.exception('Failed to cache colors')
return
for row in rows:
if not self.bot.get_guild(row['guild']):
continue
await self._add_color(**row)
async def _add_color2db(self, color, update=False):
await self.bot.dbutils.add_roles(color.guild_id, color.role_id)
sql = 'INSERT INTO `colors` (`id`, `name`, `value`, `lab_l`, `lab_a`, `lab_b`) VALUES ' \
'(:id, :name, :value, :lab_l, :lab_a, :lab_b)'
if update:
sql += ' ON DUPLICATE KEY UPDATE name=:name, value=:value, lab_l=:lab_l, lab_a=:lab_a, lab_b=:lab_b'
if isinstance(color, list):
params = [{'id': c.role_id,
'name': c.name,
'value': c.value,
'lab_l': c.lab.lab_l,
'lab_a': c.lab.lab_a,
'lab_b': c.lab.lab_b} for c in color]
else:
params = {'id': color.role_id,
'name': color.name,
'value': color.value,
'lab_l': color.lab.lab_l,
'lab_a': color.lab.lab_a,
'lab_b': color.lab.lab_b}
try:
await self.bot.dbutil.execute(sql, params=params, commit=True)
except SQLAlchemyError:
logger.exception('Failed to add color to db')
return False
else:
return True
@staticmethod
def check_rgb(rgb, to_role=True):
"""
:param rgb: rgb tuple
:param to_role: whether to convert the value to the one that shows on discord (False) or to the one you want to show (True)
:return: new rgb tuple if change was needed
"""
if max(rgb) == 0:
if to_role:
# Because #000000 is reserved for another color this must be used for black
rgb = (0, 0, 1/255)
else:
# color #000000 uses the default color on discord which is the following color
rgb = (185/255, 187/255, 190/255)
return rgb
def rgb2lab(self, rgb, to_role=True):
"""
Args:
rgb (list or tuple):
not upscaled rgb tuple
to_role (bool or none):
Bool if check_rgb is used.
None if skip using check_rgb
Returns:
LabColor: lab color
"""
if to_role is not None:
rgb = self.check_rgb(rgb, to_role=to_role)
return convert_color(sRGBColor(*rgb), LabColor)
async def _update_color(self, color, role, to_role=True, lab: LabColor=None):
if not lab:
r, g, b = role.color.to_rgb()
lab = self.rgb2lab((r/255, g/255, b/255), to_role=to_role)
color.value = role.color.value
color.lab = lab
await self._add_color2db(color, update=True)
return color
async def _add_color(self, guild, id, name, value, lab_l, lab_a, lab_b):
if not isinstance(guild, int):
guild_id = guild.id
else:
guild_id = guild
guild = self.bot.get_guild(guild_id)
role = guild.get_role(id)
if role is None:
return
color = Color(id, name, value, guild_id, (lab_l, lab_a, lab_b))
if guild_id in self._colors:
self._colors[guild_id][id] = color
else:
self._colors[guild_id] = {id: color}
if role.color.value != value:
await self._update_color(color, role)
else:
lab = self.rgb2lab(tuple(map(lambda x: x/255, role.color.to_rgb())))
if not lab_l==lab.lab_l and lab_a==lab.lab_a and lab_b==lab.lab_b:
await self._update_color(color, role, lab=lab)
return color
async def _delete_color(self, guild_id, role_id):
try:
color = self._colors[guild_id].pop(role_id)
logger.debug(f'Deleting color {color.name} with value {color.value} from guild {guild_id}')
except KeyError:
logger.debug(f'Deleting color {role_id} from guild {guild_id} if it existed')
await self.bot.dbutils.delete_role(role_id, guild_id)
def get_color(self, name, guild_id):
name = name.lower()
return discord.utils.find(lambda n: str(n[1]).lower() == name,
self._colors.get(guild_id, {}).items())
def search_color_(self, name):
name = name.lower()
names = list(self._color_names.keys())
if name in names:
return name, self._color_names[name]
else:
matches = [n for n in names if name in n]
if not matches:
return
if len(matches) == 1:
return matches[0], self._color_names[matches[0]]
return matches
def match_color(self, color, convert2discord=True):
color = color.lower()
if color in self._color_names:
rgb = self._color_names[color]
if not convert2discord:
return rgb['hex']
rgb = rgb['rgb']
rgb = tuple(map(lambda c: c/255.0, rgb))
else:
try:
rgb = Colour(color)
if not convert2discord:
return rgb.get_hex_l()
rgb = rgb.rgb
except:
return
return self.check_rgb(rgb)
@staticmethod
def closest_color_match(color, colors):
if isinstance(color, Color):
lab = color.lab
else:
lab = color
closest_match = None
similarity = 0
for c in colors:
if isinstance(c, Color):
clab = c.lab
else:
clab = c
d = 100 - delta_e_cie2000(lab, clab)
if d > similarity:
similarity = d
closest_match = c
similarity = round(similarity, 2)
return closest_match, similarity
def closest_match(self, color, guild):
colors = self._colors.get(guild.id)
if not colors:
return
rgb = self.match_color(color)
if not rgb:
return
color = self.rgb2lab(rgb)
return self.closest_color_match(color, colors.values())
async def on_guild_role_delete(self, role):
await self._delete_color(role.guild.id, role.id)
async def on_guild_role_update(self, before, after):
if before.color.value != after.color.value:
color = self._colors.get(before.guild.id, {}).get(before.id)
if not color:
return
if before.name != after.name and before.name == color.name:
color.name = after.name
await self._update_color(color, before, to_role=False)
async def _add_colors_from_roles(self, roles, ctx):
guild = ctx.guild
colors = self._colors.get(guild.id)
if colors is None:
colors = {}
self._colors[guild.id] = colors
for role in roles:
color = role.color
if color.value == 0:
await ctx.send('Role {0.name} has no color'.format(role))
continue
r = discord.utils.find(lambda c: c.value == color.value, colors.values())
if r:
await ctx.send('Color {0.name} already exists'.format(role))
continue
lab = self.rgb2lab(tuple(map(lambda v: v/255, color.to_rgb())))
color = Color(role.id, role.name, color.value, guild.id, lab)
if await self._add_color2db(color):
await ctx.send('Color {} created'.format(role))
colors[role.id] = color
else:
await ctx.send('Failed to create color {0.name}'.format(role))
@staticmethod
def concatenate_colors(images, width=50):
max_width = width*len(images)
height = max(map(lambda i: i.height, images))
empty = Image.new('RGBA', (max_width, height), (0,0,0,0))
offset = 0
for im in images:
empty.paste(im, (offset, 0))
offset += width
return empty
@staticmethod
def stack_colors(images, height=50, max_width: int=None):
max_height = height*len(images)
if not max_width:
max_width = max(map(lambda i: i.width, images))
empty = Image.new('RGBA', (max_width, max_height), (0,0,0,0))
offset = 0
for im in images:
empty.paste(im, (0, offset))
offset += height
return empty
@staticmethod
def split_rgb(s):
rgb = rgb_splitter.match(s)
if rgb:
rgb = rgb.groups()
rgb = (rgb[0], *rgb[2:])
return tuple(map(int, rgb))
@staticmethod
def rgb2hex(*rgb):
rgb = map(lambda c: hex(c)[2:].zfill(2), rgb)
return '#' + ''.join(rgb)
@staticmethod
def s_int2hex(i: str):
"""
Convert integer string to hex
"""
try:
if len(i) > 8:
raise BadArgument(f'Integer color value too long for {i}')
return '#' + hex(int(i))[2:].zfill(6)
except (ValueError, TypeError):
raise BadArgument(f'Failed to convert int to hex ({i})')
def parse_color_range(self, start, end, steps=10):
color1 = self.color_from_str(start)
color2 = self.color_from_str(end)
colors = Colour(color1).range_to(color2, steps)
return colors
def color_from_str(self, color):
color = color.lower()
if color in ('transparent', 'none', 'invisible'):
return 0, 0, 0, 0
color = color.replace('0x', '#')
if not color.startswith('#'):
match = self.match_color(color, False)
if not match:
rgb = self.split_rgb(color.strip('()[]{}').replace(', ', ','))
if not rgb:
color = self.s_int2hex(color)
else:
if len(list(filter(lambda i: -1 < i < 256, rgb))) != 3:
raise BadArgument(f'Bad rgb values for {rgb}')
color = rgb
else:
color = match
elif len(color) > 9:
raise BadArgument(f'Hex value too long for {color}')
return color
@command(aliases=['cr', 'gradient', 'hue'])
@cooldown(1, 5, BucketType.channel)
async def color_range(self, ctx, start, end, steps: int=10):
"""
Makes a color gradient from one color to another in the given steps
Resulting colors are concatenated horizontally
Example use
{prefix}{name} red blue 25
would give you color range from red to blue in 25 steps
To see all values accepted as colors check `{prefix}help get_color`
"""
if steps > 500 or steps < 2:
raise BadArgument('Maximum amount of steps is 500 and minimum is 2')
colors = list(self.parse_color_range(start, end, steps))
size = (50, max(50, min(int(1.25*steps), 300)))
images = []
hex_colors = []
def do_the_thing():
for color in colors:
try:
im = Image.new('RGB', size, color.get_hex_l())
images.append(im)
hex_colors.append(color.get_hex_l())
except (TypeError, ValueError):
raise BadArgument(f'Failed to create image using color {color}')
concat = self.concatenate_colors(images)
data = BytesIO()
concat.save(data, 'PNG')
data.seek(0)
return data
data = await self.bot.loop.run_in_executor(self.bot.threadpool, do_the_thing)
if steps > 10:
s = f'From {colors[0].get_hex_l()} to {colors[-1].get_hex_l()}'
else:
s = ' '.join(hex_colors)
await ctx.send(s, file=discord.File(data, 'colors.png'))
@command(aliases=['c'], name='get_color')
@cooldown(1, 5, BucketType.channel)
async def get_color_image(self, ctx, *, color_list: clean_content):
"""
Post a picture of a color or multiple colors
when specifying multiple colors make sure colors that have a space in them
like light blue are written using quotes like this `red "light blue" green`
By default colors are concatenated horizontally. For vertical stacking
use a newline like this
```
{prefix}{name} red green
blue yellow
```
Which would have red and green on top and blue and yellow on bottom
Color can be a
\u200b \u200b \u200b• hex value (`#000000` or `0x000000`)
\u200b \u200b \u200b• RGB tuple `(0,0,0)`
\u200b \u200b \u200b• Color name. All compatible names are listed [here](https://en.wikipedia.org/wiki/List_of_colors_(compact))
\u200b \u200b \u200b• Any of `invisible`, `none`, `transparent` for transparent spot
"""
color_list = [shlex.split(c) for c in color_list.split('\n')]
lengths = map(len, color_list)
if sum(lengths) > 100:
raise BadArgument('Maximum amount of colors is 100')
images = []
hex_colors = []
size = (50, 50)
def do_the_thing():
for colors in color_list:
ims = []
for color in colors:
color = self.color_from_str(color)
try:
im = Image.new('RGBA', size, color)
ims.append(im)
if isinstance(color, tuple):
color = self.rgb2hex(*color)
hex_colors.append(color)
except (TypeError, ValueError):
raise BadArgument(f'Failed to create image using color {color}')
images.append(self.concatenate_colors(ims))
if len(images) > 1:
concat = self.stack_colors(images)
else:
concat = images[0]
data = BytesIO()
concat.save(data, 'PNG')
data.seek(0)
return data
data = await self.bot.loop.run_in_executor(self.bot.threadpool, do_the_thing)
await ctx.send(' '.join(hex_colors), file=discord.File(data, 'colors.png'))
@command(no_pm=True, aliases=['colour'])
@cooldown(1, 5, type=BucketType.user)
async def color(self, ctx, *, color=None):
"""Set you color on the server.
{prefix}{name} name of color
To see the colors on this server use {prefix}colors or {prefix}show_colors"""
guild = ctx.guild
colors = self._colors.get(guild.id, None)
if not colors:
return await ctx.send("This guild doesn't have any color roles")
ids = set(colors.keys())
roles = set([r.id for r in ctx.author.roles])
if not color:
user_colors = roles.intersection(ids)
if not user_colors:
return await ctx.send("You don't have a color role")
if len(user_colors) > 1:
return await ctx.send('You have multiple color roles <:gappyThinking:358523789170180097>')
else:
name = colors.get(user_colors.pop())
return await ctx.send('Your current color is {0}. To set a color use {1}{2} color name\n'
'Use {1}colors to see a list of colors in this guild. To also see the role colors use {1}show_colors'.format(name, ctx.prefix, ctx.invoked_with))
color_ = self.get_color(color, guild.id)
if not color_:
match = self.closest_match(color, guild)
if not match:
return await ctx.send('Could not find color %s' % color)
color_, similarity = match
return await ctx.send('Could not find color {0}. Color closest to '
'{0} is {1} with {2:.02f}% similarity'.format(color, color_.name, similarity))
id, color = color_
if id in roles and len(roles) <= 1:
return await ctx.send('You already have that color')
roles = roles.difference(ids)
roles.add(id)
try:
await ctx.author.edit(roles=[Snowflake(r) for r in roles])
except discord.HTTPException as e:
return await ctx.send('Failed to set color because of an error\n\n```\n%s```' % e)
await ctx.send('Color set to %s' % color.name)
@staticmethod
def text_only_colors(colors):
s = ''
le = len(colors) - 1
for idx, color in enumerate(colors.values()):
s += str(color)
if le != idx:
s += ', '
s = split_string(s, maxlen=2000, splitter=', ')
return s
def sort_by_color(self, colors):
start = self.rgb2lab((0,0,0), to_role=None)
color, _ = self.closest_color_match(start, colors)
sorted_colors = [color]
colors.remove(color)
while colors:
closest, _ = self.closest_color_match(sorted_colors[-1], colors)
colors.remove(closest)
sorted_colors.append(closest)
return sorted_colors
# https://stackoverflow.com/a/3943023/6046713
@staticmethod
def text_color(color: Color):
r, g, b = color.rgb
if (r * 0.299 + g * 0.587 + b * 0.114) > 186:
return '#000000'
return '#FFFFFF'
def draw_text(self, color: Color, size, font: ImageFont.FreeTypeFont):
im = Image.new('RGB', size, color.rgb)
draw = ImageDraw.Draw(im)
name = str(color)
text_size = font.getsize(name)
text_color = self.text_color(color)
if text_size[0] > size[0]:
all_lines = []
lines = split_string(name, maxlen=len(name)//(text_size[0]/size[0]))
margin = 2
total_y = 0
for line in lines:
line = line.strip()
if not line:
continue
if text_size[1] + total_y > size[1]:
break
x = (size[0] - font.getsize(line)[0]) // 2
all_lines.append((line, x))
total_y += margin + text_size[1]
y = (size[1] - total_y) // 2
for line, x in all_lines:
draw.text((x, y), line, font=font, fill=text_color)
y += margin + text_size[1]
else:
x = (size[0] - text_size[0]) // 2
y = (size[1] - text_size[1]) // 2
draw.text((x, y), name, font=font, fill=text_color)
return im
def _sorted_color_image(self, colors):
size = (100, 100)
colors = self.sort_by_color(colors)
side = ceil(sqrt(len(colors)))
font = ImageFont.truetype(
os.path.join(WORKING_DIR, 'M-1c', 'mplus-1c-bold.ttf'),
encoding='utf-8', size=17)
images = []
reverse = False
for i in range(0, len(colors), side):
color_range = colors[i:i + side]
ims = []
for color in color_range:
ims.append(self.draw_text(color, size, font))
if not ims:
continue
if reverse:
while len(ims) < side:
ims.append(Image.new('RGBA', size, (0, 0, 0, 0)))
ims.reverse()
reverse = False
else:
reverse = True
images.append(self.concatenate_colors(ims, width=size[0]))
stack = self.stack_colors(images, size[1])
data = BytesIO()
stack.save(data, 'PNG')
data.seek(0)
return data
@group(no_pm=True, aliases=['colours'], invoke_without_command=True)
@cooldown(1, 5, type=BucketType.guild)
async def colors(self, ctx):
"""Shows the colors on this guild"""
guild = ctx.guild
colors = self._colors.get(guild.id)
if not colors:
return await ctx.send("This guild doesn't have any color roles")
if not check_botperm('attach_files', ctx=ctx):
for msg in self.text_only_colors(colors):
await ctx.send(msg)
return
data = await self.bot.loop.run_in_executor(self.bot.threadpool, self._sorted_color_image, list(colors.values()))
await ctx.send(file=discord.File(data, 'colors.png'))
@colors.command(no_pm=True)
@bot_has_permissions(attach_files=True)
@cooldown(1, 60, type=BucketType.guild)
async def roles(self, ctx):
"""
Sorts all roles in the server by color and puts them in one file.
Every role gets a square with it's color and name on it
"""
colors = []
for role in ctx.guild.roles:
rgb = role.color.to_rgb()
rgb = self.check_rgb(tuple(v/255 for v in rgb), to_role=False)
lab = convert_color(sRGBColor(*rgb), LabColor)
rgb = tuple(round(v*255) for v in rgb)
value = rgb[0]
value = (((value << 8) + rgb[1]) << 8) + rgb[2]
colors.append(Color(None, role.name, value, None, lab))
async with ctx.typing():
data = await self.bot.loop.run_in_executor(self.bot.threadpool, self._sorted_color_image, colors)
await ctx.send(file=discord.File(data, 'colors.png'))
@command(aliases=['search_colour'])
@cooldown(1, 3, BucketType.user)
async def search_color(self, ctx, *, name):
"""Search a color using a name and return it's hex value if found"""
matches = self.search_color_(name)
if matches is None:
return await ctx.send('No colors found with {}'.format(name))
if isinstance(matches, list):
total = len(matches)
matches = choice(matches, 10)
return await ctx.send('Found matches a total of {0} matches\n{1}\n{2} of {0}'.format(total, '\n'.join(matches), len(matches)))
name, match = matches
await ctx.send('Found color {0} {1[hex]}'.format(name, match))
@command(no_pm=True, aliases=['add_colour'])
@has_permissions(manage_roles=True)
@bot_has_permissions(manage_roles=True)
@cooldown(1, 5, type=BucketType.guild)
async def add_color(self, ctx, color: str, *name):
"""Add a new color to the guild"""
if not name:
name = color
else:
name = ' '.join(name)
rgb = self.match_color(color)
if not rgb:
return await ctx.send(f'Color {color} not found')
guild = ctx.guild
lab = self.rgb2lab(rgb)
color = convert_color(lab, sRGBColor)
value = int(color.get_rgb_hex()[1:], 16)
r = discord.utils.find(lambda i: i[1].value == value, self._colors.get(guild.id, {}).items())
if r:
k, r = r
if guild.get_role(r.role_id):
return await ctx.send('This color already exists')
else:
self._colors.get(guild.id, {}).pop(k, None)
color = lab
default_perms = guild.default_role.permissions
try:
d_color = discord.Colour(value)
color_role = await guild.create_role(name=name, permissions=default_perms,
colour=d_color, reason=f'{ctx.author} created a new color')
except discord.HTTPException as e:
logger.exception('guild {0.id} rolename: {1} perms: {2} color: {3} {4}'.format(guild, name, default_perms.value, str(rgb), value))
return await ctx.send('Failed to add color because of an error\n```%s```' % e)
except:
logger.exception('Failed to create color role')
return await ctx.send('Failed to add color because of an error')
color_ = Color(color_role.id, name, value, guild.id, color)
success = await self._add_color2db(color_)
if not success:
return await ctx.send('Failed to add color')
if self._colors.get(guild.id):
role = guild.get_role(list(self._colors[guild.id].keys())[0])
if role:
try:
await color_role.edit(position=max(1, role.position))
except:
logger.exception('Failed to move color to position')
self._colors[guild.id][color_role.id] = color_
else:
self._colors[guild.id] = {color_role.id: color_}
await ctx.send('Added color {} {}'.format(name, str(d_color)))
@command(no_pm=True, aliases=['colors_from_roles'])
@has_permissions(manage_roles=True)
@bot_has_permissions(manage_roles=True)
@cooldown(1, 5, type=BucketType.guild)
async def add_colors_from_roles(self, ctx, *, roles):
"""Turn existing role(s) to colors.
Usage:
{prefix}{name} 326726982656196629 Red @Blue
Works with role mentions, role ids and name matching"""
if not roles:
return await ctx.send('Give some roles to turn to guild colors')
roles = shlex.split(roles)
guild = ctx.guild
success = []
failed = []
for role in roles:
r = get_role(role, guild.roles, name_matching=True)
if r:
success.append(r)
else:
failed.append(role)
s = ''
if success:
s += 'Adding roles {}\n'.format(', '.join(['`%s`' % r.name for r in success]))
if failed:
s += 'Failed to find roles {}'.format(', '.join([f'`{r}`' for r in failed]))
for s in split_string(s, splitter=', '):
await ctx.send(s)
await ctx.send('Do you want to continue?', delete_after=60)
channel, author = ctx.channel, ctx.author
def check(msg):
if msg.channel.id != channel.id:
return False
if msg.author.id != author.id:
return False
return y_n_check(msg)
try:
msg = await self.bot.wait_for('message', timeout=60, check=check)
except asyncio.TimeoutError:
msg = None
if msg is None or not y_check(msg.content):
return await ctx.send('Cancelling', delete_after=60)
await self._add_colors_from_roles(success, ctx)
@command(no_pm=True, aliases=['del_color', 'remove_color', 'delete_colour', 'remove_colour'])
@has_permissions(manage_roles=True)
@bot_has_permissions(manage_roles=True)
@cooldown(1, 3, type=BucketType.guild)
async def delete_color(self, ctx, *, name):
"""Delete a color from the server"""
guild = ctx.guild
color = self.get_color(name, guild.id)
if not color:
return await ctx.send(f"Couldn't find color {name}")
role_id = color[0]
role = guild.get_role(role_id)
if not role:
await self._delete_color(guild.id, role_id)
await ctx.send(f'Removed color {color[1]}')
return
try:
await role.delete(reason=f'{ctx.author} deleted this color')
await self._delete_color(guild.id, role_id)
except discord.HTTPException as e:
return await ctx.send(f'Failed to remove color because of an error\n```{e}```')
except:
logger.exception('Failed to remove color')
return await ctx.send('Failed to remove color because of an error')
await ctx.send(f'Removed color {color[1]}')
@command(no_pm=True, aliases=['show_colours'])
@cooldown(1, 4, type=BucketType.guild)
async def show_colors(self, ctx):
"""Show current colors on the guild in an embed.
This allows you to see how they look"""
guild = ctx.guild
colors = self._colors.get(guild.id, None)
if not colors:
return await ctx.send("This guild doesn't have any colors")
embed_count = ceil(len(colors)/50)
switch = 0
current_embed = 0
fields = 0
embeds = [discord.Embed() for i in range(embed_count)]
for color in colors.values():
if switch == 0:
field_title = str(color)
field_value = '<@&%s>' % color.role_id
switch = 1
elif switch == 1:
field_title += ' --- ' + str(color)
field_value += ' <@&%s>' % color.role_id
switch = 0
embeds[current_embed].add_field(name=field_title, value=field_value)
fields += 1
if fields == 25:
current_embed += 1
if switch == 1:
embeds[current_embed].add_field(name=field_title, value=field_value)
for embed in embeds:
await ctx.send(embed=embed)
@command(owner_only=True)
async def color_uncolored(self, ctx):
"""Color users that don't have a color role"""
guild = ctx.guild
color_ids = list(self._colors.get(guild.id, {}).keys())
if not color_ids:
return await ctx.send('No colors')
try:
await self.bot.request_offline_members(guild)
except InvalidArgument:
pass
roles = guild.roles
colored = 0
duplicate_colors = 0
for member in list(guild.members):
m_roles = member.roles
found = [r for r in m_roles if r.id in color_ids]
if not found:
color = choice(color_ids)
role = filter(lambda r: r.id == color, roles)
try:
await member.add_roles(next(role))
colored += 1
except discord.errors.Forbidden:
return
except discord.HTTPException:
continue
elif len(found) > 1:
try:
removed_roles = color_ids.copy()
removed_roles.remove(found[0].id)
await member.remove_roles(*map(Snowflake, removed_roles), reason='Removing duplicate colors', atomic=False)
duplicate_colors += 1
except:
logger.exception('failed to remove duplicate colors')
await ctx.send('Colored %s user(s) without color role\n'
'Removed duplicate colors from %s user(s)' % (colored, duplicate_colors))
def setup(bot):
bot.add_cog(Colors(bot))
| eb2a96494c0975ae87c4ca2a3bc980a687aa2f47 | [
"SQL",
"Python",
"Text"
] | 20 | SQL | HonkingChamp/Not-a-bot | b1ccff84757002e7ff92c85afa972b7e661416da | e293a7b5022a9df78007a1d2ddaf01ed4db320ce |
refs/heads/master | <repo_name>Varun-Shourie/LibrarySystem<file_sep>/MP2vshourieC#/Utilities.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using static System.Console;
namespace MP2vshourie
{
class Utilities
{
public static void DisplayHeader(string displayString)
{
Write("\t\t{0}\n\n", displayString);
}
public static void InsertFiveBlankLines()
{
Write("\n\n\n\n\n");
}
public static void Pause(string displayString)
{
Write(displayString);
ReadLine();
}
// Reads a user inputted number and checks only whether if it is an integer or not.
public static int ReadInteger(string displayString)
{
int numberOfErrors = 0;
int number = 0;
Device testDevice = new Device();
bool repeatInput = false;
// Keeps track of the number of times a user inputs incorrectly formatted input.
do
{
try
{
Write(displayString);
number = Convert.ToInt16(ReadLine());
// Set false only in case the input is valid.
repeatInput = false;
}
catch (FormatException fe)
{
if (numberOfErrors == 2)
{
Write("\nUser has made too many errors in entering data. Please enter a key to exit. \n");
ReadLine();
Environment.Exit(0);
}
else
{
Write("\nInput must be a valid integer. Try again. \n\n");
// Set to true to suggest the user has made a mistake and should try again.
repeatInput = true;
numberOfErrors++;
}
}
catch(Exception e)
{
if (numberOfErrors == 2)
{
Write("\nUser has made too many errors in entering data. Please enter a key to exit. \n");
ReadLine();
Environment.Exit(0);
}
else
{
Write("\nInput must be a valid integer. Try again. \n\n");
// Set to true to suggest the user has made a mistake and should try again.
repeatInput = true;
numberOfErrors++;
}
}
} while (repeatInput);
return number;
}
// Overloaded solely for the purpose of menu input validation.
public static int ReadInteger(string displayString, int minimum, int maximum)
{
int number = 0;
number = ReadInteger(displayString);
if (number >= minimum && number <= maximum)
return number;
else
return -1;
}
public static string ReadStringInput(string displayString)
{
string userInput = "";
Write(displayString);
userInput = ReadLine();
return userInput;
}
// Returns a specific device from the ArrayList after testing whether if it can be accessed.
public static int RetrieveDeviceNumber(string displayString, ArrayList deviceList)
{
int number = 0;
Device tmpDevice = new Device();
number = ReadInteger(displayString);
// Device number is decremented by one to properly access the ArrayList.
try
{
tmpDevice = (Device) deviceList[number - 1];
return number;
}
catch (ArgumentOutOfRangeException aore)
{
Pause("\nInvalid Number.\n\nPress Enter to continue...");
return -1;
}
catch(Exception e)
{
Pause("\nInvalid Number.\n\nPress Enter to continue...");
return -1;
}
}
}
}
<file_sep>/MP2vshourieC#/LibrarySystem.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using static System.Console;
namespace MP2vshourie
{
public class LibrarySystem
{
// Used in manipulating device characteristics and storing devices for a fully functional library device checkout
// system.
private Device tmpDevice;
private ArrayList deviceList;
public LibrarySystem()
{
tmpDevice = new Device();
deviceList = new ArrayList();
}
// Adds a device object into the list of devices after reading its sku number and name from the user.
public void AddNewDevice()
{
string sku = "";
string name = "";
tmpDevice = new Device();
Utilities.DisplayHeader("Library Device Checkout System - Add New Device");
sku = Utilities.ReadStringInput("Sku: ").ToUpper();
name = Utilities.ReadStringInput("Name: ");
tmpDevice.EditDeviceInformation(sku, name);
deviceList.Add(tmpDevice);
Utilities.Pause("\nAdded " + name + " to Catalog.\nPress Enter to continue...");
}
// Adds a list of five devices with pre-set vales, thereby preventing unnecessary user input.
public void AddSampleDevices()
{
tmpDevice = new Device("6757A", "Apple 9.7-inch iPad Pro");
deviceList.Add(tmpDevice);
tmpDevice = new Device("93P51B", "Amazon Kindle Fire Kids Edition");
deviceList.Add(tmpDevice);
tmpDevice = new Device("10N8C", "LeapFrog Epic Learning Tablet");
deviceList.Add(tmpDevice);
tmpDevice = new Device("85U20", "Amazon Kindle Fire HD 8");
tmpDevice.AvailabilityStatus = false;
deviceList.Add(tmpDevice);
tmpDevice = new Device("91H2D", "HP Envy 8 Note");
deviceList.Add(tmpDevice);
}
// Allows the user to check in a device from the library system only if it exists and is already checked out.
public void CheckInDevice()
{
int deviceNumber = 0;
int userDeviceNumber = 0;
Device userPreferredDevice = new Device();
Utilities.DisplayHeader("Library Device Checkout System - Check In Devices\n");
Write("Checked out Devices\n\n");
Write("{0,-2} {1,-10} {2,-35}\n", "#", "SKU", "Name");
// Device number is incremented by one at the beginning to become meaningful to the user.
foreach(Device d in deviceList)
{
deviceNumber++;
if(!d.AvailabilityStatus)
Write("{0,-2} {1,-10} {2,-35}\n", deviceNumber, d.SkuNumber, d.DeviceName);
}
userDeviceNumber = Utilities.RetrieveDeviceNumber("\nEnter device number: ", deviceList);
if (userDeviceNumber != -1)
{
// Decremented by one to properly access the ArrayList.
userPreferredDevice = (Device) deviceList[userDeviceNumber - 1];
if (!userPreferredDevice.AvailabilityStatus)
{
userPreferredDevice.AvailabilityStatus = true;
Utilities.Pause("Device Checked In.\n\nPress Enter to continue...");
}
else
Utilities.Pause("This device is not checked out.\n\nPress Enter to continue...");
}
else
{
return;
}
}
// Allows the user to check out a device from the library system only if it exists and is available.
public void CheckoutDevice()
{
int deviceNumber = 0;
int userDeviceNumber = 0;
Device userPreferredDevice = new Device();
Utilities.DisplayHeader("Library Device Checkout System - Check Out Devices\n");
Write("Available Devices\n\n");
Write("{0,-2} {1,-10} {2,-35}\n", "#", "SKU", "Name");
// Device number is incremented before hand to become meaningful to the user.
foreach(Device d in deviceList)
{
deviceNumber++;
if (d.AvailabilityStatus)
Write("{0,-2} {1,-10} {2,-35}\n", deviceNumber, d.SkuNumber, d.DeviceName);
}
userDeviceNumber = Utilities.RetrieveDeviceNumber("\nEnter device number: ", deviceList);
if (userDeviceNumber != -1)
{
// Decremented by one to allow access to the ArrayList.
userPreferredDevice = (Device) deviceList[userDeviceNumber - 1];
if (userPreferredDevice.AvailabilityStatus)
{
userPreferredDevice.AvailabilityStatus = false;
Utilities.Pause("Device Checked Out.\n\nPress Enter to continue...");
}
else
Utilities.Pause("This device is already checked out.\n\nPress Enter to continue...");
}
else
{
return;
}
}
public ArrayList DeviceList
{
get { return DeviceList; }
set { DeviceList = value; }
}
// Displays all devices regardless of availability status.
private void DisplayAllDevices()
{
int deviceNumber = 0;
Utilities.DisplayHeader("Library Device Checkout System - List\n");
Write("{0,-2} {1,-10} {2,-35} {3,-11}\n", "#", "SKU", "Name", "Status");
// device number is incremented at the beginning to become meaningful to the user.
foreach(Device d in deviceList) {
deviceNumber++;
Write("{0,-2} {1,-10} {2,-35}", deviceNumber, d.SkuNumber, d.DeviceName);
if (d.AvailabilityStatus)
Write(" {0,-11}\n", "Available");
else
Write(" {0,-11}\n", "Checked Out");
}
}
// Simply displays the full list of devices in a manner conducive to a menu.
public void DisplayDeviceList()
{
DisplayAllDevices();
Utilities.Pause("\nPress Enter to continue...");
}
// Allows the user to alter the device's information only if the device exists.
public void EditDeviceInformation()
{
int numberOfDevices = 0;
int deviceNumber = 0;
Device userPreferredDevice = new Device();
String sku = "";
String name = "";
numberOfDevices = GetNumberOfDevices();
Utilities.DisplayHeader("Library Device Checkout System - Edit Devices\n");
DisplayAllDevices();
deviceNumber = Utilities.RetrieveDeviceNumber("\nEnter Device number to edit (" + 1 + "-" + numberOfDevices + "): ",
deviceList);
if (deviceNumber != -1)
{
sku = Utilities.ReadStringInput("Sku: ").ToUpper();
name = Utilities.ReadStringInput("Name: ");
userPreferredDevice = (Device) deviceList[deviceNumber - 1];
userPreferredDevice.EditDeviceInformation(sku, name);
Utilities.Pause("\nDevice information updated.\n\nPress Enter to continue...");
}
else
{
return;
}
}
public void ExitLibrarySystem()
{
Write("Good bye!\n");
Environment.Exit(0);
}
// Manually retrieves the number of devices in the ArrayList.
public int GetNumberOfDevices()
{
int numberOfDevices = 0;
foreach (Device d in deviceList)
numberOfDevices++;
return numberOfDevices;
}
// Reads the user choice for which option to execute in the library device checkout system.
public int ReadLibrarySystemOptions()
{
int userMenuChoice = 0;
Write("\t\tLibrary Device Checkout System\n\n");
WriteLine("1. List Devices by Title");
WriteLine("2. Add New Devices");
WriteLine("3. Edit Device Information");
WriteLine("4. Search by Device Name");
WriteLine("5. Check Out Devices");
WriteLine("6. Check In Devices");
WriteLine("7. Exit\n\n");
userMenuChoice = Utilities.ReadInteger("Select menu options 1-7: ", 1, 7);
return userMenuChoice;
}
public void SearchDeviceName()
{
string userSearch = "";
int deviceNumber = 0;
string deviceName = "";
Utilities.DisplayHeader("Library Device Checkout System - Search\n");
userSearch = Utilities.ReadStringInput("Enter Device to search for: ");
Write("\nListings for '{0}'\n", userSearch);
Write("{0,-2} {1,-10} {2,-35}\n", "#", "SKU", "Name");
// Device number is incremented in the beginning to become meaningful to the user.
// Both the user search and device name are turned into upper case for a case insensitive search.
foreach (Device d in deviceList)
{
deviceNumber++;
deviceName = d.DeviceName.ToUpper();
if (deviceName.Contains(userSearch.ToUpper()))
Write("{0,-2} {1,-10} {2,-35}\n", deviceNumber, d.SkuNumber, d.DeviceName);
}
Utilities.Pause("\nPress Enter to continue...");
}
}
}
<file_sep>/MP2vshourieC#/Menu.cs
using System;
using System.Collections.Generic;
using System.Text;
using static System.Console;
namespace MP2vshourie
{
public class Menu
{
// We only require a library system to execute the menu.
private LibrarySystem librarySystem;
public Menu()
{
librarySystem = new LibrarySystem();
}
// Displays the menu repeatedly until the user opts out of the library device checkout system.
private void DisplayMenu()
{
bool repeatInput = false;
int userMenuChoice = 0;
int numberOfErrors = 0;
librarySystem.AddSampleDevices();
do
{
repeatInput = true;
userMenuChoice = librarySystem.ReadLibrarySystemOptions();
// Resets the number of errors if the user entered correct input.
if (userMenuChoice >= 1 && userMenuChoice <= 6)
{
Utilities.InsertFiveBlankLines();
numberOfErrors = 0;
}
// The user's selection in the menu results in the option's execution from the menu.
switch (userMenuChoice)
{
case 1:
librarySystem.DisplayDeviceList();
Utilities.InsertFiveBlankLines();
break;
case 2:
librarySystem.AddNewDevice();
Utilities.InsertFiveBlankLines();
break;
case 3:
librarySystem.EditDeviceInformation();
Utilities.InsertFiveBlankLines();
break;
case 4:
librarySystem.SearchDeviceName();
Utilities.InsertFiveBlankLines();
break;
case 5:
librarySystem.CheckoutDevice();
Utilities.InsertFiveBlankLines();
break;
case 6:
librarySystem.CheckInDevice();
Utilities.InsertFiveBlankLines();
break;
case 7:
librarySystem.ExitLibrarySystem();
break;
default:
if(numberOfErrors == 2)
{
WriteLine("\nUser has made too many errors in entering data. Please enter a key to exit.");
ReadLine();
Environment.Exit(0);
}
numberOfErrors++;
Utilities.InsertFiveBlankLines();
break;
}
} while (repeatInput);
}
public static void Main(string[] args)
{
Menu menu = new Menu();
menu.DisplayMenu();
}
}
}
<file_sep>/README.md
MiniProject-2
Console Application Using OOP Concepts in which we manage books and tablets to be checked out in a library.
<file_sep>/MP2vshourie/src/Utilities.java
// <NAME>, MP2, CIS340, Tuesday/Thursday, 3:00PM-4:15PM
import java.util.Scanner;
public class Utilities {
// Made static so only one copy remains throughout the entire program.
private static Scanner scanner = new Scanner(System.in);
// Prints a neatly preformatted header for the program.
public static void displayHeader(String displayString) {
System.out.printf("\t\t%s\n\n", displayString);
}
// No setter is included for this getter since we do not need to alter the scanner in any way.
public static Scanner getScanner() {
return scanner;
}
public static void insertFiveBlankLines() {
System.out.print("\n\n\n\n\n\n");
}
// Inserts a prompt for a pause in the program.
public static void pause(String displayString) {
System.out.print(displayString);
scanner.nextLine();
}
// Reads an integer from the user with extensive input validation.
public static int readInteger(String displayString) {
int numberOfErrors = 0;
int number = 0;
boolean repeatInput = false;
// Keeps track of the number of times the user puts in incorrectly formatted input.
do {
try {
System.out.print(displayString);
number = Integer.parseInt(scanner.nextLine());
// Set false only in case the user input is valid.
repeatInput = false;
}
catch(NumberFormatException e) {
if(numberOfErrors == 2) {
System.out.println("\nUser has made too many errors in entering data. Please enter a key to exit.\n");
scanner.nextLine();
System.exit(0);
}
else {
System.out.println("\nInput must be a valid integer. Try again.\n");
// Set to true to suggest the user has made a mistake and should try again.
repeatInput = true;
numberOfErrors++;
}
}
} while (repeatInput);
return number;
}
// Overloaded to validate for indexes which are out of bounds.
public static int readInteger(String displayString, int minimum, int maximum) {
int userInput = 0;
userInput = readInteger(displayString);
// -1 is returned to signify an error in user input.
if(userInput < minimum || userInput > maximum) {
return -1;
}
return userInput;
}
// Reads string input for a user and returns it to another part of the application.
public static String readStringInput(String displayString) {
String userInput = "";
System.out.print(displayString);
userInput = scanner.nextLine();
return userInput;
}
}
<file_sep>/MP2vshourieC#/Device.cs
using System;
namespace MP2vshourie
{
public class Device
{
// The three aspects of a device which the library device checkout system will track.
private string skuNumber;
private string deviceName;
private bool availabilityStatus;
// For the three properties present, I chose not to abbreviate it further since this likely allows for easier maintenance.
public bool AvailabilityStatus
{
get { return availabilityStatus; }
set { availabilityStatus = value; }
}
// By default, we assume the device is automatically available when added.
public Device(string skuNumber = "", string deviceName = "")
{
SkuNumber = skuNumber;
DeviceName = deviceName;
AvailabilityStatus = true;
}
public string DeviceName
{
get { return deviceName; }
set { deviceName = value; }
}
public void EditDeviceInformation(string skuNumber, string deviceName)
{
SkuNumber = skuNumber;
DeviceName = deviceName;
}
public string SkuNumber
{
get { return skuNumber; }
set { skuNumber = value; }
}
}
}
| 4a951ec80fee6e4a2112b5cd915ff29eb651c822 | [
"Markdown",
"C#",
"Java"
] | 6 | C# | Varun-Shourie/LibrarySystem | 0808a40dd2e2671f99f40f68b2aa936fe6a3c7b5 | d457a29a2d394cd5ae39cf7b29fa89c1c3e86a8c |
refs/heads/master | <repo_name>DeftPenk/datasciencecapstone<file_sep>/ui.R
suppressWarnings(library(shiny))
suppressWarnings(library(markdown))
shinyUI(navbarPage("Coursera's Data Science Capstone: Final Project",
tabPanel("Next Word Predictor",
HTML("<strong>Author: <NAME></strong>"),
br(),
HTML("<strong>Date: 25 September 2020</strong>"),
br(),
# Sidebar
sidebarLayout(
sidebarPanel(
helpText("This application takes your string and predict the next word to your string"),
textInput("inputString", "Enter your word or partial phrase here",value = ""),
helpText("Once you finished typing your word or phrase, please click on the below button NextWord to suggest next expected word for your word or phrase"),
submitButton('NextWord'),
br(),
br(),
br(),
br()
),
mainPanel(
h2("The suggested next word for your word or phrase is"),
verbatimTextOutput("prediction"),
strong("You entered the following word or phrase as Input to the application:"),
tags$style(type='text/css', '#text1 {background-color: rgba(255,255,0,0.40); color: blue;}'),
textOutput('text1')
)
)
),
tabPanel("Overview",
mainPanel(
includeMarkdown("Overview.md"),
)
),
tabPanel("Instructions",
mainPanel(
includeMarkdown("Instructions.md")
)
)
)
) | 2e01f2c82342e7d8765bd8aebd7a8cb207671758 | [
"R"
] | 1 | R | DeftPenk/datasciencecapstone | 701c5a4cfea93d8cb2bd777e1acd12a0b9d5f37f | eb42f839da7587f9061225de79dbd7eb88b4fb2d |
refs/heads/master | <repo_name>knmurphy/UnicornLive-workshop<file_sep>/src/components/Admin/index.jsx
/* eslint no-param-reassign: ["error", { "props": false }] */
import React, { Component } from 'react';
import './index.css';
import JsonTable from 'ts-react-json-table';
import Popup from 'react-popup';
/* Location 1 */
/* Location 3 */
import myJson from './questions.json';
const columns = [{
key: 'Question',
label: 'Questions:',
}, {
key: 'button1',
label: ' ',
cell: () => <button type="button">Post Question</button>,
}, {
key: 'button2',
label: ' ',
cell: () => <button type="button">Post Answer</button>,
}];
class Content extends Component {
tableSettings = {
header: false,
}
handleQuestionClick = (rowData) => {
/* Location 4 */
}
handleAnswerClick = (rowData) => {
/* Location 5 */
}
onClickCell = (event, columnName, rowData) => {
if (columnName === 'button1') {
this.handleQuestionClick(rowData);
} else if (columnName === 'button2') {
this.handleAnswerClick(rowData);
}
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to Unicorn Live</h1>
</header>
<JsonTable rows={myJson.Questions} columns={columns} settings={this.tableSettings} onClickCell={this.onClickCell} className="tabelsa" />
</div>
);
}
}
/* Location 2 */
export default Content;
<file_sep>/src/components/Game/index.jsx
import React, { Component } from 'react';
/* Location 8 */
/* Location 10 */
/* Location 15 */
import Video from '../Video';
import Modal from '../Modal';
class Game extends Component {
constructor(props) {
super(props);
this.state = {
modalVisible: false,
drawInfo: {},
};
}
componentDidMount() {
this.listenForQuestions();
this.listenForAnswers();
this.setupClient();
}
setupClient = () => {
/* Location 16 */
}
listenForQuestions = () => {
const self = this;
/* Location 11 */
}
listenForAnswers = () => {
const self = this;
/* Location 12 */
}
callbackFunction = (childData) => {
/* Location 14 */
}
render() {
/* Location 9 */
const url = '';
const { modalVisible, drawInfo } = this.state;
return (
<div className="game-container">
<Video
controls
techOrder={['AmazonIVS']}
src={url}
bigPlayButton={false}
parentCallback={this.callbackFunction}
autoplay
/>
<Modal className={modalVisible ? 'show' : 'hidden'} drawInfo={drawInfo} />
</div>
);
}
}
export default Game;
| c6d7b6dd2951f4f94714efaa59329341bcd340d7 | [
"JavaScript"
] | 2 | JavaScript | knmurphy/UnicornLive-workshop | 57e7c7cf47eab4c4dc7b28fb201f6fbc6589bc1e | 2b21635fe915a65f72e418c7402dc6fb654e345e |
refs/heads/master | <repo_name>liuhr-python/drf-homework06<file_sep>/api/views.py
import re
#
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated # 导入权限模块
from rest_framework_jwt.authentication import JSONWebTokenAuthentication # 导入JWT模块
from api.authentication import JWTAuthentication #导入自定义校验模块
from api.serializers import UserModelSerializer #导入反序列化器
from utils.response import APIResponse
# 获取token 两种url
class UserAPIV(APIView):
permission_classes = [IsAuthenticated] # 权限:只允许认证通过的用户访问 游客无权访问
authentication_classes = [JWTAuthentication] # 自定义校验模块
# authentication_classes = [JSONWebTokenAuthentication] # 系统校验模块
def get(self, request, *args, **kwargs):
return APIResponse(results={"username": request.user.username})
# 多方式登录签发token
class MoreLoginAPIView(APIView):
authentication_classes = []
permission_classes = []
def post(self, request, *args, **kwargs):
user_ser = UserModelSerializer(data=request.data)
user_ser.is_valid(raise_exception=True)
return APIResponse(data_message="成功", token=user_ser.token, results=UserModelSerializer(user_ser.obj).data)
<file_sep>/api/urls.py
from django.urls import path
from django.conf.urls import url
from rest_framework_jwt.views import ObtainJSONWebToken, obtain_jwt_token
from api import views
urlpatterns = [
url(r"login/", ObtainJSONWebToken.as_view()), # 无视图 直接获取token,需调掉as_view
url(r"obt/", obtain_jwt_token), # 无视图 直接获取token,无需调掉as_view
path("user/", views.UserAPIV.as_view()), # 通过user 获取 token
path("check/", views.MoreLoginAPIView.as_view()), # 多方式登录签发token
]
| 3c74ff1c76f94c61d0ad6db3d193e883dddb98e7 | [
"Python"
] | 2 | Python | liuhr-python/drf-homework06 | 0c94e50d47747cb39adf1730263292bb9b0457b0 | e252532b62c49b1d48c6eafe2ba6b08c2e220412 |
refs/heads/master | <file_sep><!doctype html>
<html>
<head> <h1 align=center>Read From Player Table</h1><head>
<body>
<style>
.container {
width: 500px;
clear: both;
}
.container input {
width: 100%;
clear: both;
}
</style>
Please Enter a PlayerID to be read from the Rewards Player Table
<form action="#" method="get">
<div class="container">
<label>PlayerID</label>
<input type="text" name="playerID" >
<input type="submit" name="submit" >
</div>
</form>
<?php
$conn = mysqli_connect("localhost", "cs411tech_testtest", "%Gd~zouycV]l", "cs411tech_dbo");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$playerID = $_GET['playerID'];
$sql="SELECT * FROM `cs411tech_dbo.AwardsPlayers` where playerID='$playerID'";
$result = $conn->query($sql);
if(isset($_GET['submit'])){
if (mysqli_query($conn, $sql)) {
echo "Record from table:";
echo"<br></br>";
}
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "<br> AwardID: ". $row["awardID"]. " lgID: ". $row["lgID"]. " Notes:" . $row["notes"]. " PlayerID:" . $row["playerID"]. " Tie:" . $row["tie"] . " yearID:" . $row["yearID"]."</br>";
}
}else
{
echo "No results from query";
}
}
mysqli_close($conn);
?>
<body>
</form>
</html><file_sep> <?php
//query 1
$connect = mysqli_connect("localhost", "cs411tech_testtest", "%Gd~zouycV]l", "cs411tech_dbo");
$query = "SELECT peo.`nameFirst` as FirstName, (`tenureInDays`/365) as TenureYear FROM `playerTenure` pt
join `cs411tech_dbo.People` peo on pt.`playerID` = peo.`playerID` order by `tenureInDays` DESC limit 25";
$result = mysqli_query($connect, $query);
//query 2
$query2 = "SELECT lgID, count(*) as number FROM `cs411tech_dbo.AwardsPlayers` GROUP BY lgID";
$result2 = mysqli_query($connect, $query2);
//query 3
$query3 = "SELECT P.`nameFirst` as Player_NM, count(A.`awardID`) as AWD_CNT FROM `cs411tech_dbo.People` P
join `cs411tech_dbo.AwardsPlayers` A on P.`playerID` = A.playerID
group by P.`nameFirst`
order by AWD_CNT desc
limit 10";
$result3 = mysqli_query($connect, $query3);
//query 4
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(DrawColumn);
function DrawColumn()
{
var OurChart = google.visualization.arrayToDataTable([
['FirstName','TenureYear'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["FirstName"]."', ".$row["TenureYear"]."],";
}
?>
]);
var t = {
title: 'Player Tenure'
};
var chart = new google.visualization.LineChart(document.getElementById('columnchart_values'));
chart.draw(OurChart, t);
}
google.charts.setOnLoadCallback(DrawC2);
function DrawC2()
{
var OurChart = google.visualization.arrayToDataTable([
['lgID', 'Number'],
<?php
while($row = mysqli_fetch_array($result2))
{
echo "['".$row["lgID"]."', ".$row["number"]."],";
}
?>
]);
var ti = {
title: 'Number of Players in each League',
};
var chart = new google.visualization.ColumnChart(document.getElementById('cc'));
chart.draw(OurChart, ti);
}
google.charts.setOnLoadCallback(DoC);
function DoC()
{
var info = google.visualization.arrayToDataTable([
['Player_NM', 'Number'],
<?php
while($row = mysqli_fetch_array($result3))
{
echo "['".$row["Player_NM"]."', ".$row["AWD_CNT"]."],";
}
?>
]);
var ti = {
title: 'Top 10 Awarded Players',
};
var chart = new google.visualization.ColumnChart(document.getElementById('view_q'));
chart.draw(info, ti);
}
</script>
</head>
<body>
<br /><br />
<div style="width:900px;">
<br />
<div id="columnchart_values" style="width: 900px; height: 500px;"></div>
</div>
<div style="width:900px;">
<br />
<div id="cc" style="width: 900px; height: 500px;"></div>
</div>
<div style="width:900px;">
<br />
<div id="view_q" style="width: 900px; height: 500px;"></div>
</div>
</body>
</html> <file_sep><!doctype html>
<html>
<head> <h1 align=center>Insert into Rewards Player Table</h1><head>
<body>
<style>
.container {
width: 500px;
clear: both;
}
.container input {
width: 100%;
clear: both;
}
</style>
<form action="#" method="get">
<div class="container">
<label>awardID</label>
<input type="text" name="awardID" >
<label>lgID</label>      
<input type="text" name="lgID" >
<label>Notes</label>
<input type="text" name="Notes" >
<label>playerID</label>
<input type="text" name="playerID" >
<label>Tie</label>   
<input type="text" name="Tie" >
<label>YearID</label>
<input type="text" name="YearID" >
<input type="submit" name="submit" >
</div>
<?php
$conn = mysqli_connect("localhost", "cs411tech_testtest", "%Gd~zouycV]l", "cs411tech_dbo");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$Award=$_GET['awardID'];
$lgID=$_GET['lgID'];
$Notes=$_GET['Notes'];
$playerID=$_GET['playerID'];
$Tie=$_GET['Tie'];
$YearID=$_GET['YearID'];
//$sql=$conn->prepare("INSERT INTO `cs411tech_dbo.AwardsPlayers` (playerID, awardID, yearID, lgID, tie, notes) VALUES (?,?,?,?,?,?)");
//$sql->bind_param("sss", $Award, $lgID, $Notes,$playerID,$Tie,$YearID);
//$sql->execute();
$sql="INSERT INTO `cs411tech_dbo.AwardsPlayers` (playerID, awardID, yearID, lgID, tie, notes) VALUES ('$playerID','$Award','$YearID','$lgID','$Tie','$Notes')";
if (!($stmt = $conn->prepare("INSERT INTO `cs411tech_dbo.AwardsPlayers` (playerID, awardID, yearID, lgID, tie, notes) VALUES (?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if(isset($_GET['submit'])){
if (mysqli_query($conn, $sql)) {
echo "Successfully Inserted Record";
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
<body>
</form>
</html><file_sep><?php
//query 1
$connect = mysqli_connect("localhost", "cs411tech_testtest", "%Gd~zouycV]l", "cs411tech_dbo");
$query = "SELECT DISTINCTROW TEM.`name` as NAME, count(`playerID`) as PLYR_CNT FROM `cs411tech_dbo.Batting` BAT
join (SELECT distinct `teamID`, `name` FROM `cs411tech_dbo.Teams`) TEM on BAT.`teamID` = TEM.`teamID`
group by NAME
order by PLYR_CNT desc
limit 12";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(DrawColumn);
function DrawColumn()
{
var OurChart = google.visualization.arrayToDataTable([
['NAME','PLYR_CNT'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["NAME"]."', ".$row["PLYR_CNT"]."],";
}
?>
]);
var t = {
title: 'Player Distribution'
};
var chart = new google.visualization.PieChart(document.getElementById('columnchart_values'));
chart.draw(OurChart, t);
}
</script>
</head>
<body>
<br /><br />
<div style="width:900px;">
<br />
<div id="columnchart_values" style="width: 900px; height: 500px;"></div>
</div>
</body>
</html> <file_sep><html>
<head> <h1 align=center>Trade Players to other Teams</h1><head>
<body>
<style>
.container {
width: 500px;
clear: both;
}
.container input {
width: 100%;
clear: both;
}
</style>
<form action="#" method="post">
<?php
$conn = mysqli_connect("localhost", "cs411tech_testtest", "%Gd~zouycV]l", "cs411tech_dbo");
$sql = "select playerID from `cs411tech_dbo.People`";
$result = mysqli_query($conn, $sql);
?>
<div>
<select name="PlayerID">
<?php
while($rows = $result->fetch_assoc())
{
$player = $rows['playerID'];
echo "<option value='$player'>$player</option>";
}
echo "</select>";
//$sql2 = "select teamID from `cs411tech_dbo.Teams`";
//$result2 = mysqli_query($conn, $sql);
//echo "<input type=submit name=submit>";
?>
<select name="TeamID">
<?php
$sql2 = "select teamID from `cs411tech_dbo.Teams`";
$result2 = mysqli_query($conn, $sql2);
while($rows = $result2->fetch_assoc())
{
$team = $rows['teamID'];
echo "<option value='$team'>$team</option>";
}
echo "</select>";
//$sql2 = "select teamID from `cs411tech_dbo.Teams`";
//$result2 = mysqli_query($conn, $sql);
//echo "<input type=submit name=submit>";
?>
<input type="submit" name="submit">
</div>
<?php
$playerID = $_POST['PlayerID'];
$teamID = $_POST['TeamID'];
//echo "hello" .$playerID .$teamID;
$sql3 = "select teamID from `cs411tech_dbo.Fielding` where playerID = '$playerID' order by yearID desc limit 1";
$result3 = mysqli_query($conn, $sql3);
//echo "test";
while($rows = $result3->fetch_assoc())
{
$team2 = $rows['teamID'];
//echo $team2;
$sql4="INSERT INTO TradedPlayers (NewTeamID, OldTeamID, playerID) VALUES ('$teamID','$team2','$playerID')";
if (mysqli_query($conn, $sql4)) {
echo "Successfully Inserted Record: this was inserted to TradedPlayers table and player was tradded to : '$teamID' and updated in fielding table. ";
$sql5="Update`cs411tech_dbo.Fielding` set teamID='$teamID' where playerID ='$playerID' order by yearID DESC,POS limit 1";
if (mysqli_query($conn, $sql5)) {
echo "Successfully Updated Record in Fielding table ".$teamID;
}
}
else{
echo "failed";
}
}
$sql6 = "SELECT * FROM `cs411tech_dbo.Fielding` where playerID='$playerID' order by yearID DESC, POS limit 1";
$result4 = mysqli_query($conn, $sql6);
//insert statement
//update statement
/*if(isset = $_POST(['PlayerID']))
{
echo "hello" .$playerID;
}*/
?>
<div class="container">
<div >
<table >
<tr>
<th>Player ID</th>
<th>Team ID</th>
</tr>
<?php
while($row = mysqli_fetch_array($result4))
{
?>
<tr>
<td><?php echo $row["playerID"]; ?></td>
<td><?php echo $row["teamID"];?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</form>
<body>
<html><file_sep><!doctype html>
<html>
<head> <h1 align=center>Comments Blog</h1><head>
<body>
<style>
.container {
width: 500px;
clear: both;
}
.container input {
width: 100%;
clear: both;
}
.content {
margin-top:auto;
margin-bottom:auto;
text-align:center;
}
.center {
text-align: center;
border: 3px solid red;
}
</style>
<form action="#" method="get">
<div class="container">
<label>PlayerID</label>
<input type="text" name="playerID" >
<label>Comment to add</label>      
<input type="text" name="Comment" >
<input type="submit" name="submit" >
</div>
<?php
$conn = mysqli_connect("localhost", "cs411tech_testtest", "%Gd~zouycV]l", "cs411tech_dbo");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$PlayerID=$_GET['playerID'];
$Comment=$_GET['Comment'];
//echo $PlayerID;
//echo $Comment;
//$sql=$conn->prepare("INSERT INTO `cs411tech_dbo.AwardsPlayers` (playerID, awardID, yearID, lgID, tie, notes) VALUES (?,?,?,?,?,?)");
//$sql->bind_param("sss", $Award, $lgID, $Notes,$playerID,$Tie,$YearID);
//$sql->execute();
$sql="INSERT INTO Comments (playerID, Comm) VALUES ('$PlayerID','$Comment')";
if(isset($_GET['submit'])){
if (mysqli_query($conn, $sql)) {
echo "Successfully Inserted Record";
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
$sql2 = "Select * from Comments C inner join `cs411tech_dbo.People` P on P.playerID = C.playerID where C.playerID='$PlayerID'";
$result2 = mysqli_query($conn, $sql2);
$sql3 = "Select * from Comments";
$result3= mysqli_query($conn, $sql3);
?>
<div class="container">
<div >
<table >
<tr>
<th>Player ID</th>
<th>Comment</th>
</tr>
<?php
while($row = mysqli_fetch_array($result2))
{
?>
<tr>
<td><?php echo $row["playerID"]; ?></td>
<td><?php echo $row["Comm"];?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<div class="center" >
<div class="center">
<table >
<tr>
<th>Player ID</th>
<th>Comment</th>
</tr>
<?php
while($row = mysqli_fetch_array($result3))
{
?>
<tr>
<td><?php echo $row["playerID"]; ?></td>
<td><?php echo $row["Comm"];?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<?php
mysqli_close($conn);
?>
<body>
</form>
</html> | f22608cc71e6e8d9ac3fa0c6926c6eba356267e9 | [
"PHP"
] | 6 | PHP | GregoryScottSelf/CS411Project_2020 | 6334171fec7c7ac908b24333c8beb9fd48df0bee | 2a17b042d87f0ffae535c6bec51da7a2dd12e364 |
refs/heads/master | <repo_name>agcastillo/ITPCS_Benchmarking<file_sep>/resources/parse_results.py
import sys
import fileinput
import os
iterations = 0
dim_matrix = []
# Get parsing information from parse_info.txt
f = open('parse_info.txt','r')
line_split = f.read().split('\n')
iterations = int(line_split[0])
dim_matrix = [int(x) for x in line_split[1].split(',')[:-1]]
paths = line_split[2].split(',')[:-1]
paths = [x + "output_files/" for x in paths]
print("Parsing results for " + str(iterations) + " iterations of the following dimensions: ")
print(dim_matrix)
f = open("results.txt", 'w')
for path in paths:
f.write("***********************************************************************\n")
f.write("Test Location: " + path[:-13] + "\n")
f.write("***********************************************************************\n")
for i in range(iterations):
f.write( "Test Iteration: " + str(i)+ "\n")
for dim in dim_matrix:
# These arrays will hold all the start_time and end_time printf statements from each execution of our IT files
start_times = []
end_times = []
filename = path + "slurm_" + str(dim) + "_" + str(i) + ".out"
exists = os.path.isfile(filename)
if exists:
for line in open( filename, 'r'):
# Appent to either array based on which they belong to, handle error where two printfs occured on top of each other
if "Start Time:" in line:
try:
line = line[11:-1]
line.strip()
start_times.append(int(line))
except Exception:
continue
elif "End Time:" in line:
try:
line = line[9:-1]
line.strip()
end_times.append(int(line))
except Exception:
continue
# Get average of each array and print the diffence between the start time and end time (in milliseconds)
if (len(start_times) != 0) & (len(end_times) != 0):
avg_start = sum(start_times)/len(start_times)
avg_end = sum(end_times)/len(end_times)
delta = avg_end - avg_start
f.write("\t| Dim = " + str(dim) + ", Time (ms) = " + str(delta)+ "\n")
else:
# If the job was aborted or didn't have any valid output for some reason, print NA for that dimension
f.write("\t| Dim = " + str(dim) + ", Time (ms) = NA"+ "\n")
else:
print( filename + " was not found")
f.write("\n")
<file_sep>/resources/run_tests.py
import fileinput
import sys
import os
import subprocess
import re
# Directories where your .it files can be found, each directory should only have *one* .it file and *one* .map file
# Results from the tests will be stored in the respective directory as well
test_directories = ["ITPCS_Benchmarking/Test1/", "ITPCS_Benchmarking/Test2/", "ITPCS_Benchmarking/Test3/", "ITPCS_Benchmarking/Test4/", "ITPCS_Benchmarking/Test5/"]
# Number of Tests you want to conduct
num_iterations = 3
# Array dimensions you want to test with, assuming your .it file takes a dim_matrix variable
dim_matrix = [80000, 160000, 240000, 320000,400000,480000, 560000, 640000, 720000]
# Node count and max job time for each slurm job submission
node_count = "20"
time_allowance = "00:05:00"
# Check if we need to make the compiler
# If not, just make sure gompi module is loaded
exists = os.path.isfile('sicc')
if (exists):
os.system("module load gompi/5.4.0_2.1.5")
else:
os.system("make -f MakeFile-Compiler clean")
os.system("module load gompi/5.4.0_2.1.5")
os.system("make -f MakeFile-Compiler")
# Copy the results parser into the current directory
subprocess.call(["cp" ,"ITPCS_Benchmarking/resources/parse_results.py", "."])
for test_directory in test_directories:
if not test_directory.endswith("/"):
test_directory += "/"
# Make directories to store slurm files and output files in
subprocess.call(["mkdir", test_directory + "slurm_files"])
subprocess.call(["mkdir", test_directory + "output_files"])
# Find .it and .map files in the given directory
# Skip this directory if either file doesn't exist
file_name = None
map_name = None
for file in os.listdir(test_directory):
if file.endswith(".it"):
file_name = file
print(file_name)
elif file.endswith(".map"):
map_name = file
print(map_name)
if (file_name) is None:
print("No file with .it extension found in " + test_directory)
continue
elif map_name is None:
print("No file with .map extension found in " + test_directory)
continue
# Compile the IT file and move the fully compiled .o file to the test directory
subprocess.call(["make", "clean", "-f", "MakeFile-Executable"])
subprocess.call(["./sicc",test_directory + file_name,"ITPCS_Benchmarking/resources/rivana-cluster.ml", "ITPCS_Benchmarking/resources/rivana-cluster.cn", test_directory + map_name])
subprocess.call(["make", "-f", "MakeFile-Executable"])
subprocess.call(["mv","bin/it-program.o",test_directory])
# Job submissions happen here
for i in range(num_iterations):
for dim in dim_matrix:
prefix = file_name[:-3] + "_" + str(dim) + "_" + str(i)
# Create a new slurm file for each compiled IT file, for each iteration, and for each matrix dimension we want to test
slurm_file = open(prefix + ".slurm",'w')
slurm_file.write("#!/bin/bash"
+"\n#SBATCH --nodes="+node_count
+"\n#SBATCH --ntasks="+ node_count
+"\n#SBATCH --cpus-per-task=20"
+"\n#SBATCH --exclusive"
+"\n#SBATCH --time=" + time_allowance
+"\n#SBATCH --partition=parallel"
+"\n#SBATCH --account=crosscampusgrid"
+"\n#SBATCH --output=" + test_directory + "output_files/slurm_" + str(dim) + "_" + str(i) + ".out"
+"\nmodule load gompi/5.4.0_2.1.5"
+"\nmodule load gcc"
+"\nmodule load openmpi"
+"\nmpirun " + test_directory + "it-program.o matrix_dim=" + str(dim)
+"\n")
slurm_file.close()
# Submit job and move slurm file to the slurm_files directory
subprocess.call(["sbatch", prefix + ".slurm"])
subprocess.call(["mv", prefix + ".slurm", test_directory + "slurm_files/"])
# Create a file that will hold information necessary for parsing
parse_file = open("parse_info.txt", 'w')
dims = ""
directories = ""
for dim in dim_matrix:e
dims += str(dim) + ","
for d in test_directories:
directories += d + ","
parse_file.write(str(num_iterations) + "\n" + dims + "\n" + directories)
parse_file.close()
# Signal script end
print("Successfully submitted jobs for " + file_name)
| 7d57279c2c7bb54733379a538d0ebe5ad51d346f | [
"Python"
] | 2 | Python | agcastillo/ITPCS_Benchmarking | fb8c6a137eaa34ae79a8585b0a15be40aa5903c8 | 2a739fecf060ed4c5f314b33b87363b7d53f978a |
refs/heads/master | <file_sep>package delegated
import (
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
authorizationapi "github.com/openshift/origin/pkg/authorization/api"
"github.com/openshift/origin/pkg/cmd/server/bootstrappolicy"
projectapi "github.com/openshift/origin/pkg/project/api"
templateapi "github.com/openshift/origin/pkg/template/api"
)
const (
ProjectNameParam = "PROJECT_NAME"
ProjectDisplayNameParam = "PROJECT_DISPLAYNAME"
ProjectDescriptionParam = "PROJECT_DESCRIPTION"
ProjectAdminUserParam = "PROJECT_ADMIN_USER"
)
var (
parameters = []string{ProjectNameParam, ProjectDisplayNameParam, ProjectDescriptionParam, ProjectAdminUserParam}
)
func DefaultTemplate() *templateapi.Template {
ret := &templateapi.Template{}
ret.Name = "project-request"
ret.Namespace = kapi.NamespaceDefault
project := &projectapi.Project{}
project.Name = "${" + ProjectNameParam + "}"
project.Annotations = map[string]string{
"description": "${" + ProjectDescriptionParam + "}",
"displayName": "${" + ProjectDisplayNameParam + "}",
}
ret.Objects = append(ret.Objects, project)
binding := &authorizationapi.RoleBinding{}
binding.Name = "admins"
binding.Namespace = "${" + ProjectNameParam + "}"
binding.Users = util.NewStringSet("${" + ProjectAdminUserParam + "}")
binding.RoleRef.Name = bootstrappolicy.AdminRoleName
ret.Objects = append(ret.Objects, binding)
for _, parameterName := range parameters {
parameter := templateapi.Parameter{}
parameter.Name = parameterName
ret.Parameters = append(ret.Parameters, parameter)
}
return ret
}
<file_sep>package osdn
import (
"fmt"
"github.com/golang/glog"
"strings"
kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
kclient "github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util/exec"
"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
"github.com/openshift/openshift-sdn/ovssubnet"
osdnapi "github.com/openshift/openshift-sdn/pkg/api"
osclient "github.com/openshift/origin/pkg/client"
"github.com/openshift/origin/pkg/sdn/api"
)
type OsdnRegistryInterface struct {
oClient osclient.Interface
kClient kclient.Interface
}
func NetworkPluginName() string {
return "redhat/openshift-ovs-subnet"
}
func Master(osClient osclient.Client, kClient kclient.Client, clusterNetwork string, clusterNetworkLength uint) {
osdnInterface := newOsdnRegistryInterface(osClient, kClient)
// get hostname
output, err := exec.New().Command("hostname", "-f").CombinedOutput()
if err != nil {
glog.Fatalf("SDN initialization failed: %v", err)
}
host := strings.TrimSpace(string(output))
kc, err := ovssubnet.NewKubeController(&osdnInterface, host, "")
if err != nil {
glog.Fatalf("SDN initialization failed: %v", err)
}
kc.StartMaster(false, clusterNetwork, clusterNetworkLength)
}
func Node(osClient osclient.Client, kClient kclient.Client, hostname string, publicIP string) {
osdnInterface := newOsdnRegistryInterface(osClient, kClient)
kc, err := ovssubnet.NewKubeController(&osdnInterface, hostname, publicIP)
if err != nil {
glog.Fatalf("SDN initialization failed: %v", err)
}
kc.StartNode(false, false)
}
func newOsdnRegistryInterface(osClient osclient.Client, kClient kclient.Client) OsdnRegistryInterface {
return OsdnRegistryInterface{&osClient, &kClient}
}
func (oi *OsdnRegistryInterface) InitSubnets() error {
return nil
}
func (oi *OsdnRegistryInterface) GetSubnets() (*[]osdnapi.Subnet, error) {
hostSubnetList, err := oi.oClient.HostSubnets().List()
if err != nil {
return nil, err
}
// convert HostSubnet to osdnapi.Subnet
subList := make([]osdnapi.Subnet, 0)
for _, subnet := range hostSubnetList.Items {
subList = append(subList, osdnapi.Subnet{Minion: subnet.HostIP, Sub: subnet.Subnet})
}
return &subList, nil
}
func (oi *OsdnRegistryInterface) GetSubnet(minion string) (*osdnapi.Subnet, error) {
hs, err := oi.oClient.HostSubnets().Get(minion)
if err != nil {
return nil, err
}
return &osdnapi.Subnet{Minion: hs.Host, Sub: hs.Subnet}, nil
}
func (oi *OsdnRegistryInterface) DeleteSubnet(minion string) error {
return oi.oClient.HostSubnets().Delete(minion)
}
func (oi *OsdnRegistryInterface) CreateSubnet(minion string, sub *osdnapi.Subnet) error {
hs := &api.HostSubnet{
TypeMeta: kapi.TypeMeta{Kind: "HostSubnet"},
ObjectMeta: kapi.ObjectMeta{Name: minion},
Host: minion,
HostIP: sub.Minion,
Subnet: sub.Sub,
}
_, err := oi.oClient.HostSubnets().Create(hs)
return err
}
func (oi *OsdnRegistryInterface) WatchSubnets(receiver chan *osdnapi.SubnetEvent, stop chan bool) error {
// double go :(
revision := ""
wi, err := oi.oClient.HostSubnets().Watch(revision)
if err != nil {
return err
}
go func() {
for {
ev := <-wi.ResultChan()
switch ev.Type {
case watch.Added:
// create SubnetEvent
hs := ev.Object.(*api.HostSubnet)
receiver <- &osdnapi.SubnetEvent{Type: osdnapi.Added, Minion: hs.Host, Sub: osdnapi.Subnet{Minion: hs.HostIP, Sub: hs.Subnet}}
case watch.Deleted:
hs := ev.Object.(*api.HostSubnet)
receiver <- &osdnapi.SubnetEvent{Type: osdnapi.Deleted, Minion: hs.Host, Sub: osdnapi.Subnet{Minion: hs.HostIP, Sub: hs.Subnet}}
case watch.Modified:
hs := ev.Object.(*api.HostSubnet)
receiver <- &osdnapi.SubnetEvent{Type: osdnapi.Added, Minion: hs.Host, Sub: osdnapi.Subnet{Minion: hs.HostIP, Sub: hs.Subnet}}
case watch.Error:
fmt.Errorf("Error in watching subnets")
return
}
}
}()
return nil
}
func (oi *OsdnRegistryInterface) InitMinions() error {
// return no error, as this gets initialized by apiserver
return nil
}
func (oi *OsdnRegistryInterface) GetMinions() (*[]string, error) {
nodes, err := oi.kClient.Nodes().List(labels.Everything(), fields.Everything())
if err != nil {
return nil, err
}
// convert kapi.NodeList to []string
minionList := make([]string, 0)
for _, minion := range nodes.Items {
minionList = append(minionList, minion.Name)
}
return &minionList, nil
}
func (oi *OsdnRegistryInterface) CreateMinion(minion string, data string) error {
return fmt.Errorf("Feature not supported in native mode. SDN cannot create/register minions.")
}
func (oi *OsdnRegistryInterface) WatchMinions(receiver chan *osdnapi.MinionEvent, stop chan bool) error {
wi, err := oi.kClient.Nodes().Watch(labels.Everything(), fields.Everything(), "0")
if err != nil {
return err
}
go func() {
for {
ev := <-wi.ResultChan()
switch ev.Type {
case watch.Added:
// create minionEvent
node := ev.Object.(*kapi.Node)
receiver <- &osdnapi.MinionEvent{Type: osdnapi.Added, Minion: node.ObjectMeta.Name}
case watch.Deleted:
node := ev.Object.(*kapi.Node)
receiver <- &osdnapi.MinionEvent{Type: osdnapi.Deleted, Minion: node.ObjectMeta.Name}
case watch.Modified:
node := ev.Object.(*kapi.Node)
receiver <- &osdnapi.MinionEvent{Type: osdnapi.Added, Minion: node.ObjectMeta.Name}
case watch.Error:
fmt.Errorf("Error in watching subnets")
return
}
}
}()
return nil
}
func (oi *OsdnRegistryInterface) WriteNetworkConfig(network string, subnetLength uint) error {
cn := &api.ClusterNetwork{
TypeMeta: kapi.TypeMeta{Kind: "ClusterNetwork"},
ObjectMeta: kapi.ObjectMeta{Name: "default"},
Network: network,
HostSubnetLength: int(subnetLength),
}
_, err := oi.oClient.ClusterNetwork().Create(cn)
return err
}
func (oi *OsdnRegistryInterface) GetContainerNetwork() (string, error) {
cn, err := oi.oClient.ClusterNetwork().Get("default")
return cn.Network, err
}
func (oi *OsdnRegistryInterface) GetSubnetLength() (uint64, error) {
cn, err := oi.oClient.ClusterNetwork().Get("default")
return uint64(cn.HostSubnetLength), err
}
func (oi *OsdnRegistryInterface) CheckEtcdIsAlive(seconds uint64) bool {
// always assumed to be true as we run through the apiserver
return true
}
| 66f9070c99ce982e2c27d441ed8fbe02c8fefeab | [
"Go"
] | 2 | Go | vinsleo/origin | 4d416a5f99f95548778d0b1f0266b0b8bfb9bb83 | 7ad2c7307f534d7bc61b5ecd69f495f803882b4b |
refs/heads/master | <repo_name>GeoffreyEmerson/code301-week1<file_sep>/README.md
# Code Fellows 301 - Design Portfolio Project
By <NAME>
June 2016
This is a project created during the Code Fellows 301 class.
Live demo: https://project-portfolio-201606.herokuapp.com
<file_sep>/controller/portfolio.js
(function(module) {
var Controller = {};
// Initialize page after loading data
Controller.initPage = function() {
allProjects(ProjectView.renderProjects);
repoView.index();
};
Controller.index = function() {
ProjectView.displayPage('home');
};
Controller.about = function() {
ProjectView.displayPage('about');
};
Controller.projects = function() {
ProjectView.displayPage('projects');
};
Controller.contact = function() {
ProjectView.displayPage('contact');
};
Controller.notFound = function() {
ProjectView.displayPage('notFound'); // TODO: not made yet
};
module.Controller = Controller;
})(window);
$(document).ready(function() {
// Starts on pageload
Controller.initPage();
});
<file_sep>/views/repo-view.js
(function(module) {
var repoView = {};
var render = Handlebars.compile(gitRepoTemplate);
repoView.index = function() {
repos.requestRepos(function(){
$('#githubRepos').append( repos.with('name').map(render) );
});
};
module.repoView = repoView;
})(window);
<file_sep>/controller/middleware.js
(function(module) {
var Middleware = {};
Middleware.example = function(ctx, next, other) {
console.log('--- Middleware report ---');
console.log('This is the ctx object:');
console.log(ctx);
console.log('This is the "next" function:');
console.log(next);
console.log('Is there anything else passed in?');
console.log(other);
// TODO: Something interesting.
next();
};
module.Middleware = Middleware;
}(window));
<file_sep>/views/project-view.js
(function(module) {
var ProjectView = {};
ProjectView.toHtml = Handlebars.compile(articleTemplate);
ProjectView.renderProjects = function(projectArray) {
projectArray.forEach(function(project) {
$('#projectSection').append(ProjectView.toHtml(project));
});
}; // End of renderProjects()
ProjectView.displayPage = function(choice) {
if (screen.width > 699 ) { // mobile view uses a single page scrolling view
$('.fullPage').fadeOut('500');
$('#' + choice).delay('500').fadeIn('slow');
} else {
scrollTo(choice);
}
};
var scrollTo = setScrollFunction(50,8);
function setScrollFunction(msBetweenJumps, divisions) {
// msBetweenJumps determines the time between jumps. The lower the number, the higher the "frame rate".
// divisions determines the fraction of the remaining distance to leap. The lower the number, the larger the jump.
// Suggested settings: 50,8
return function(element){
var destination = document.getElementById(element);
var smoothScrollTo = function(lastJump) {
var nextJump = window.scrollY + Math.ceil((destination.offsetTop - window.scrollY) / divisions );
if ( nextJump !== lastJump) {
window.scroll(0, nextJump); // The built in scroll function takes an X and a Y value. This function is only concerned with Y scrolling.
// TODO: I think there may be a difference beteen browsers as to the window.scroll function. Needs testing.
window.setTimeout(smoothScrollTo, msBetweenJumps, nextJump);
}
};
smoothScrollTo(window.scrollY);
};
}
module.ProjectView = ProjectView;
})(window);
| 225cd2c319874aa8e9cf6f59b130347f7f13283a | [
"Markdown",
"JavaScript"
] | 5 | Markdown | GeoffreyEmerson/code301-week1 | 0b03497e1da13a03a2e96ba06bc2631c2b197209 | f8c875aeab629fc18d37a701466a6e926e5c5824 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Exercise3
{
class HouseholdAccounts
{
public int Date { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public int Amount { get; set; }
public void AddNewExpense()
{
Console.Write("Enter your expense date => ");
Date = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter your expense description => ");
Description = Console.ReadLine();
Console.Write("Enter Department => ");
Category = Console.ReadLine();
Console.Write("Enter Email Id => ");
Amount = Convert.ToInt32(Console.ReadLine());
}
}
}
<file_sep>using System;
namespace Exercise1
{
abstract class Shape1
{
protected float R, L, B;
//Abstract methods can have only declarations
public abstract float Area();
public abstract float Circumference();
}
class Rectangle : Shape1
{
public override float Area()
{
Console.Write("Enter Length => ");
L = float.Parse(Console.ReadLine());
Console.Write("Enter Breadth => ");
B = float.Parse(Console.ReadLine());
return L * B;
}
public override float Circumference()
{
return 2*(L + B);
}
}
class Circle : Shape1
{
public override float Area()
{
Console.Write("Enter Radius => ");
R = float.Parse(Console.ReadLine());
return (float)Math.PI * R * R;
}
public override float Circumference()
{
return (float)Math.PI * 2 * R;
}
}
class Program
{
public static void Calculate(Shape1 S)
{
Console.WriteLine("Area : {0}", S.Area());
Console.WriteLine("Circumference : {0}", S.Circumference());
}
static void Main(string[] args)
{
Shape1 s = new Rectangle();
Calculate(s);
//Console.WriteLine($"Rectangle Area is = {s.Area()}");
//Console.WriteLine($"Rectangle Circumference is = {s.Circumference()}");
Shape1 s1 = new Circle();
Calculate(s1);
//Console.WriteLine($"Circle Area is = {s1.Area()}");
//Console.WriteLine($"Circle Circumference is = {s1.Circumference()}");
//Console.WriteLine("Hello World!");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Exercise2
{
class House
{
protected int area;
protected Door door;
public House(int area)
{
this.area = area;
door = new Door();
}
public int Area
{
get { return area; }
set { area = value; }
}
public Door Door
{
get { return door; }
set { door = value; }
}
public virtual void ShowData()
{
Console.WriteLine("I am a house, my area is {0} m2.", area);
}
}
class SmallApartment : House
{
public SmallApartment()
: base(50)
{
}
public override void ShowData()
{
Console.WriteLine("I am an apartment, my area is " +
area + " m2");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Exercise4
{
class Person
{
private int age;
public void Hello()
{
Console.WriteLine("Hello");
}
public void SetAge(int n) {
this.age = n;
}
public int getAge()
{
return age;
}
}
class Student : Person {
public void GoToClasses() {
Console.WriteLine("I’m going to class.");
}
public void ShowAge(int age) {
SetAge(age);
Console.WriteLine($"My age is: {getAge()} years old");
}
}
class Teacher : Person
{
private string subject;
public void Explain()
{
subject = "Explanation begins";
Console.WriteLine(subject);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace Exercise3
{
class Program
{
public class Expense
{
public int Date { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public int Amount { get; set; }
public override string ToString()
{
return Date + "\t" + Description + "\t" + Category + "\t" + Amount;
}
}
static void Main(string[] args)
{
static List<Expense> ShowExpense()
{
return new List<Expense>
{
new Expense { Date = 20110101, Description = "Food", Category = "Small", Amount = 100 },
new Expense { Date = 20111231, Description = "Cloths", Category = "Small", Amount = 100 },
new Expense { Date = 20110101, Description = "Furniture", Category = "Large", Amount = 1000 }
};
}
Menu m = new Menu();
int option = 3;
do
{
Console.Clear();
option = m.Print();
switch (option)
{
case (int)Options.AddNewExpense:
HouseholdAccounts a = new HouseholdAccounts();
a.AddNewExpense();
break;
case (int)Options.ShowExpenses:
ShowExpense();
break;
case (int)Options.SearchCosts:
Console.WriteLine("Thanks for Visit");
break;
case (int)Options.ModifyExpense:
Console.WriteLine("Thanks for Visit");
break;
case (int)Options.DeleteExpense:
Console.WriteLine("Thanks for Visit");
break;
case (int)Options.Exit:
break;
default:
Console.WriteLine("Invalid Option !!!!!");
break;
}
Console.WriteLine("Press Enter to Continue.......");
Console.ReadLine();
} while (option != (int)Options.Exit);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Exercise4
{
class StudentAndTeacherTest
{
static void Main(string[] args)
{
Student s = new Student();
s.Hello();
s.ShowAge(20);
Teacher t = new Teacher();
t.Hello();
t.Explain();
//Console.WriteLine("Hello World!");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Exercise5
{
class ComplexNumber
{
private int real, imaginary;
public ComplexNumber()
{
}
public ComplexNumber(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public void SetImaginary(int imaginary) {
this.imaginary = imaginary;
}
public void SetReal(int real)
{
this.real = real;
}
public string ToString() {
string result = "";
result = "(" + this.real + "," + this.imaginary + ")";
return result;
}
public double GetMagnitude()
{
double result = Math.Sqrt((real * this.real) + (this.imaginary* this.imaginary));
return result;
}
public ComplexNumber Add(ComplexNumber b)
{
//ComplexNumber s = new ComplexNumber();
this.real = b.real + this.real;
this.imaginary = b.imaginary + this.imaginary;
//Console.WriteLine(s.real);
//Console.WriteLine(s.imaginary);
return this;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Exercise3
{
enum Options
{
AddNewExpense = 1,
ShowExpenses,
SearchCosts,
ModifyExpense,
DeleteExpense,
Exit
}
}
| 868c87bc66736ae25f391bb394919acb1b42debe | [
"C#"
] | 8 | C# | yingliang1/Lab3Demo | cccec702932ba67bafca56fe48117609c32dea34 | c2600e7d6cc54f4aa212cccba79c3060f7bcd797 |
refs/heads/master | <repo_name>cubeopen7/gartools<file_sep>/tools/tf/data.py
# -*- coding: utf-8 -*-
import os
import time
import numpy as np
import tensorflow as tf
from PIL import Image
from tqdm import tqdm
'''
APIs Operating TFRecords.
'''
def bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def float_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def data_features(data_list):
feature = {}
for info in data_list:
name = info.get("name")
dtype = info.get("type")
data =info.get("data")
_f_data = None
if dtype == "str":
_f_data = bytes_feature(data)
elif dtype == "int":
_f_data = int64_feature(data)
elif dtype == "float":
_f_data = float_feature(data)
feature[name] = _f_data
return tf.train.Features(feature=feature)
def data_example(data_list):
return tf.train.Example(features=data_features(data_list))
def read_int64_feature():
return tf.FixedLenFeature([], tf.int64)
def read_bytes_feature():
return tf.FixedLenFeature([], tf.string)
def read_float_feature():
return tf.FixedLenFeature([], tf.float32)
def get_param_features(feature_info):
features = {}
for info in feature_info:
fixed_feature = None
if info[1] == "str":
fixed_feature = read_bytes_feature()
elif info[1] == "int":
fixed_feature = read_int64_feature()
elif info[1] == "float":
fixed_feature = read_float_feature()
features[info[0]] = fixed_feature
return features
def get_features(serialized_example, features):
features = get_param_features(features)
features = tf.parse_single_example(serialized_example, features=features)
return features
'''
APIs Transfer Images to TFRecord.
'''
def img2tfrecord(img_dir, img_width, img_height, tfrecord_name, img_label=None):
if os.path.exists(tfrecord_name):
raise FileExistsError("The TFRecord file already exists.")
tic = time.time()
writer = tf.python_io.TFRecordWriter(tfrecord_name)
if img_label is None:
for img_name in tqdm(os.listdir(img_dir)):
img_path = img_dir + img_name
img = Image.open(img_path)
img_data = np.array(img.resize((img_width, img_height), Image.ANTIALIAS)) # Image.ANTIALIAS的作用是抗锯齿
data_list = [{"name": "img_raw", "type": "str", "data": img_data.tostring()}]
example = data_example(data_list)
writer.write(example.SerializeToString())
else:
for img_name in tqdm(os.listdir(img_dir)):
img_path = img_dir + img_name
idx = int(img_name.split(".")[0])
label = img_label[img_label["name"]==idx]["label"].values[0]
img = Image.open(img_path)
img_data = np.array(img.resize((img_width, img_height), Image.ANTIALIAS)) # Image.ANTIALIAS的作用是抗锯齿
data_list = [{"name": "label", "type": "int", "data": label},
{"name": "img_raw", "type": "str", "data": img_data.tostring()}]
example = data_example(data_list)
writer.write(example.SerializeToString())
writer.close()
print("Data transfer process done in {}s".format(time.time()-tic))
def read_tfrecord_op(file_list, img_width, img_height, num_epochs=1, with_label=False, normalize=False, **kwargs):
file_queue = tf.train.string_input_producer(file_list, num_epochs=num_epochs)
reader = tf.TFRecordReader()
_, serialized_example = reader.read(file_queue)
if with_label:
feature = [("img_raw", "str"), ("label", "int")]
features = get_features(serialized_example, features=feature)
image = tf.decode_raw(features["img_raw"], tf.int8)
image = tf.reshape(image, shape=[img_width, img_height, 3])
if normalize:
image = (tf.cast(image, tf.float32) / 255.0 - 0.5) * 2
label = tf.cast(features["label"], tf.int32)
images, labels = tf.train.shuffle_batch([image, label], **kwargs)
return images, labels
<file_sep>/analyse/basic.py
# -*- coding: utf-8 -*-
__all__ = ["missing"]
import pandas as pd
def missing(df):
df_shape = df.shape
df_samples = df_shape[0]
df_columns = df_shape[1]
missing_df = df.isnull()
missing_columns = missing_df.sum(axis=0)
missing_columns = missing_columns[missing_columns > 0].sort_values(ascending=False)
if len(missing_columns) == 0:
print("没有任何缺失数据")
return
else:
missing_col_count = len(missing_columns)
print("有{0}列数据缺失,占总列数的{1}%".format(missing_col_count, round(missing_col_count/df_columns, 6)))
print("缺失的列为: {}".format(missing_columns.index.values))
missing_samples = missing_df.sum(axis=1)
missing_samples = missing_samples[missing_samples > 0]
missing_spl_count = len(missing_samples)
print("有{0}行数据缺失,占总行数的{1}%".format(missing_spl_count, round(missing_spl_count/df_samples, 6)))
return<file_sep>/o2o_feature.py
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from datetime import date
DATA_DIR = "D:/Code/data/O2O/"
TRAIN_FILE = "ccf_offline_stage1_train.csv"
TEST_FILE = "ccf_offline_stage1_test_revised.csv"
ON_TRAIN_FILE = "ccf_online_stage1_train.csv"
train = pd.read_csv(DATA_DIR+TRAIN_FILE, header=None) # 1754884 * 7
train.columns = ["user_id", "merchant_id", "coupon_id", "discount_rate", "distance", "date_received", "date"]
test= pd.read_csv(DATA_DIR+TEST_FILE, header=None) # 113640 * 6
test.columns = ["user_id", "merchant_id", "coupon_id", "discount_rate", "distance", "date_received"]
# on_train = pd.read_csv(DATA_DIR+ON_TRAIN_FILE, header=None) # 11429826 * 7
# on_train.columns = ["user_id","merchant_id","action","coupon_id","discount_rate","date_received","date"]
# 训练数据分析
# # 1.优惠券接受日期
# train_date_received = list(train["date_received"].unique())
# train_date_received.remove("null")
# train_date_received = sorted(train_date_received)
# print(train_date_received[0]) # 开始日期是20160101
# print(train_date_received[-1]) # 结束日期是20160615
# print(len(train_date_received)) # 共167天数据
# print((train["date_received"]=="null").sum(), (train["date_received"]=="null").sum()/train.shape[0]) # date_received字段共701602条缺失, 缺失率为40%
feature1 = train[(train.date>="20160101")&(train.date<="20160413") | ((train.date_received>="20160101")&(train.date_received<="20160413")&(train.date=="null"))] # 995240
dataset1 = train[(train.date>="20160414")&(train.date<="20160514")] # 147745
feature2 = train[(train.date>="20160201")&(train.date<="20160514") | ((train.date_received>="20160201")&(train.date_received<="20160514")&(train.date=="null"))] # 812779
dataset2 = train[(train.date>="20160515")&(train.date<="20160615")] # 194432
feature3 = train[(train.date>="20160315")&(train.date<="20160630") | ((train.date_received>="20160315")&(train.date_received<="20160630")&(train.date=="null"))] # 1036975
dataset3 = test # 113640
# 预测集3最近一个月内每个用户领取优惠券的总和
t = dataset3[["user_id"]]
t['this_month_user_receive_all_coupon_count'] = 1
t = t.groupby("user_id").sum().reset_index()
# 同一用户领取同一优惠券的次数
t1 = dataset3[["user_id","coupon_id"]]
t1["this_month_user_receive_same_coupon_count"] = 1
t1 = t1.groupby(["user_id","coupon_id"]).sum().reset_index()
# 一个用户领取多张同一优惠券的最早最晚日期
t2 = dataset3[["user_id","coupon_id","date_received"]]
t2.date_received = t2.date_received.astype("str")
t2 = t2.groupby(['user_id','coupon_id']).agg(lambda x:":".join(x)).reset_index() # aggregate
t2["receive_number"] = t2.date_received.apply(lambda s:len(s.split(":")))
t2 = t2[t2.receive_number>1]
t2["max_date_received"] = t2.date_received.apply(lambda s:max([int(d) for d in s.split(":")]))
t2["min_date_received"] = t2.date_received.apply(lambda s:min([int(d) for d in s.split(":")]))
t2 = t2[["user_id","coupon_id","max_date_received","min_date_received"]]
# 这条记录是本月第一次/最后一次接收优惠券
def is_firstlastone(x):
if x==0:
return 1
elif x>0:
return 0
else:
return -1 #those only receive once
t3 = dataset3[['user_id','coupon_id','date_received']]
t3 = pd.merge(t3, t2, on=['user_id','coupon_id'],how='left')
t3['this_month_user_receive_same_coupon_lastone'] = t3.max_date_received - t3.date_received
t3['this_month_user_receive_same_coupon_firstone'] = t3.date_received - t3.min_date_received
t3.this_month_user_receive_same_coupon_lastone = t3.this_month_user_receive_same_coupon_lastone.apply(is_firstlastone)
t3.this_month_user_receive_same_coupon_firstone = t3.this_month_user_receive_same_coupon_firstone.apply(is_firstlastone)
t3 = t3[['user_id','coupon_id','date_received','this_month_user_receive_same_coupon_lastone','this_month_user_receive_same_coupon_firstone']]
# 用户对应日期接收的优惠券的数量
t4 = dataset3[['user_id','date_received']]
t4['this_day_user_receive_all_coupon_count'] = 1
t4 = t4.groupby(['user_id','date_received']).agg('sum').reset_index()
# 用户对应日期接收的同一张优惠券的数量
t5 = dataset3[['user_id','coupon_id','date_received']]
t5['this_day_user_receive_same_coupon_count'] = 1
t5 = t5.groupby(['user_id','coupon_id','date_received']).agg('sum').reset_index()
t6 = dataset3[['user_id','coupon_id','date_received']]
t6.date_received = t6.date_received.astype('str')
t6 = t6.groupby(['user_id','coupon_id'])['date_received'].agg(lambda x:':'.join(x)).reset_index()
t6.rename(columns={'date_received':'dates'},inplace=True)
def get_day_gap_before(s):
date_received, dates = s.split('-')
dates = dates.split(':')
gaps = []
for d in dates:
this_gap = (date(int(date_received[0:4]), int(date_received[4:6]), int(date_received[6:8])) - date(int(d[0:4]), int(d[4:6]), int(d[6:8]))).days
if this_gap > 0:
gaps.append(this_gap)
if len(gaps) == 0:
return -1
else:
return min(gaps)
def get_day_gap_after(s):
date_received, dates = s.split('-')
dates = dates.split(':')
gaps = []
for d in dates:
this_gap = (date(int(d[0:4]), int(d[4:6]), int(d[6:8])) - date(int(date_received[0:4]), int(date_received[4:6]), int(date_received[6:8]))).days
if this_gap > 0:
gaps.append(this_gap)
if len(gaps) == 0:
return -1
else:
return min(gaps)
t7 = dataset3[['user_id','coupon_id','date_received']]
t7 = pd.merge(t7,t6,on=['user_id','coupon_id'],how='left')
t7['date_received_date'] = t7.date_received.astype('str') + '-' + t7.dates
t7['day_gap_before'] = t7.date_received_date.apply(get_day_gap_before)
t7['day_gap_after'] = t7.date_received_date.apply(get_day_gap_after)
t7 = t7[['user_id','coupon_id','date_received','day_gap_before','day_gap_after']]
other_feature3 = pd.merge(t1,t,on='user_id')
other_feature3 = pd.merge(other_feature3,t3,on=['user_id','coupon_id'])
other_feature3 = pd.merge(other_feature3,t4,on=['user_id','date_received'])
other_feature3 = pd.merge(other_feature3,t5,on=['user_id','coupon_id','date_received'])
other_feature3 = pd.merge(other_feature3,t7,on=['user_id','coupon_id','date_received'])
other_feature3.to_csv('data/other_feature3.csv',index=None)
print(other_feature3.shape)<file_sep>/dbwrapper/mongo.py
# -*- coding: utf-8 -*-
import pymongo
class MongoClass(object):
def __init__(self, host="localhost", port=27017, db_name=None, coll_name=None):
self._client = pymongo.MongoClient(host=host, port=port)
self._db = None
self._coll = None
if db_name is not None:
self._db = self._client.get_database(db_name)
if db_name is not None and coll_name is not None:
self._coll = self._db.get_collection(coll_name)
def get_db(self, db_name):
return self.client.get_database(name=db_name)
def get_collection(self, coll_name, db_name=None):
if db_name is None:
return self.db.get_collection(coll_name)
return self.client.get_database(db_name).get_collection(coll_name)
def set_db(self, db_name):
self._db = self.client.get_database(db_name)
def set_collection(self, coll_name):
self._coll = self.db.get_collection(coll_name)
@property
def client(self):
return self._client
@property
def db(self):
return self._db
@property
def collection(self):
return self._coll
@property
def stock_db(self):
return self.client.get_database("cubeopen")
@property
def market_coll(self):
return self.client.get_database("cubeopen").get_collection("market_daily")<file_sep>/[kaggle][cnn]invasive_species_monitoring.py
# -*- coding: utf-8 -*-
import os
import math
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.slim.nets import vgg
from tools.tf.data import img2tfrecord, read_tfrecord_op
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string("data_dir", "D:/Code/data/Invasive Species Monitoring/", "Datas' base folder direction.")
flags.DEFINE_string("train_dir", "train/", "Train data folder's name.")
flags.DEFINE_string("test_dir", "test/", "Test data folder's name.")
flags.DEFINE_string("train_label_file", "train_labels.csv", "Train datas' label file.")
flags.DEFINE_string("train_tfrecord_name", "train.tfrecords", "Train data TFRecord file name.")
flags.DEFINE_string("test_tfrecord_name", "test.tfrecords", "Test data TFRecord file name.")
flags.DEFINE_string("model_file", "model.ckpt", "Store the parameters of the model.")
flags.DEFINE_integer("width", 224, "Images' width.")
flags.DEFINE_integer("height", 224, "Images' height.")
flags.DEFINE_integer("num_epochs", 10, "Repeat times of the total samples.")
flags.DEFINE_integer("batch_size", 32, "Training batch size.")
flags.DEFINE_integer("decay_per", 50, "Learning rate decay epoch.")
flags.DEFINE_float("learning_rate", 0.001, "Initial learning rate.")
flags.DEFINE_float("decay_rate", 0.01, "Learning rate decay rate.")
_PER_BATCH = int(math.floor(2295 / FLAGS.batch_size))
# train_label = pd.read_csv(FLAGS.data_dir + FLAGS.train_label_file)
# train_label.columns = ["name", "label"]
# img2tfrecord(img_dir=FLAGS.data_dir+FLAGS.train_dir, img_width=FLAGS.width, img_height=FLAGS.height, tfrecord_name=FLAGS.train_tfrecord_name, img_label=train_label) # 将train数据(图片和标签)转为TFRecord, 方便使用
# img2tfrecord(img_dir=FLAGS.data_dir+FLAGS.test_dir, img_width=FLAGS.width, img_height=FLAGS.height, tfrecord_name=FLAGS.test_tfrecord_name) # 将test数据(图片和标签)转为TFRecord, 方便使用
def _create_cnn_graph(img, is_training=True):
with tf.variable_scope("vgg_16"):
with slim.arg_scope(vgg.vgg_arg_scope()):
net = slim.repeat(img, 2, slim.conv2d, 64, [3, 3], scope="conv1") # 创建多个拥有相同变量的指定层
net = slim.max_pool2d(net, [2, 2], scope="pool1")
net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope="conv2")
net = slim.max_pool2d(net, [2, 2], scope="pool2")
net = slim.repeat(net, 2, slim.conv2d, 256, [3, 3], scope="conv3")
net = slim.max_pool2d(net, [2, 2], scope="pool3")
net = slim.repeat(net, 2, slim.conv2d, 512, [3, 3], scope="conv4")
net = slim.max_pool2d(net, [2, 2], scope="pool4")
net = slim.repeat(net, 2, slim.conv2d, 512, [3, 3], scope="conv5")
net = slim.max_pool2d(net, [2, 2], scope="pool5")
net = slim.flatten(net)
net = slim.fully_connected(net, 512, biases_regularizer=slim.l2_regularizer(0.0005), scope="fc1")
net = slim.fully_connected(net, 2, activation_fn=None, biases_regularizer=slim.l2_regularizer(0.0005), scope="fc2")
return net
def _losses(logits, labels):
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels))
return loss
def _optimize(loss):
global_step = slim.get_or_create_global_step()
learning_rate = tf.train.exponential_decay(FLAGS.learning_rate, global_step, decay_steps=_PER_BATCH*FLAGS.decay_per, decay_rate=FLAGS.decay_rate, staircase=True)
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
return train_op
# Training model
tf.reset_default_graph()
with tf.device("/cpu:0"):
train_img, label = read_tfrecord_op([FLAGS.train_tfrecord_name], img_width=FLAGS.width, img_height=FLAGS.height, num_epochs=FLAGS.num_epochs, normalize=True, with_label=True,
batch_size=FLAGS.batch_size, capacity=256, num_threads=2, min_after_dequeue=32)
pred = _create_cnn_graph(train_img, is_training=True)
loss = _losses(pred, label)
train_op = _optimize(loss)
print("Start training...")
with tf.Session() as sess:
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(FLAGS.num_epochs):
avg_loss, acc = 0, 0
for j in range(_PER_BATCH):
_, l = sess.run([train_op, loss])
avg_loss += l / _PER_BATCH
print("Epoch {} Batch {} - average loss: {}".format(i+1, j+1, avg_loss))
coord.request_stop()
coord.join(threads)
print("Training complete.")
saver = tf.train.Saver(slim.get_model_variables())
saver.save(sess, os.path.join(os.getcwd(), FLAGS.model_file))
# tf.reset_default_graph()
# Use model to get the result with test samples<file_sep>/test.py
# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
img = Image.open("D:/Code/data/Invasive Species Monitoring/train/1.jpg")
img1 = img.resize((224, 224))
img.show()
img1.show()
a = 1<file_sep>/MGM_visual.py
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from analyse.basic import *
train = pd.read_csv("./data/train.csv")
shape = train.shape
# # y的分布情况
# # 1.散点图
# y = train["y"].sort_values(ascending=True)
# plt.scatter(np.arange(shape[0]), y)
# plt.xlabel("Index")
# plt.ylabel("y")
# plt.show()
# # 2.柱状图
# sns.distplot(train["y"], bins=50)
# plt.show()
# # 特征的整体类型
# dtype = train.dtypes.reset_index()
# dtype.columns = ["name", "type"]
# print(dtype.groupby("type").count().reset_index())
# 缺失情况
missing(train)
print(train["X0"].unique())<file_sep>/stock_price.py
# -*- coding: utf-8 -*-
import pandas as pd
import tensorflow as tf
from analyse.basic import missing
from dbwrapper.mongo import MongoClass
batch_size = 30
time_step = 20
hidden_size = 20
input_size = 7
output_size = 1
learning_rate = 0.01
max_epoch_size = 1000
def lstm(x, y=None, is_training=True):
input_w = tf.get_variable("input_weight", shape=[input_size, hidden_size], dtype=tf.float32)
input_b = tf.get_variable("input_bias", shape=[hidden_size], dtype=tf.float32)
input = tf.reshape(x, shape=[-1, 7], name="unfold_input")
input = tf.matmul(input, input_w) + input_b
input = tf.reshape(input, shape=[batch_size, time_step, hidden_size], name="re_build")
lstm_cell = tf.contrib.rnn.BasicLSTMCell(hidden_size, forget_bias=1.0, state_is_tuple=True, reuse=tf.get_variable_scope().reuse)
init_states = lstm_cell.zero_state(batch_size, dtype=tf.float32)
output, final_states = tf.nn.dynamic_rnn(lstm_cell, input, initial_state=init_states, dtype=tf.float32)
output = tf.reshape(output, shape=[-1, hidden_size], name="unfold_output")
output_w = tf.get_variable("output_weight", shape=[hidden_size, output_size], dtype=tf.float32)
output_b = tf.get_variable("output_bias", shape=[output_size], dtype=tf.float32)
output = tf.matmul(output, output_w) + output_b
loss = tf.reduce_mean(tf.square(tf.reshape(output, [-1]) - tf.reshape(y, [-1])))
if not is_training:
return None, loss
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
return train_op, loss
if __name__ == "__main__":
columns = ["code", "date", "open", "high", "low", "close", "amount", "volume", "turnover"]
field_dict = {name: 1 for name in columns}
field_dict["_id"] = 0
# market_coll = MongoClass().market_coll
# train_data = pd.DataFrame(list(market_coll.find({"code": "000001"}, field_dict))).sort_values(by="date", ascending=True)
# train_data.to_csv("./data/stock_raw.csv", index=False)
raw_data = pd.read_csv("./data/stock_raw.csv")
num_data = raw_data[["open", "high", "low", "close", "amount", "volume", "turnover"]]
num_data["label"] = 0
num_data["label"][:num_data.shape[0]-1] = num_data["close"][1:]
num_data = num_data.drop(num_data.shape[0]-1)
def rolling_normalize(data):
return ((data - data.mean()) / data.std())[-1]
for col in num_data:
col_data = num_data[col]
num_data[col] = col_data.rolling(60).apply(rolling_normalize)
num_data = num_data.dropna(axis=0)
train_data = num_data[:5000]
test_data = num_data[5000:]
train_x = train_data.iloc[:, :7].values
train_y = train_data.label.values
test_x = test_data.iloc[:, :7].values
test_y = test_data.label.values
epoch_size = train_data.shape[0] // (batch_size * time_step)
with tf.Graph().as_default():
initializer = tf.random_normal_initializer(-0.1, 0.1)
with tf.name_scope("train"):
with tf.variable_scope("train_input"):
x_input = tf.placeholder(dtype=tf.float32, name="train_x")
y_input = tf.placeholder(dtype=tf.float32, name="train_y")
i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue()
x = tf.slice(x_input, [i * batch_size * time_step, 0], [batch_size * time_step, 7])
x = tf.reshape(x, [batch_size, time_step, 7])
y = tf.slice(y_input, [i * batch_size * time_step], [batch_size * time_step])
y = tf.reshape(y, [batch_size, time_step])
with tf.variable_scope("model", reuse=False, initializer=initializer):
train_op, loss = lstm(x, y)
with tf.name_scope("test"):
with tf.variable_scope("test_input"):
test_input_x = tf.placeholder(dtype=tf.float32, name="test_input_x")
test_input_y = tf.placeholder(dtype=tf.float32, name="test_input_y")
j = tf.train.range_input_producer(test_data.shape[0] // (batch_size * time_step), num_epochs=1, shuffle=False).dequeue()
t_x = tf.slice(test_input_x, [j * batch_size * time_step, 0], [batch_size * time_step, 7])
t_x = tf.reshape(t_x, [batch_size, time_step, 7])
t_y = tf.slice(test_input_y, [j * batch_size * time_step], [batch_size * time_step])
t_y = tf.reshape(t_y, [batch_size, time_step])
with tf.variable_scope("model", reuse=True, initializer=initializer):
_, test_loss = lstm(t_x, t_y, is_training=False)
train_feed_dict = {x_input: train_x, y_input: train_y}
test_feed_dict = {test_input_x: test_x, test_input_y: test_y}
sv = tf.train.Supervisor(logdir="./model/stock.model")
with sv.managed_session() as sess:
for i in range(max_epoch_size * epoch_size):
_, cost = sess.run([train_op, loss], feed_dict=train_feed_dict)
print("Epoch {}: Loss is {}.".format(i + 1, cost))
cost = 0
for i in range(test_data.shape[0] // (batch_size * time_step)):
_cost = sess.run([test_loss], feed_dict=test_feed_dict)
cost += _cost[0]
print("Epoch {}: Loss is {}.".format(i + 1, cost / (i + 1)))
sv.saver.save(sess, save_path="./model/stock.model/model", global_step=sv.global_step) | b98091236167a7f34a428257171a2b88e3921a03 | [
"Python"
] | 8 | Python | cubeopen7/gartools | 7d3a06262165f5f819ef9cbe0a4e13ea962145f8 | 79f0ab1dec2b234aab8720367e4c85e48a13478d |
refs/heads/main | <file_sep>class Solution {
public:
void dfs(vector<vector<int>>& graph,vector<bool> vis,vector<vector<int>>& vc,vector<int> tt,int S){
if(vis[S]==true)return;
vis[S]=true;
for(auto it : graph[S]){
if(vis[it]==false){
tt.push_back(it);
dfs(graph,vis,vc,tt,it);
tt.pop_back();
}
}
if(S==(graph.size() - 1)){
vc.push_back(tt);
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> vc;
vector<int> tt;
tt.push_back(0);
vector<bool> vis(graph.size() + 5, false);
dfs(graph,vis,vc,tt,0);
return vc;
}
};<file_sep>class Solution {
public:
vector<vector<int>> dp;
int helper(int l, int r, vector<int>& piles){
if(dp[l][r]) return dp[l][r];
if(l == r) return piles[l];
return dp[l][r] = max(piles[l] - helper(l+1,r,piles) , piles[r] - helper(l,r-1,piles));
}
bool stoneGame(vector<int>& piles) {
int n = piles.size();
dp.assign(n+1,vector<int>(n+1,0));
return helper(0,n-1,piles) > 0;
}
};<file_sep>class Solution {
public:
int partitionDisjoint(vector<int>& nums) {
int n=nums.size();
vector<int> maxl(n),minr(n);
int maxll=-1;
for(int i=0;i<n;i++){
maxll=max(maxll,nums[i]);
maxl[i]=maxll;
}
int minrr = INT_MAX;
for(int i=n-1;i>=0;i--){
minrr=min(minrr,nums[i]);
minr[i]=minrr;
}
for(int i=0;i+1<n;i++){
if(maxl[i]<=minr[i+1]){
return (i+1);
}
}
return -1;
}
};<file_sep>class Solution {
public:
string customSortString(string order, string str) {
unordered_map<char,int> mp;
string s = "";
for(auto ch : str){
mp[ch]++;
}
for(auto ch : order){
if(mp.find(ch)!=mp.end()){
auto it = mp.find(ch);
while(it->second>0){
s += it->first;
it->second -= 1;
}
mp.erase(it);
}
}
for(auto& it : mp){
while(it.second > 0){
s += it.first;
it.second--;
}
}
return s;
}
};<file_sep>class Solution {
public:
int minPatches(vector<int>& nums, int target) {
int n = nums.size();
long mx = 0;
int count = 0;
for(int x : nums){
while(x > mx+1){
mx += (mx+1);
count += 1;
if(mx >= target) return count;
}
// x <= mx+1
mx += x;
if(mx >= target) return count;
}
while(target > mx){
mx += (mx+1);
count += 1;
}
return count;
}
};<file_sep>class Solution {
public:
vector<int> threeEqualParts(vector<int>& arr) {
int countone=count(arr.begin(),arr.end(),1);
int n=arr.size();
if(countone%3){
return {-1,-1};
}
if(countone==0){
return {0,n-1};
}
int total=countone/3;
int p1=0,p2=0,p3=0;
int count=0;
for(int i=0;i<n;i++){
if(arr[i]==1){
if(count==0){
p1=i;
}else if(count==total){
p2=i;
}else if(count==2*total){
p3=i;
}
count+=1;
}
}
while(p3<n-1){
p1+=1;
p2+=1;
p3+=1;
if(arr[p1]!=arr[p2] || arr[p2]!=arr[p3] || arr[p1]!=arr[p3]){
return {-1,-1};
}
}
return {p1,p2+1};
}
};<file_sep>class Solution {
public:
struct cmp{
bool operator()(const int& a, const int& b) const {
if (abs(a) == abs(b)) return a < b;
else return abs(a) < abs(b);
}
};
bool canReorderDoubled(vector<int>& arr) {
int n = arr.size();
multiset<int,cmp> m;
for(auto i : arr)m.insert(i);
while(m.size()){
auto i = *m.begin();
m.erase(m.begin());
auto i2 = m.find(i*2);
if(i2==m.end())return false;
m.erase(i2);
}
return true;
}
};<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
int bp = 0,kj = 0;
ListNode* reverse(ListNode* head, int k)
{
if(kj==bp){
return head;
}
// base case
if (!head)
return NULL;
kj+=1;
ListNode* current = head;
ListNode* next = NULL;
ListNode* prev = NULL;
int count = 0;
/*reverse first k nodes of the linked list */
while (current != NULL && count < k) {
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
/* next is now a pointer to (k+1)th node
Recursively call for the list starting from current.
And make rest of the list as next of first node */
if (next != NULL)
head->next = reverse(next, k);
/* prev is new head of the input list */
return prev;
}
ListNode* reverseKGroup(ListNode* head, int k) {
int len=0;ListNode* pt=head;
while(pt!=NULL){
pt=pt->next;len+=1;
}
bp = len/k;
return reverse(head,k);
}
};<file_sep>class Solution {
public:
int r,c;
unordered_map<int,int> mp;
vector<int> dx = {1,0,0,-1};
vector<int> dy = {0,1,-1,0};
int tp = 0,size=0;
bool isValid(int i, int j){
return (i>=0&&j>=0&&i<r&&j<c);
}
void dfs(vector<vector<int>>& a, int i, int j,int& id,vector<vector<int>>& b,vector<vector<bool>>& vis){
vis[i][j]=true;
size+=1;
b[i][j]=id;
for(int q=0;q<4;q++){
int nr = i+dx[q];
int nc = j+dy[q];
if(isValid(nr,nc)){
if(a[nr][nc]==1){
if(vis[nr][nc]==false) dfs(a,nr,nc,id,b,vis);
}
}
}
}
int largestIsland(vector<vector<int>>& a) {
r=a.size(), c=a[0].size();
vector<vector<int>> b(r,vector<int>(c,0));
bool ones=false,zeros=false;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(a[i][j]==0)zeros=true;
else ones=true;
}
}
if(ones == false) return 1;
if(zeros == false) return (int)(r*c);
int res = 0;
int id = 2;
vector<vector<bool>> vis(r,vector<bool>(c,false));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
tp=0;size=0;
if(a[i][j]==1 && vis[i][j]==false){
dfs(a,i,j,id,b,vis);
mp[id] = size;
id += 1;
}
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(b[i][j]==0){
set<int> s;
for(int q=0;q<4;q++){
int nr = i+dx[q];
int nc = j+dy[q];
if(isValid(nr,nc)){
if(b[nr][nc]!=0){
s.insert(b[nr][nc]);
}
}
}
int curr = 1;
for(auto it : s){
curr += mp[it];
}
res = max(res, curr);
}
}
}
return res;
}
};<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int,int> a;
bool findTarget(TreeNode* root, int k) {
if(root == NULL) return false;
a[root->val]=1;
if((root->val)!=(k-(root->val)))
if(a.find(k - (root->val)) != a.end())return true;
return (findTarget(root->left,k) || findTarget(root->right,k));
}
};<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> dfs(int l, int r){
vector<TreeNode*> ff;
if(l > r) return {nullptr};
if(l == r){
return {new TreeNode(l)};
}
for(int i = l; i <= r; i++){
vector<TreeNode*> left = dfs(l,i-1);
vector<TreeNode*> right = dfs(i+1,r);
for(auto ll : left){
for(auto rr : right){
ff.push_back(new TreeNode(i,ll,rr));
}
}
}
return ff;
}
vector<TreeNode*> generateTrees(int n) {
return dfs(1,n);
}
};<file_sep>/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
if(root==NULL)return {};
queue<pair<Node*,int>> q;
q.push({root,0});
vector<vector<int>> ans;
while(!q.empty()){
pair<Node*,int> curr = q.front();
q.pop();
if(curr.second==(int)ans.size()){
ans.emplace_back();
}
ans[curr.second].push_back((curr.first)->val);
vector<Node*> next = (curr.first)->children;
for(auto it : next){
q.push({it,curr.second+1});
}
}
return ans;
}
};<file_sep># Leetcode_Solutions
tejas702 Leetcode solutions.
This repository will contain all Leetcode solutions of tejas702 (https://leetcode.com/tejas702/).<file_sep>class Solution {
public:
int maxTurbulenceSize(vector<int>& arr) {
int n = arr.size();
if(n==1) return n;
int res = 0;
vector<int> pre(n,0);
if(arr[1] > arr[0]){pre[1]=1;pre[0]=-1;}
else if(arr[1] < arr[0]){pre[1]=-1;pre[0]=1;}
for(int i = 2;i < n; i++){
if(arr[i] > arr[i-1])pre[i] = 1;
else if(arr[i] < arr[i-1])pre[i]=-1;
else pre[i]=pre[i-1];
}
for(int i = 0;i < n;){
int j = i+1;
while(j < n){
if(pre[j] == pre[j-1])break;
j++;
}
int len = j-i;
if(i > 0){
if(pre[i]==pre[i-1] && arr[i]!=arr[i-1])len+=1;
}
if(j<=n-1){
if(pre[j-1]!=pre[j])len+=1;
}
res = max(res,len);
if(j>i) i=j;
else i+=1;
}
return res;
}
};<file_sep>class Solution {
public:
int findLUSlength(vector<string>& strs) {
int n = strs.size();
unordered_map<string,set<int>> mp;
for(int ind = 0;ind < n; ind++){
string curr = strs[ind];
int n2 = curr.size();
for(int i = 0;i < (1<<n2); i++){
string now = "";
for(int j = 0;j < n2;j++){
if(i & (1<<j)){
now+=curr[j];
}
}
mp[now].insert(ind);
}
}
int res = -1;
for(auto it : mp){
if((int)it.second.size() == 1){
res = max(res,(int)it.first.size());
}
}
return res;
}
};<file_sep>class Solution {
public:
bool judgeSquareSum(int c) {
unordered_map<int,int> m;
for(int i = 0;i <= 46340; i++){
m[(i*i)]++;
if(m.find(c - (i*i))!=m.end())return true;
}
return false;
}
};<file_sep>class NumArray {
public:
vector<int> a;
NumArray(vector<int>& nums) {
for(int i = 0;i < (int)nums.size(); i++){
if(i==0)a.push_back(nums[i]);
else a.push_back(nums[i]+a.back());
}
}
int sumRange(int left, int right) {
int v = a[right];
if(left == 0)return v;
return v-a[left-1];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(left,right);
*/<file_sep>class Solution {
public:
vector<vector<int>> adj;
vector<int> subans,count;
vector<int> ans;
void dfs1(int src, int par){
int numnodes = 1;
int dist = 0;
for(auto it : adj[src]){
if(it != par){
dfs1(it,src);
numnodes += count[it];// number of nodes in child subtree
dist += subans[it]+count[it];// number of nodes + distances of child subtree
}
}
subans[src] = dist;
count[src] = numnodes;
}
void dfs2(int src, int par, int& n){
if(par == -1){
ans[src] = subans[src]+(n-count[src]);
}else{
ans[src] = subans[src] + (n-count[src])+(ans[par]-(subans[src]+count[src]));
}
for(auto it : adj[src]){
if(it != par){
dfs2(it,src,n);
}
}
}
vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {
adj.resize(n+1);
for(auto it : edges){
adj[it[0]].push_back(it[1]);
adj[it[1]].push_back(it[0]);
}
subans.resize(n+1,0);count.resize(n+1,0);
dfs1(0,-1);
ans.resize(n,0);
dfs2(0,-1,n);
return ans;
}
};<file_sep>class Solution {
public:
char slowestKey(vector<int>& a, string s) {
int n = a.size();
char ans = s[0];
int maxi = a[0];
for(int i = 1;i < n; i++){
int curr = a[i]-a[i-1];
if(curr > maxi){
maxi = curr;
ans = s[i];
}else if(curr == maxi && ans < s[i])ans=s[i];
}
return ans;
}
};<file_sep>class Solution {
public:
vector<int> a,ff;
Solution(vector<int>& nums) {
a=nums;ff=nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
a=ff;
return a;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
a=ff;
for(int i=0;i<a.size();i++){
int rr = (rand()%a.size());
swap(a[i],a[rr]);
}
return a;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* vector<int> param_1 = obj->reset();
* vector<int> param_2 = obj->shuffle();
*/<file_sep>/*
* @lc app=leetcode id=20 lang=cpp
*
* [20] Valid Parentheses
*/
// @lc code=start
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
//#define ordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ar array
#define ld long double
// A hash function used to hash a pair of any kind
struct hash_pair {
template <class T1, class T2>
size_t operator()(const pair<T1, T2>& p) const
{
auto hash1 = hash<T1>{}(p.first);
auto hash2 = hash<T2>{}(p.second);
return hash1 ^ hash2;
}
};
// Comparator function by key for MAP
struct cmpmap {
bool operator()(const string& a, const string& b) const {
return a.length() < b.length();
}
};
// Comparator function for PRIORITY QUEUE
struct cmppq {
bool operator()(const string& p1, const string& p2){
return p1.length() < p2.length();
}
};
const int mod= (int)1e9 + 7;
const int mxN = 200005;
const int INF = INT_MAX;
#define pb push_back
#define forn(i,j,n) for(int (i)=(j);(i) >= (n); (i)--)
#define forr(i,j,n) for(int (i)=(j);(i) < (n); (i)++)
#define sz(x) ((int)(x).size())
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef map<int, int> mp;
typedef unordered_map<int,int> ump;
#define all(v) v.begin(), v.end()
#define alla(arr, sz) arr, arr + sz
#define sort(v) sort(all(v))
#define sorta(arr, sz) sort(alla(arr, sz))
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char c : s){
if( c == '(' || c=='{' || c=='['){
st.push(c);
}else if(st.top() == '(' && c==')'){
st.pop();
}else if(st.top() == '[' && c==']'){
st.pop();
}else if(st.top() == '{' && c=='}'){
st.pop();
}
}
return (sz(st) == 0);
}
};
// @lc code=end
<file_sep>class Solution {
public:
int findMin(vector<int>& nums) {
int n = nums.size();
int left = 0, right = n-1;
if(nums[right] > nums[left]) return nums[left];
while(left < right){
int mid = left + (right-left)/2;
if(nums[mid] < nums[right]) right=mid;
else left = mid+1;
}
return nums[left];
}
};<file_sep>class Solution {
public:
int shortestPath(vector<vector<int>>& grid, int k) {
int m = grid.size(), n = grid[0].size();
queue<array<int,4>> q;
q.push({0,0,0,k});
vector<vector<int>> vis(m,vector<int>(n,-1));
while(!q.empty()){
array<int,4> c = q.front();
q.pop();
int x = c[0], y = c[1];
if(x<0||y<0||x>=m||y>=n){
continue;
}
if(x == m-1 && y==n-1){
return c[2];
}
if(grid[x][y]==1){
if(c[3]>0)
c[3]-=1;
else
continue;
}
if(vis[x][y] >= c[3]){
continue;
}
vis[x][y]=c[3];
q.push({x+1,y,c[2]+1,c[3]});
q.push({x-1,y,c[2]+1,c[3]});
q.push({x,y+1,c[2]+1,c[3]});
q.push({x,y-1,c[2]+1,c[3]});
}
return -1;
}
};<file_sep>class Solution {
public:
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
unordered_map<int,int> mp;
for(vector<int>& f : edges){
mp[f[1]]++;
}
vector<int> vc;
for(int i=0;i<n;i++){
if(mp.find(i)==mp.end())vc.push_back(i);
}
return vc;
}
};<file_sep>class Solution {
public:
vector<vector<int>> fourSum(vector<int>& a, int target) {
int n=a.size();
unordered_map<int,vector<array<int,2>>> mp;
map<vector<int>,int> mp2;
vector<vector<int>> vc;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(mp.find(target-a[i]-a[j])!=mp.end()){
vector<array<int,2>> p = mp[target-a[i]-a[j]];
for(array<int,2> p2 : p){
vector<int> tb = {a[i],a[j],a[p2[0]],a[p2[1]]};
sort(tb.begin(),tb.end());
if(mp2.find(tb)==mp2.end()) {vc.push_back(tb);mp2[tb]++;}
}
}
}
for(int j=0;j<i;j++){
mp[a[i]+a[j]].push_back({i,j});
}
}
return vc;
}
};<file_sep>class Solution {
public:
string orderlyQueue(string s, int k) {
int n = s.size();
if(k == 1){
string res = s;
for(int i = 0;i < n; i++){
string curr = s.substr(i)+s.substr(0,i);
res = min(res, curr);
}
return res;
}else{
sort(begin(s),end(s));
return s;
}
}
};<file_sep>class Solution {
public:
string breakPalindrome(string p) {
int n = p.size();
if(n==1)return "";
bool done = 0;
for(int i = 0;i < n; i++){
if(p[i]!='a'){
for(char c = 'a'; c <= 'z'; c++){
if(c == p[i])continue;
if(p[n-i-1]==c || n-i-1==i)continue;
p[i]=c;
done=1;
break;
}
if(done) break;
}
}
if(done) return p;
for(int i = n-1;i >= 0; i--){
if(p[i]=='a'){
for(char c = 'b'; c <= 'z'; c++){
if(p[n-i-1]==c || n-i-1==i)continue;
p[i]=c;
done=1;
break;
}
if(done) break;
}
}
return p;
}
};<file_sep>class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int n = 9;
int row[n];
int col[n];
int box[n];
memset(row,0,sizeof(row));
memset(col,0,sizeof(row));
memset(box,0,sizeof(row));
for(int i = 0;i < n; i++){
for(int j = 0;j < n; j++){
if(board[i][j] == '.') continue;
int value = board[i][j] - '0';
int position = 1 << (value-1);
int boxpos = (i/3)*3 + j/3;
if((row[i] & position) || (col[j] & position) || (box[boxpos] & position)){
return false;
}
row[i] |= position;
col[j] |= position;
box[boxpos] |= position;
}
}
return true;
}
};<file_sep>class Solution {
public:
int canBeTypedWords(string text, string brokenLetters) {
text += " ";
int n=text.size();
int words = 0,j=-1;
for(int i=0;i<n;i++){
if(text[i]==' '){
string now = text.substr(j,i-j);bool f=0;
for(char c2 : now){for(char c : brokenLetters){
if(c==c2){
f=1;break;
}
}
if(f==1)break;}
if(f==0)words+=1;
j=-1;
}else if(j==-1){
j=i;
}
}
return words;
}
};<file_sep>class Solution {
public:
vector<int> beautifulArray(int n) {
vector<int> ff = {1};
int n1 = 2;
while((int)(ff.size()) < n){
vector<int> odd;
vector<int> even;
// compute odd
for(int i=0;i<(int)ff.size();i++){
if((2*ff[i]) - 1 <= n1){
odd.push_back(2*(ff[i])-1);
}
}
// compute even
for(int i=0;i<(int)ff.size();i++){
if((2*ff[i]) <= n1){
even.push_back(2*(ff[i]));
}
}
// add both
ff.clear();
for(auto it : odd){
ff.push_back(it);
}
for(auto it : even){
ff.push_back(it);
}
n1+=1;
}
return ff;
}
};<file_sep>class Solution {
public:
int triangleNumber(vector<int>& a) {
sort(a.begin(),a.end());
int n=a.size(),c=0;
if(n<3)return 0;
for(int i=0;i+2<n;i++){
for(int j=i+1;j<n&&a[i]>0;j++){
int k;
auto it = lower_bound(a.begin(),a.end(),a[i]+a[j]);
k = it-a.begin();
c += (k-j-1);
}
}
return c;
}
}; | 31f1ad6936740e3e485438c5268e64f7cd7a9609 | [
"Markdown",
"C++"
] | 31 | C++ | tejas702/Leetcode_Solutions | 0d31b64b6a7be019b51208455550bd205da2396c | ec40942fc77ecde7f2ef6f10196e524e2bfddd78 |
refs/heads/master | <repo_name>rnzsgh/fargate-workshop-apps<file_sep>/web/Dockerfile
FROM debian:8 as builder
RUN apt-get update && \
apt-get install -y openssl && \
openssl genrsa -des3 -passout pass:x -out server.pass.key 2048 && \
openssl rsa -passin pass:x -in server.pass.key -out server.key && \
rm server.pass.key && \
openssl req -new -key server.key -out server.csr \
-subj "/C=US/ST=NY/L=NYC/O=Good/OU=IT Department/CN=selfsigned.com" && \
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
FROM nginx:1.15-alpine
COPY --from=builder /server.* /etc/nginx/
COPY default.conf /etc/nginx/conf.d/
EXPOSE 8443
STOPSIGNAL SIGTERM
CMD ["nginx", "-g", "daemon off;"]
<file_sep>/back/Dockerfile
FROM golang:1.11.1 as builder
RUN mkdir -p /build
WORKDIR /build
RUN useradd -u 10001 app
ENV GO111MODULE on
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
FROM scratch
COPY --from=builder /build/main /main
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/ssl/certs /etc/ssl/certs
USER app
EXPOSE 7080
CMD ["/main"]
<file_sep>/back/main.go
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"strings"
_ "github.com/go-sql-driver/mysql"
log "github.com/golang/glog"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
var mysqlSchema = `
CREATE TABLE IF NOT EXISTS text_data(
id int NOT NULL AUTO_INCREMENT,
value text,
PRIMARY KEY (id)
) ENGINE=INNODB;`
var postgresSchema = `
CREATE TABLE IF NOT EXISTS text_data(
id SERIAL PRIMARY KEY,
value text
);`
var db *sqlx.DB
func init() {
flag.Parse()
flag.Lookup("logtostderr").Value.Set("true")
var objmap map[string]interface{}
var err error
if err = json.Unmarshal([]byte(os.Getenv("DB_ADMIN")), &objmap); err != nil {
panic(fmt.Sprintf("Unable to parse DB_ADMIN data - reason: %v", err))
}
db, err = sqlx.Connect(
os.Getenv("DB_ENGINE"),
fmt.Sprintf(
"user=%s dbname=%s sslmode=require password=%s host=%s",
objmap["username"].(string),
os.Getenv("DB_NAME"),
objmap["password"].(string),
os.Getenv("DB_ENDPOINT"),
),
)
if err != nil {
panic(fmt.Sprintf("Unable to open db connection - reason: %v", err))
}
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Info("Backend called")
w.WriteHeader(http.StatusOK)
io.WriteString(w, "Hello World - new!\n")
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
io.WriteString(w, pair[0]+"="+pair[1]+"\n")
}
})
http.ListenAndServe(":7080", nil)
}
<file_sep>/api/server.js
const express = require('express')
const app = express()
const port = 8090
const { createLogger, format, transports } = require('winston')
const { combine, timestamp, label, printf } = format
const log = createLogger({
format: combine(
label({ label: 'fargate' }),
timestamp(),
printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`;
})
),
transports: [ new transports.Console() ]
})
app.get('/', (req, res) =>
res.send('Hello World!')
)
app.listen(port, () => log.info(`API listening on port: ${port}`))
<file_sep>/back/go.mod
module github.com/rnzsgh/fargate-workshop-apps/back
require github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
require (
github.com/go-sql-driver/mysql v1.4.0
github.com/jmoiron/sqlx v1.2.0
github.com/lib/pq v1.0.0
)
| 19ba5bb09d9aaf74f14786418dd549188cddacd5 | [
"JavaScript",
"Go Module",
"Go",
"Dockerfile"
] | 5 | Dockerfile | rnzsgh/fargate-workshop-apps | f97c2bc79fd975f75e0ac782576ca20a2a57f6ee | 7b36564e3c1a1faa1c53c4e7512a89f740b9eb83 |
refs/heads/master | <repo_name>tgraha09/TKG-APP<file_sep>/src/App.js
import bttnstyle from './dist/css/tkg-button.css'
import cardhoverstyle from './dist/css/tkg-card-hover.css'
import pager from './dist/css/tkg-pager.css'
import accordian from './dist/css/tkg-accordian.css'
import { TKGButton } from './dist/js/tkg-templates/tkg-button'
import { TKGHoverCard } from './dist/js/tkg-templates/tkg-card-hover'
import { TKGPager } from './dist/js/tkg-templates/tkg-pager'
import { TKGAccordian } from './dist/js/tkg-templates/tkg-accordian'
import { TKGHelpers } from './dist/js/tkg-helpers'
import logo from './logo.svg';
import $ from "jquery";
import './App.css';
let defaultAPP = ''
function App() {
return (
<div className="App">
</div>
);
}
export default App;
<file_sep>/src/dist/index.js
import bttnstyle from './css/tkg-button.css'
import cardhoverstyle from './css/tkg-card-hover.css'
import pager from './css/tkg-pager.css'
import accordian from './css/tkg-accordian.css'
import { TKGButton } from './js/tkg-templates/tkg-button'
import { TKGHoverCard } from './js/tkg-templates/tkg-card-hover'
import { TKGPager } from './js/tkg-templates/tkg-pager'
import { TKGAccordian } from './js/tkg-templates/tkg-accordian'
import $ from "jquery";
/*1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor,
compare it to the elements before. Move the greater elements one position up to.*/<file_sep>/README.md
## TKGAPP (Ongoing) - (JavaScript)(Testing Envrionment)
### System: Windows
### Frameworks: React, ElectronJS, Custom Webpack (TKG-Template)
### Feb. 2020 to Current
* Created a testing environment for testing new css styling and scripts for future project development.
* Comes equipt with webpacker for custom templates.
| 2c43169c3a58fbe885bbeacd11f07106c1561398 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | tgraha09/TKG-APP | b9563ac194f01ce4a7077267bb82c412c7f12d34 | 0c0a675c3c635bc2a1f0eae586871a11ea50a1bc |
refs/heads/master | <repo_name>12Matheus/Archievements<file_sep>/operação_bancária[1].cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include<ctype.h>
int main(){
int operacao;
float deposito;
int saque;
int saldo;
printf("\n==============================");
printf("\nSIMULACAO BANCARIA:");
printf("\n==============================");
printf("\n[1] para saldo");
printf("\n[2] para extrato");
printf("\n[3] para saque");
printf("\n[4] para Deposito");
printf("\n==============================");
printf("\n\nEcolha a operacao desejada: ");
printf("\n==============================");
scanf("%d", &operacao);
switch (operacao) {
// Verifica se a opção é Saldo
case 1:
saldo=(deposito)-(saque);
printf("\n======================");
printf("Seu saldo é:R$ %d\n",saldo);
printf("\n=======================");
system("PAUSE");
break;
// Verifica se a opção é Extrato
case 2:
break;
// Verifica se a opção é Saque
case 3:
printf("\n==========================");
printf("Operacao Desejada:Saque\n");
printf("Digite o Valor Solicitado:R$");
printf("\n==========================");
scanf("%d",&saque);
system("PAUSE");
if (saque>saldo)
{
printf("\n===========================================================================");
printf("Valor Solicitado R$%d é menor que o saldo disponivel que é R$%d\n",saque,saldo);
printf("\n===========================================================================");
saque=(0);
system("PAUSE");
}
else if (saque<=saldo)
{
saldo=(deposito)-saque;
printf("\n==========================");
printf("Seu novo Saldo é:R$%d",&saldo);
printf("\n==========================");
break;
// Verifica se a opção é Depósito
case 4:
// Mostra a saudação na tela
printf("\n=============================");
printf("\nEntre com o Valor do deposito");
printf("\n=============================");
scanf("%f", &deposito);
printf("\n========================================");
printf("\nDeposito efetuado com sucesso!\n\n");
printf("\nO valor depositado eh %.2f\n\n", deposito);
printf("\n========================================");
break;
/* Saída Padrão, ou seja, caso nenhuma das opções for atendida
ela executa uma ação padrão ----->*/
default:
printf("\n===================");
printf("\nOpcao Invalida!\n\n");
printf("\n===================");
}
system("pause");
}
}
<file_sep>/gasolina_e_alcool[1].cpp
#include<stdio.h>
#include<stdlib.h>
int main (){
int combustivel;
float litros, total,total2, desconto;
char c;
printf("qual o tipo de combustível vendido:\n A - Alcool\n G - Gasolina\n");
scanf("%c", &combustivel);
if(combustivel == 'A' || combustivel == 'a'){
printf("O combustivel escolhido foi Alcool = 1.90/L\n");
printf("Digite a quantia de litros abastecido:\n");
scanf("%f", &litros);
if(litros <= 20.00){ total = litros * 1.90; desconto = litros * (1.90 * 0.03);
total2 = total - desconto;
printf("Valor a pagar %.2f\n", total2);
} else if (litros > 20.00){ total = litros * 1.90; desconto = litros * (1.90 * 0.05);
total2 = total - desconto;
printf("Valor a pagar %.2f\n", total2);
} } else if(combustivel == 'G' || combustivel == 'g'){
printf("O combustivel escolhido foi Gasolina = 2.50/L\n");
printf("Digite a quantia de litros abastecido:\n");
scanf("%f", &litros);
if (litros <= 20.00){ total = litros * 2.50; desconto = litros * (2.50 * 0.04);
total2 = total - desconto;
printf("Valor a pagar %.2f\n", total2);
} else if(litros > 20.00){ total = litros * 2.50; desconto = litros * (2.50 * 0.06);
total2 = total - desconto;
printf("Valor a pagar %.2f\n", total2);
} }
return 0;}
<file_sep>/aula01/devc+ testcode.cpp
#include<stdio.h>
#include<stdlib.h>
int main(){
int val;
printf("informe um valor qualquer");
scanf("%d",&val);
if(val > 10){
printf("valor maior do que o desejado\n");
}else{
printf("valor na faixa desejada\n");
}
system("pause");
return 0;
| 45fbf7a8ac563b58fa61fee981af75aed30fb42a | [
"C++"
] | 3 | C++ | 12Matheus/Archievements | 6c686aca2f5b4b90f9ce21d6a3d3c14d47b8fd77 | 2115015be1f8f82d3d11b648498d35c0e1e4eda7 |
refs/heads/master | <file_sep>#!/bin/sh
ROOT_FOLDER=${PWD}
echo $ROOT_FOLDER
cd pymonero
make
cd build/release/src/wallet/api
make install
echo "ready!"
<file_sep>import tkinter as tk
import pywallet_api
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
# UI Widgets Setup
def create_widgets(self):
self.main_label = tk.Label(self)
self.main_label["text"] = "Click Go! to Create/Open"
self.main_label["bg"] = "black"
self.main_label["fg"] = "green"
self.main_label["width"] = 50
self.main_label["height"] = 20
self.main_label["wraplength"] = 200
self.main_label.pack(side="top")
self.show_wallet_btn = tk.Button(self)
self.show_wallet_btn["text"] = "Go!"
self.show_wallet_btn["command"] = self.access_wallet
self.show_wallet_btn.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.quit)
self.quit.pack(side="bottom")
# Create New or Open Existing Wallet
def access_wallet(self):
# hide button
self.show_wallet_btn.pack_forget()
self.wallet_manager = pywallet_api.WalletManagerFactory.getWalletManager()
has_wallet = self.wallet_manager.walletExists('wallet/mywallet');
if has_wallet != True:
self.w = self.wallet_manager.createWallet('wallet/mywallet', '', 'English', 1)
else :
self.w = self.wallet_manager.openWallet('wallet/mywallet', '', 1);
self.main_label["text"] = '\n Main address : ' + self.w.mainAddress() + '\n\n seed : ' + self.w.seed()
root = tk.Tk()
# launch to foreground
root.lift()
root.attributes('-topmost',True)
app = Application(master=root)
app.mainloop()
<file_sep># pymonero-gui
- Proof-of-concept to develop with monero in Python. Currently only creates & shows a monero wallet (main public address & seed)
- TESTING ONLY. Filename & testnet hardcoded in init app.py
- Uses https://github.com/ehanoc/pymonero (Python C++ bindings)
# Dependencies
- sudo apt-get install python3-tk
# Build
- Clone
- ``` git submodule update --init --recursive --remote ```
- build & install python module ``` sh build.sh ``` (Wait, will build monero first)
- run ``` python3 app.py ```

| 48902ea306eb4609c7dd9c6c4243ff4cbec22c25 | [
"Markdown",
"Python",
"Shell"
] | 3 | Shell | ehanoc/pymonero-gui | 795e808fd5730c35a87ee72a5509b40ad917c5ce | dda12eff11d4e1ef1686b05032ff3eac6d40f82d |
refs/heads/master | <file_sep>const redux = require('redux');
const createStore = redux.createStore;
const combineReducers = redux.combineReducers;
const applyMiddleware = redux.applyMiddleware;
// const Buy_book = "Buy_book";
// const intialState = {
// numberOfBooks: 10,
// numberOfPens: 15
// }
const initialSateBooks = {
numberOfBooks: 10
}
const initialSatePens = {
numberOfPens: 15
}
function buyBook() {
return {type: "Buy_book", info: "My First Redux Code!"}
}
function buyPen() {
return {type: "Buy_pen", info: "This is Good Pan"}
}
const BookReducer = (state = initialSateBooks, action) => {
switch (action.type) {
case "Buy_book":
return {
...state,
numberOfBooks: state.numberOfBooks - 1
}
default:
return state
}
}
const PenReducer = (state = initialSatePens, action) => {
switch (action.type) {
case "Buy_pen":
return {
...state,
numberOfPens: state.numberOfPens - 2
}
default:
return state
}
}
const Reducer = combineReducers({Book: BookReducer, Pen: PenReducer})
const logger = store => {
return next => {
return action => {
const result = next(action);
console.log("middleware log", result);
return result
}
}
}
const store = createStore(Reducer, applyMiddleware(logger));
console.log("initial State", store.getState());
const unsubcribe = store.subscribe(() => {
console.log('updated', store.getState())
});
store.dispatch(buyBook());
store.dispatch(buyBook());
store.dispatch(buyBook());
store.dispatch(buyPen());
store.dispatch(buyPen());
unsubcribe();
| 1b589b645a40f33a5232963bd29af1f3e4920826 | [
"JavaScript"
] | 1 | JavaScript | sunilkumar1996/redux-demo | 9bb22ac633dfd45cfa03108b9f4599fc5606caac | f81fb06710b82066ddde707ea32e70b26258e02b |
refs/heads/master | <file_sep>package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
if err := http.ListenAndServe(":8080", r); err != nil {
log.Println("Listen and Serve ...", err)
}
}
<file_sep>package db
import "time"
// DataSource contains username,pssword and database name.
var (
DataSource = "root:sonyss-a3@/made"
MaxIdleConnections = 200
TimeoutConnection = 60 * time.Second
)
<file_sep>package middleware
import (
"log"
"net/http"
"time"
)
// Logger returns a handler function that will log inf about
// the request then call the provided handler function.
func Logger(next http.HandlerFunc) http.HandlerFunc {
// Wrap this hadnler around next one prvided.
return func(res http.ResponseWriter, req *http.Request) {
start := time.Now()
// Once tge handler call proceeding this defer
// is complete, log how long the request took.
defer func() {
d := time.Now().Sub(start)
log.Printf("(%s) : %s -> %s (%s)", req.Method, req.URL.Path, req.RemoteAddr, d)
}()
next(res, req)
}
}
<file_sep>package users
import (
"time"
)
// User contains information about user.
type User struct {
UserID int `json:"user_id" validate:"upwd"`
UserType int `json:"type"`
FirstName string `json:"first_name"`
LastName string `json:"lat_name"`
Password string `json:"<PASSWORD>"`
Email string `json:"email"`
Company string `json:"company"`
Image string `json:"image"`
DataCreated *time.Time `json:"data_created"`
DataModified *time.Time `json:"data_modified"`
}
/*
create table users (id int primary key auto_increment,userType int not null,
firstName varchar(100) not null,lastName varchar(100) not null,
password varchar(36) not null,email varchar(60) not null,
company varchar (256), image varchar(256) not null,
dataCreated time ,dataModified timestamp
);
*/
<file_sep>// go test -v
// go test -v -run TestCreate
// go test -v -run TestUpdate
// go test -v -run TestDelete
// go test -v -run TestRetrieve
// go test -v -run TestList
package users
import (
"testing"
"time"
"github.com/workspace/golang-crud/http/internal/platform/db"
)
const succeed = "\u2713"
const failed = "\u2717"
func TestCreate(t *testing.T) {
if err := connect(); err != nil {
t.Error(db.ErrInvalidDBProvider, err)
}
now := time.Now()
insert := User{
UserType: 1,
FirstName: "Mary",
LastName: "Jane",
Password: "<PASSWORD>",
Email: "<EMAIL>",
Company: "Devos",
Image: "jane.jpg",
DataCreated: &now,
}
t.Log("Given the need to crate user")
{
t.Log("When using a valid user model")
{
user, err := Create(&insert)
if err != nil {
t.Fatalf("\t%s\tShould be able to create a new user in the system %v", failed, insert)
}
t.Logf("\t%s\tShould be able to create a new user in the system : %+v", succeed, user)
}
}
}
func TestUpdate(t *testing.T) {
if err := connect(); err != nil {
t.Error(db.ErrInvalidDBProvider, err)
}
now := time.Now()
update := User{
UserID: 1,
UserType: 2,
FirstName: "Max",
LastName: "Musterman",
Password: "<PASSWORD>",
Email: "<EMAIL>",
Company: "Devos",
Image: "max.jpg",
DataModified: &now,
}
t.Log("Given the need to update user")
{
t.Log("When using a valid user model")
{
user, err := Update(&update)
if err != nil {
t.Fatalf("\t%s\tShould be able to update user in the system %v", failed, update)
}
t.Logf("\t%s\tShould be able to update user in the system : %+v", succeed, user)
t.Log(now)
}
}
}
func TestRetrieve(t *testing.T) {
if err := connect(); err != nil {
t.Error(db.ErrInvalidDBProvider, err)
}
userID := 1
t.Log("Given the neet to retrieve user")
{
t.Log("When using a valid user model")
{
user, err := Retrieve(userID)
if err != nil {
t.Fatalf("\t%s\tShould be able to retrieve user from the system %v", failed, err)
}
t.Logf("\t%s\tShould be able to retrieve user from the system : \n %+v", succeed, user)
}
}
}
func TestList(t *testing.T) {
if err := connect(); err != nil {
t.Error(db.ErrInvalidDBProvider, err)
}
t.Log("Given the need to retrieve all users from system")
{
users, err := List()
if err != nil {
t.Fatalf("\t%s\tShould be able to retrieve users from system %v", failed, err)
}
t.Logf("\t%s\tShould be able to retrieve users from system : \n %+v", succeed, users)
}
}
func connect() error {
return db.NewMySql()
}
<file_sep>package db
import (
"database/sql"
"log"
"github.com/pkg/errors"
)
var ReadDB *sql.DB
// ErrInvalidDBProvider is returned in the event that unitialized
// db is used to perform action against.
var ErrInvalidDBProvider = errors.New("invalid DB provider")
// NewMysql creates a new mysql connection.
func NewMySql() error {
log.Println("Preparing mysql connection...")
// Open a database value. Specify the mysql driver
// for database/sql
var err error
ReadDB, err = sql.Open("mysql", DataSource)
if err != nil {
return errors.Wrapf(err, "[sql.Open] %s", DataSource)
}
// Defined in config.go
ReadDB.SetMaxIdleConns(MaxIdleConnections)
ReadDB.SetConnMaxLifetime(TimeoutConnection)
// sql.Open() does not establish any connection to the
// database. It just prepare the database connection value
// for later use. To make sure the database is available and
// accessible, we will use db.Ping()
if err = ReadDB.Ping(); err != nil {
return errors.Wrap(err, "[db.Ping]")
}
log.Println("Able to connect to the mysql database!")
return nil
}
<file_sep>package users
import (
"log"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/pkg/errors"
"github.com/workspace/golang-crud/http/internal/platform/db"
)
const (
stmtInsertUser = "INSERT INTO users (userType ,firstName, lastName, password, email, company,image, dataCreated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
stmtUpdateUser = "UPDATE users set userType = ?, firstName = ?, lastName = ?, password = ?, email = ?, company = ?, image = ? WHERE id = ?"
stmtDeleteUser = "DELETE FROM users WHERE id = ?"
stmtRetrieveUser = "SELECT id,userType,firstName,lastName,email,company,image FROM users WHERE id = ?"
stmtListUsers = "SELECT id,userType,firstName,lastName,email,company,image FROM users"
stmtCountUsers = "SELECT count(id) FROM users"
)
// Create inserts a new user into the database.
func Create(u *User) (*User, error) {
write, err := db.ReadDB.Begin()
if err != nil {
write.Rollback()
return nil, errors.Wrap(err, "Insert[db.ReadDB.Begin]")
}
now := time.Now()
user := User{
UserType: u.UserType,
FirstName: u.FirstName,
LastName: u.LastName,
Password: <PASSWORD>,
Email: u.Email,
Company: u.Company,
Image: u.Image,
DataCreated: &now,
}
_, err = write.Exec(stmtInsertUser, &user.UserType, &user.FirstName, &user.LastName, &user.Password, &user.Email, &user.Company, &user.Image, &user.DataCreated)
if err != nil {
write.Rollback()
return nil, errors.Wrapf(err, "Insert[write.Exec] %s", stmtInsertUser)
}
return &user, write.Commit()
}
// Update updates a user in the database.
func Update(u *User) (*User, error) {
write, err := db.ReadDB.Begin()
if err != nil {
write.Rollback()
return nil, errors.Wrapf(err, "Update[db.ReadDB.Begin]")
}
now := time.Now()
user := User{
UserType: u.UserType,
FirstName: u.FirstName,
LastName: u.LastName,
Password: <PASSWORD>,
Email: u.Email,
Company: u.Company,
Image: u.Image,
DataModified: &now,
}
_, err = write.Exec(stmtUpdateUser, &user.UserType, &user.FirstName, &user.LastName, &user.Password, &user.Email, &user.Company, &user.Image, &user.UserID)
if err != nil {
write.Rollback()
return nil, errors.Wrapf(err, "Update[write.Exec] %s \n %v", stmtUpdateUser, u)
}
return &user, write.Commit()
}
// Delete removes user from database.
func Delete(userID int) error {
writeDb, err := db.ReadDB.Begin()
if err != nil {
writeDb.Rollback()
return errors.Wrap(err, "Delete[db.ReadDB.Begin]")
}
_, err = writeDb.Exec(stmtDeleteUser, userID)
if err != nil {
writeDb.Rollback()
return errors.Wrapf(err, "Could not delete user with id %d", userID)
}
return writeDb.Commit()
}
// Retrieve returns specific user from database.
func Retrieve(userID int) (*User, error) {
var u User
row := db.ReadDB.QueryRow(stmtRetrieveUser, userID)
if err := row.Scan(&u.UserID, &u.UserType, &u.FirstName, &u.LastName, &u.Email, &u.Company, &u.Image); err != nil {
return nil, errors.Wrapf(err, "Could not retrieve user with the given id %d", userID)
}
return &u, nil
}
// List returns all existing users from database.
func List() ([]User, error) {
var users []User
rows, err := db.ReadDB.Query(stmtListUsers)
if err != nil {
return nil, errors.Wrap(err, "List[db.ReadDB.Begin]")
}
defer rows.Close()
if rows.Next() {
var u User
if err := rows.Scan(&u.UserID, &u.UserType, &u.FirstName, &u.LastName, &u.Email, &u.Password, &u.Company, &u.Image); err != nil {
return nil, errors.Wrap(err, "Could not read data from database")
}
users = append(users, u)
}
return users, nil
}
// Count return number of users in database.
func Count() (count int) {
rows, _ := db.ReadDB.Query(stmtCountUsers)
if rows.Next() {
err := rows.Scan(count)
log.Fatalf("%s", err)
}
return count
}
| 5ecb7b7090f8b76076cdb19296633cd3511a9b50 | [
"Go"
] | 7 | Go | SanelSacic/golang-crud | 5393fa8c3a4100a55f2b51f7cab5a4f061f12b18 | 2d372eb66e9082ac145f5a99294c4c8d40c9afe1 |
refs/heads/master | <repo_name>eldesh/json-parser<file_sep>/README.md
Very low footprint JSON parser written in portable ANSI C.
* BSD licensed with no dependencies (i.e. just drop the C file into your project)
* Never recurses or allocates more memory than it needs
* Very simple API with operator sugar for C++
[](http://travis-ci.org/udp/json-parser)
# API
json_value * json_parse
(const json_char * json);
json_value * json_parse_ex
(json_settings * settings, const json_char * json, char * error);
void json_value_free
(json_value *);
json_value * json_value_dup
(json_value const *);
void json_value_dump
(FILE * fp, json_value const * v);
bool json_value_equal
(json_value const * lhs, json_value const * rhs);
bool json_type_equal
(json_value const * lhs, json_value const * rhs);
json_value const * find_json_object
(json_value const * v, char const * field);
## Reader
Read a C typed value from json\_value .
bool json_value_read_if_<type>
(<type> * x, json_value const * v);
Supported types are below:
int, uint
uint8_t, uint16_t, uint32_t, uint64_t
int8_t, int16_t, int32_t, int64_t
float, double
string, bool
The `type` field of `json_value` is one of:
* `json_object` (see `u.object.length`, `u.object.values[x].name`, `u.object.values[x].value`)
* `json_array` (see `u.array.length`, `u.array.values`)
* `json_integer` (see `u.integer`)
* `json_double` (see `u.dbl`)
* `json_string` (see `u.string.ptr`, `u.string.length`)
* `json_boolean` (see `u.boolean`)
* `json_null`
<file_sep>/Makefile
###
###
NAME= json_parser
### include debug information: 1=yes, 0=no
DBG?= 0
DEPEND= dependencies
LIBDIR= ./lib
OBJDIR= ./obj
CC= $(shell which gcc)
CXX= $(shell which g++)
CFLAGS= -std=gnu99 -pedantic -ffloat-store -fno-strict-aliasing -fsigned-char
FLAGS= -Wall -Wextra -pedantic-errors -Wformat=2 -Wcast-align -Wwrite-strings -Wfloat-equal -Wpointer-arith \
-Wno-uninitialized -Wno-unused-parameter
ifeq ($(DBG),1)
SUFFIX= .dbg
FLAGS+= -g
else
SUFFIX=
FLAGS+= -O3
endif
SRC= json.c
OBJ= $(SRC:%.c=$(OBJDIR)/%.o$(SUFFIX))
LIB= $(LIBDIR)/lib$(NAME)$(SUFFIX).a
.PHONY: default distclean clean depend
default: messages objdir_mk depend $(LIB)
messages:
ifeq ($(DBG),1)
@echo 'Compiling with Debug support...'
endif
clean:
@echo remove all objects
@rm -rf $(OBJDIR)
@rm -f test
distclean: clean
@rm -f $(DEPEND)
@rm -rf $(LIBDIR)
$(LIB): $(OBJ)
@echo
@echo 'creating library "$(LIB)"'
@mkdir -p $(LIBDIR)
@ar rv $@ $?
@ranlib $@
@echo '... done'
@echo
depend:
@echo
@echo 'checking dependencies'
@$(SHELL) -ec '$(CC) -MM $(CFLAGS) \
$(SRC) \
| sed '\''s@\(.*\)\.o[ :]@$(OBJDIR)/\1.o$(SUFFIX):@g'\'' \
>$(DEPEND)'
@echo
$(OBJDIR)/%.o$(SUFFIX): %.c
@echo 'compiling object file "$@" ...'
@$(CC) -c -o $@ $(FLAGS) $(CFLAGS) $<
objdir_mk:
@echo 'Creating $(OBJDIR) ...'
@mkdir -p $(OBJDIR)
test: test.c $(LIB)
@$(CC) -o $@ $(FLAGS) $(CFLAGS) -Llib $< -l$(NAME)$(SUFFIX)
-include $(DEPEND)
<file_sep>/json_config.h
#if !defined JSON_CONFIG_H
#define JSON_CONFIG_H
#if !defined json_char
#define json_char char
#endif
#if defined __cplusplus
#define HAVE__BOOL 1
#endif
#if !defined HAVE__BOOL
#define HAVE__BOOL 0
#endif
#endif /* JSON_CONFIG_H */
<file_sep>/json.c
/* vim: set et ts=3 sw=3 ft=c:
*
* Copyright (C) 2012 <NAME> et al. All rights reserved.
* https://github.com/udp/json-parser
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#if defined _WIN32
# pragma warning (push)
# pragma warning (disable : 4996)
#endif
#ifdef __cplusplus
# include <cassert>
#else
# include <assert.h>
#endif
#include "json.h"
#ifdef __cplusplus
const struct _json_value json_value_none; /* zero-d by ctor */
#else
const struct _json_value json_value_none = { NULL, json_none, {0}, {NULL} };
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <float.h>
#include <errno.h>
typedef unsigned short json_uchar;
static unsigned char hex_value (json_char c)
{
if (c >= 'A' && c <= 'F')
return (c - 'A') + 10;
if (c >= 'a' && c <= 'f')
return (c - 'a') + 10;
if (c >= '0' && c <= '9')
return c - '0';
return 0xFF;
}
typedef struct
{
json_settings settings;
int first_pass;
unsigned long used_memory;
unsigned int uint_max;
unsigned long ulong_max;
} json_state;
static void * json_alloc (json_state * state, unsigned long size, int zero)
{
void * mem;
if ((state->ulong_max - state->used_memory) < size)
return 0;
if (state->settings.max_memory
&& (state->used_memory += size) > state->settings.max_memory)
{
return 0;
}
if (! (mem = zero ? calloc (1, size) : malloc (size)))
return 0;
return mem;
}
static int new_value
(json_state * state, json_value ** top, json_value ** root, json_value ** alloc, json_type type)
{
json_value * value;
int values_size;
if (!state->first_pass)
{
value = *top = *alloc;
*alloc = (*alloc)->_reserved.next_alloc;
if (!*root)
*root = value;
switch (value->type)
{
case json_array:
if (! (value->u.array.values = (json_value **) json_alloc
(state, value->u.array.length * sizeof (json_value *), 0)) )
{
return 0;
}
break;
case json_object:
values_size = sizeof (*value->u.object.values) * value->u.object.length;
if (! ((*(void **) &value->u.object.values) = json_alloc
(state, values_size + ((unsigned long) value->u.object.values), 0)) )
{
return 0;
}
value->_reserved.object_mem = (*(char **) &value->u.object.values) + values_size;
break;
case json_string:
if (! (value->u.string.ptr = (json_char *) json_alloc
(state, (value->u.string.length + 1) * sizeof (json_char), 0)) )
{
return 0;
}
break;
default:
break;
};
value->u.array.length = 0;
return 1;
}
value = (json_value *) json_alloc (state, sizeof (json_value), 1);
if (!value)
return 0;
if (!*root)
*root = value;
value->type = type;
value->parent = *top;
if (*alloc)
(*alloc)->_reserved.next_alloc = value;
*alloc = *top = value;
return 1;
}
#define e_off \
((int) (i - cur_line_begin))
#define whitespace \
case '\n': ++ cur_line; cur_line_begin = i; \
case ' ': case '\t': case '\r'
#define string_add(b) \
do { if (!state.first_pass) string [string_length] = b; ++ string_length; } while (0);
static const int
flag_next = 1, flag_reproc = 2, flag_need_comma = 4, flag_seek_value = 8, flag_exponent = 16,
flag_got_exponent_sign = 32, flag_escaped = 64, flag_string = 128, flag_need_colon = 256,
flag_done = 512;
json_value * json_parse_ex (json_settings * settings, const json_char * json, char * error_buf)
{
json_char error [128];
unsigned int cur_line;
const json_char * cur_line_begin, * i;
json_value * top, * root, * alloc = 0;
json_state state;
int flags;
error[0] = '\0';
memset (&state, 0, sizeof (json_state));
memcpy (&state.settings, settings, sizeof (json_settings));
memset (&state.uint_max, 0xFF, sizeof (state.uint_max));
memset (&state.ulong_max, 0xFF, sizeof (state.ulong_max));
state.uint_max -= 8; /* limit of how much can be added before next check */
state.ulong_max -= 8;
for (state.first_pass = 1; state.first_pass >= 0; -- state.first_pass)
{
json_uchar uchar;
unsigned char uc_b1, uc_b2, uc_b3, uc_b4;
json_char * string;
unsigned int string_length;
top = root = 0;
flags = flag_seek_value;
cur_line = 1;
cur_line_begin = json;
for (i = json ;; ++ i)
{
json_char b = *i;
if (flags & flag_done)
{
if (!b)
break;
switch (b)
{
whitespace:
continue;
default:
sprintf (error, "%d:%d: Trailing garbage: `%c`", cur_line, e_off, b);
goto e_failed;
};
}
if (flags & flag_string)
{
if (!b)
{ sprintf (error, "Unexpected EOF in string (at %d:%d)", cur_line, e_off);
goto e_failed;
}
if (string_length > state.uint_max)
goto e_toolong;
if (flags & flag_escaped)
{
flags &= ~ flag_escaped;
switch (b)
{
case 'b': string_add ('\b'); break;
case 'f': string_add ('\f'); break;
case 'n': string_add ('\n'); break;
case 'r': string_add ('\r'); break;
case 't': string_add ('\t'); break;
case 'u':
if ((uc_b1 = hex_value (*++ i)) == 0xFF || (uc_b2 = hex_value (*++ i)) == 0xFF
|| (uc_b3 = hex_value (*++ i)) == 0xFF || (uc_b4 = hex_value (*++ i)) == 0xFF)
{
sprintf (error, "Invalid character value `%c` (at %d:%d)", b, cur_line, e_off);
goto e_failed;
}
uc_b1 = uc_b1 * 16 + uc_b2;
uc_b2 = uc_b3 * 16 + uc_b4;
uchar = ((json_char) uc_b1) * 256 + uc_b2;
if (sizeof (json_char) >= sizeof (json_uchar) || (uc_b1 == 0 && uc_b2 <= 0x7F))
{
string_add ((json_char) uchar);
break;
}
if (uchar <= 0x7FF)
{
if (state.first_pass)
string_length += 2;
else
{ string [string_length ++] = 0xC0 | ((uc_b2 & 0xC0) >> 6) | ((uc_b1 & 0x3) << 3);
string [string_length ++] = 0x80 | (uc_b2 & 0x3F);
}
break;
}
if (state.first_pass)
string_length += 3;
else
{ string [string_length ++] = 0xE0 | ((uc_b1 & 0xF0) >> 4);
string [string_length ++] = 0x80 | ((uc_b1 & 0xF) << 2) | ((uc_b2 & 0xC0) >> 6);
string [string_length ++] = 0x80 | (uc_b2 & 0x3F);
}
break;
default:
string_add (b);
};
continue;
}
if (b == '\\')
{
flags |= flag_escaped;
continue;
}
if (b == '"')
{
if (!state.first_pass)
string [string_length] = 0;
flags &= ~ flag_string;
string = 0;
switch (top->type)
{
case json_string:
top->u.string.length = string_length;
flags |= flag_next;
break;
case json_object:
if (state.first_pass)
(*(json_char **) &top->u.object.values) += string_length + 1;
else
{
top->u.object.values [top->u.object.length].name
= (json_char *) top->_reserved.object_mem;
(*(json_char **) &top->_reserved.object_mem) += string_length + 1;
}
flags |= flag_seek_value | flag_need_colon;
continue;
default:
break;
};
}
else
{
string_add (b);
continue;
}
}
if (flags & flag_seek_value)
{
switch (b)
{
whitespace:
continue;
case ']':
if (top->type == json_array)
flags = (flags & ~ (flag_need_comma | flag_seek_value)) | flag_next;
else if (!state.settings.settings & json_relaxed_commas)
{ sprintf (error, "%d:%d: Unexpected ]", cur_line, e_off);
goto e_failed;
}
break;
default:
if (flags & flag_need_comma)
{
if (b == ',')
{ flags &= ~ flag_need_comma;
continue;
}
else
{ sprintf (error, "%d:%d: Expected , before %c", cur_line, e_off, b);
goto e_failed;
}
}
if (flags & flag_need_colon)
{
if (b == ':')
{ flags &= ~ flag_need_colon;
continue;
}
else
{ sprintf (error, "%d:%d: Expected : before %c", cur_line, e_off, b);
goto e_failed;
}
}
flags &= ~ flag_seek_value;
switch (b)
{
case '{':
if (!new_value (&state, &top, &root, &alloc, json_object))
goto e_alloc_failure;
continue;
case '[':
if (!new_value (&state, &top, &root, &alloc, json_array))
goto e_alloc_failure;
flags |= flag_seek_value;
continue;
case '"':
if (!new_value (&state, &top, &root, &alloc, json_string))
goto e_alloc_failure;
flags |= flag_string;
string = top->u.string.ptr;
string_length = 0;
continue;
case 't':
if (*(++ i) != 'r' || *(++ i) != 'u' || *(++ i) != 'e')
goto e_unknown_value;
if (!new_value (&state, &top, &root, &alloc, json_boolean))
goto e_alloc_failure;
top->u.boolean = 1;
flags |= flag_next;
break;
case 'f':
if (*(++ i) != 'a' || *(++ i) != 'l' || *(++ i) != 's' || *(++ i) != 'e')
goto e_unknown_value;
if (!new_value (&state, &top, &root, &alloc, json_boolean))
goto e_alloc_failure;
flags |= flag_next;
break;
case 'n':
if (*(++ i) != 'u' || *(++ i) != 'l' || *(++ i) != 'l')
goto e_unknown_value;
if (!new_value (&state, &top, &root, &alloc, json_null))
goto e_alloc_failure;
flags |= flag_next;
break;
default:
if (isdigit ((int)b) || b == '-')
{
if (!new_value (&state, &top, &root, &alloc, json_integer))
goto e_alloc_failure;
flags &= ~ (flag_exponent | flag_got_exponent_sign);
if (state.first_pass)
continue;
if (top->type == json_double) {
top->u.dbl = strtod (i, (json_char **) &i);
if (errno == ERANGE)
goto e_overflow;
} else {
top->u.integer = strtol (i, (json_char **) &i, 10);
if (errno == ERANGE)
goto e_overflow;
}
flags |= flag_next | flag_reproc;
}
else
{ sprintf (error, "%d:%d: Unexpected %c when seeking value", cur_line, e_off, b);
goto e_failed;
}
};
};
}
else
{
switch (top->type)
{
case json_object:
switch (b)
{
whitespace:
continue;
case '"':
if (flags & flag_need_comma && (!state.settings.settings & json_relaxed_commas))
{
sprintf (error, "%d:%d: Expected , before \"", cur_line, e_off);
goto e_failed;
}
flags |= flag_string;
string = (json_char *) top->_reserved.object_mem;
string_length = 0;
break;
case '}':
flags = (flags & ~ flag_need_comma) | flag_next;
break;
case ',':
if (flags & flag_need_comma)
{
flags &= ~ flag_need_comma;
break;
}
default:
sprintf (error, "%d:%d: Unexpected `%c` in object", cur_line, e_off, b);
goto e_failed;
};
break;
case json_integer:
case json_double:
if (isdigit ((int)b))
continue;
if (b == 'e' || b == 'E')
{
if (!(flags & flag_exponent))
{
flags |= flag_exponent;
top->type = json_double;
continue;
}
}
else if (b == '+' || b == '-')
{
if (flags & flag_exponent && !(flags & flag_got_exponent_sign))
{
flags |= flag_got_exponent_sign;
continue;
}
}
else if (b == '.' && top->type == json_integer)
{
top->type = json_double;
continue;
}
flags |= flag_next | flag_reproc;
break;
default:
break;
};
}
if (flags & flag_reproc)
{
flags &= ~ flag_reproc;
-- i;
}
if (flags & flag_next)
{
flags = (flags & ~ flag_next) | flag_need_comma;
if (!top->parent)
{
/* root value done */
flags |= flag_done;
continue;
}
if (top->parent->type == json_array)
flags |= flag_seek_value;
if (!state.first_pass)
{
json_value * parent = top->parent;
switch (parent->type)
{
case json_object:
parent->u.object.values
[parent->u.object.length].value = top;
break;
case json_array:
parent->u.array.values
[parent->u.array.length] = top;
break;
default:
break;
};
}
if ( (++ top->parent->u.array.length) > state.uint_max)
goto e_toolong;
top = top->parent;
continue;
}
}
alloc = root;
}
return root;
e_unknown_value:
sprintf (error, "%d:%d: Unknown value", cur_line, e_off);
goto e_failed;
e_alloc_failure:
strcpy (error, "Memory allocation failure");
goto e_failed;
e_overflow:
sprintf (error, "%d:%d: numeral parser have occurred overflow", cur_line, e_off);
goto e_failed;
e_toolong:
sprintf (error, "%d:%d: Too long size object", cur_line, e_off);
goto e_failed;
e_failed:
if (error_buf)
{
if (*error)
strcpy (error_buf, error);
else
strcpy (error_buf, "Unknown error");
}
if (state.first_pass)
alloc = root;
while (alloc)
{
top = alloc->_reserved.next_alloc;
free (alloc);
alloc = top;
}
if (!state.first_pass)
json_value_free (root);
return 0;
}
json_value * json_parse (const json_char * json)
{
json_settings settings;
memset (&settings, 0, sizeof (json_settings));
return json_parse_ex (&settings, json, 0);
}
void json_value_free (json_value * value)
{
json_value * cur_value;
if (!value)
return;
value->parent = 0;
while (value)
{
switch (value->type)
{
case json_array:
if (!value->u.array.length)
{
free (value->u.array.values);
break;
}
value = value->u.array.values [-- value->u.array.length];
continue;
case json_object:
if (!value->u.object.length)
{
free (value->u.object.values);
break;
}
value = value->u.object.values [-- value->u.object.length].value;
continue;
case json_string:
free (value->u.string.ptr);
break;
default:
break;
};
cur_value = value;
value = value->parent;
free (cur_value);
}
}
void json_value_dump(FILE * fp, json_value const * v) {
void (* const rec)(FILE * fp, json_value const * v) = json_value_dump;
assert(fp);
if (v) {
unsigned int i;
switch (v->type) {
case json_none: // ??
fprintf(fp, "none");
break;
case json_object:
fprintf(fp, "{");
if (v->u.object.length >= 1) {
fprintf(fp, "\"%s\":", v->u.object.values[0].name);
rec(fp, v->u.object.values[0].value);
}
for (i=1; i<v->u.object.length; ++i) {
fprintf(fp, ",");
fprintf(fp, "\"%s\":", v->u.object.values[i].name);
rec(fp, v->u.object.values[i].value);
}
fprintf(fp, "}");
break;
case json_array:
fprintf(fp, "[");
if (v->u.array.length >= 1) {
rec(fp, v->u.array.values[0]);
}
for (i=1; i<v->u.array.length; ++i) {
fprintf(fp, ",");
rec(fp, v->u.array.values[i]);
}
fprintf(fp, "]");
break;
case json_integer:
fprintf(fp, "%ld", v->u.integer);
break;
case json_double:
fprintf(fp, "%lf", v->u.dbl);
break;
case json_string:
fprintf(fp, "\"%s\"", v->u.string.ptr);
break;
case json_boolean:
fprintf(fp, v->u.boolean ? "true" : "false");
break;
case json_null:
fprintf(fp, "null");
break;
default:
fprintf(stderr, "unknown format json value is passed\n");
break;
}
} else
fprintf(fp, "(NULL)");
}
char const * json_type_to_string(json_type ty) {
switch (ty) {
case json_none : return "json_none";
case json_object : return "json_object";
case json_array : return "json_array";
case json_integer : return "json_integer";
case json_double : return "json_double";
case json_string : return "json_string";
case json_boolean : return "json_boolean";
case json_null : return "json_null";
default : return NULL;
}
}
// implies
#define IMP(p,q) ((!(p)) || ((p) && (q)))
#define XOR(x,y) (((x) && (!(y))) || ((!(x)) && (y)))
static bool json_value_object_equal(json_value const * lhs, json_value const * rhs) {
unsigned int i;
if (lhs==rhs) return true; // given values are same object
if (XOR(lhs, rhs)) return false;
if (lhs->type!=json_object || rhs->type!=json_object)
return false; // type mismatch
if (lhs->u.object.length != rhs->u.object.length)
return false; // number of fields mismatch
for (i=0; i<lhs->u.object.length; ++i) {
// compare without ordering
json_value const * v = find_json_object(rhs, lhs->u.object.values[i].name);
if (!(v && json_value_equal(v, lhs->u.object.values[i].value)))
return false;
}
return true;
}
static bool json_value_array_equal(json_value const * lhs, json_value const * rhs) {
unsigned int i;
if (lhs==rhs) return true; // given values are same object
if (XOR(lhs, rhs)) return false;
if (lhs->type!=json_array || rhs->type!=json_array)
return false; // type mismatch
if (lhs->u.array.length != rhs->u.array.length)
return false; // number of fields mismatch
for (i=0; i<lhs->u.array.length; ++i) {
if (!json_value_equal(lhs->u.array.values[i], rhs->u.array.values[i]))
return false;
}
return true;
}
bool json_value_equal(json_value const * lhs, json_value const * rhs) {
if (lhs==rhs) return true;
if (XOR(lhs, rhs)) return false;
return lhs->type==rhs->type
&& IMP(lhs->type==json_none , false)
&& IMP(lhs->type==json_object , json_value_object_equal(lhs, rhs))
&& IMP(lhs->type==json_array , json_value_array_equal (lhs, rhs))
&& IMP(lhs->type==json_integer, lhs->u.integer==rhs->u.integer)
&& IMP(lhs->type==json_double , false) // can't declare valid comparison function
&& IMP(lhs->type==json_string , lhs->u.string.length==rhs->u.string.length
&& !strcmp(lhs->u.string.ptr, rhs->u.string.ptr))
&& IMP(lhs->type==json_boolean, lhs->u.boolean==rhs->u.boolean)
&& IMP(lhs->type==json_null , true);
}
static bool json_object_type_equal(json_value const * lhs, json_value const * rhs) {
unsigned int i;
if (lhs==rhs) return true; // given values are same object
if (XOR(lhs, rhs)) return false;
if (lhs->type!=json_object || rhs->type!=json_object)
return false; // type mismatch
if (lhs->u.object.length != rhs->u.object.length)
return false; // number of fields mismatch
for (i=0; i<lhs->u.object.length; ++i) {
// compare without ordering
json_value const * v = find_json_object(rhs, lhs->u.object.values[i].name);
if (!(v && json_type_equal(v, lhs->u.object.values[i].value)))
return false;
}
return true;
}
static bool json_array_type_equal(json_value const * lhs, json_value const * rhs) {
unsigned int i;
if (lhs==rhs) return true; // given values are same object
if (XOR(lhs, rhs)) return false;
if (lhs->type!=json_array || rhs->type!=json_array)
return false; // type mismatch
if (lhs->u.array.length != rhs->u.array.length)
return false; // number of fields mismatch
for (i=0; i<lhs->u.array.length; ++i) {
if (!json_type_equal(lhs->u.array.values[i], rhs->u.array.values[i]))
return false;
}
return true;
}
bool json_type_equal (json_value const * lhs, json_value const * rhs) {
if (lhs==rhs) return true;
if (XOR(lhs, rhs)) return false;
return lhs->type == rhs->type
&& IMP(lhs->type==json_none , false)
&& IMP(lhs->type==json_object , json_object_type_equal(lhs, rhs)) //
&& IMP(lhs->type==json_array , json_array_type_equal (lhs, rhs)) // compare recursively
&& IMP(lhs->type==json_integer, true)
&& IMP(lhs->type==json_double , true)
&& IMP(lhs->type==json_string , true)
&& IMP(lhs->type==json_boolean, true)
&& IMP(lhs->type==json_null , true);
}
#undef XOR
json_value const * find_json_object(json_value const * v, char const * field) {
if (v && v->type == json_object) {
unsigned int i;
for (i=0; i<v->u.object.length; ++i) {
if (!strcmp(v->u.object.values[i].name, field))
return v->u.object.values[i].value;
}
}
return NULL;
}
bool all_array_type(json_type ty, json_value const * js) {
if (js && js->type==json_array) {
size_t i;
for (i=0; i<js->u.array.length; ++i) {
json_value const * x = js->u.array.values[i];
if (!(x && x->type==ty))
return false;
}
return true;
} else
return false;
}
static json_value * make_json_value_none(void) {
json_value * json_ = (json_value*)calloc(1, sizeof(json_value));
if (!json_)
return NULL;
*json_ = json_value_none;
return json_;
}
json_value * json_value_dup(json_value const * json) {
json_value * json_ = NULL;
if (!json)
return NULL;
json_ = make_json_value_none();
if (!json_)
return NULL;
// copy tag
json_->type = json->type;
// copy body
if (json->type == json_integer) { json_->u.integer = json->u.integer; }
else if (json->type == json_double ) { json_->u.dbl = json->u.dbl; }
else if (json->type == json_boolean) { json_->u.boolean = json->u.boolean; }
else if (json->type == json_null ) { }
else if (json->type == json_string ) {
json_->u.string.length = json->u.string.length;
json_->u.string.ptr = strdup(json->u.string.ptr);
} else if (json->type == json_object) {
size_t i;
json_->u.object.length = json->u.object.length;
json_->u.object.values = calloc(json->u.object.length
/* because inner type have no name, get size from the NULL */
, sizeof(*((json_value*)NULL)->u.object.values));
for (i=0; i<json_->u.object.length; ++i) {
json_->u.object.values[i].name = strdup(json->u.object.values[i].name);
// recursive copy
json_->u.object.values[i].value = json_value_dup(json->u.object.values[i].value);
}
} else if (json->type == json_array) {
size_t i;
json_->u.array.length = json->u.array.length;
json_->u.array.values = calloc(json->u.array.length, sizeof(json_value));
for (i=0; i<json_->u.array.length; ++i)
// recursive copy
json_->u.array.values[i] = json_value_dup(json->u.array.values[i]);
} else if (json->type == json_none) {
} else {
free(json_);
return NULL;
}
return json_;
}
//
// constructor
//
json_value json_value_from_bool (bool b) {
json_value t = json_value_none;
t.type = json_boolean;
t.u.boolean = b;
return t;
}
json_value json_value_from_int (int x) {
json_value t = json_value_none;
t.type = json_integer;
t.u.integer = x;
return t;
}
json_value json_value_from_string(char const * str) {
json_value t = json_value_none;
t.type = json_string;
t.u.string.length = strlen(str);
#if defined WIN32
t.u.string.ptr = _strdup(str);
#else
t.u.string.ptr = strdup(str);
#endif
return t;
}
json_value json_value_from_real(double r) {
json_value t = json_value_none;
t.type = json_double;
t.u.dbl = r;
return t;
}
//
// discriminator
//
bool json_value_is_string (json_value v) { return v.type==json_string; }
bool json_value_is_number (json_value v) { return v.type==json_integer || v.type==json_double; }
bool json_value_is_array (json_value v) { return v.type==json_array ; }
bool json_value_is_object (json_value v) { return v.type==json_object; }
//
// accessor
//
bool json_value_read_if_uint(unsigned int * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& 0u <= v->u.integer
&& v->u.integer <= UINT_MAX)
{
*x = (unsigned int)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_int(int * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& INT_MIN <= v->u.integer
&& v->u.integer <= INT_MAX) {
*x = v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_uint8_t(uint8_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& 0 <= v->u.integer
&& v->u.integer <= UINT8_MAX)
{
*x = (uint8_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_uint16_t(uint16_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& 0 <= v->u.integer
&& v->u.integer <= UINT16_MAX)
{
*x = (uint16_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_uint32_t(uint32_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& 0 <= v->u.integer
&& v->u.integer <= UINT32_MAX)
{
*x = (uint32_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_uint64_t(uint64_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& 0 <= v->u.integer
//&& v->u.integer <= UINT32_MAX
)
{
*x = (uint32_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_uintptr_t(uintptr_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& 0 <= v->u.integer
&& v->u.integer <= UINTPTR_MAX)
{
*x = (uintptr_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_int8_t(int8_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& INT8_MIN <= v->u.integer
&& v->u.integer <= INT8_MAX)
{
*x = (int8_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_int16_t(int16_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& INT16_MIN <= v->u.integer
&& v->u.integer <= INT16_MAX)
{
*x = (int16_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_int32_t(int32_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& INT32_MIN <= v->u.integer
&& v->u.integer <= INT32_MAX)
{
*x = v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_int64_t(int64_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
// && INT64_MIN <= v->u.integer
// && v->u.integer <= INT64_MAX
)
{
*x = v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_intptr_t(intptr_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& INTPTR_MIN <= v->u.integer
&& v->u.integer <= INTPTR_MAX)
{
*x = (intptr_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_size_t(size_t * x, json_value const * v) {
assert(x);
if (v && v->type==json_integer
&& 0 <= v->u.integer
&& v->u.integer <= SIZE_MAX)
{
*x = (size_t)v->u.integer;
return true;
} else
return false;
}
bool json_value_read_if_float(float * f, json_value const * v) {
assert(f);
if (v && v->type==json_double
&& FLT_MIN <= v->u.dbl
&& v->u.dbl <= FLT_MAX)
{
*f = v->u.dbl;
return true;
} else
return false;
}
bool json_value_read_if_double(double * d, json_value const * v) {
assert(d);
if (v && v->type==json_double
// && FLT_MIN <= v->u.dbl
// && v->u.dbl <= FLT_MAX
)
{
*d = v->u.dbl;
return true;
} else
return false;
}
bool json_value_read_if_string(char * ss, json_value const * v) {
assert(ss);
if (v && v->type==json_string) {
strncpy(ss, v->u.string.ptr, 256);
return true;
} else
return false;
}
bool json_value_read_if_bool(bool * x, json_value const * v) {
assert(x);
if (v && v->type==json_boolean) {
*x = v->u.boolean != 0;
return true;
} else
return false;
}
<file_sep>/test.c
#define _CRT_SECURE_NO_WARNINGS
#if defined __cplusplus
# include <cstdio>
# include <cstdlib>
# include <cstdint>
# include <cstring>
# include <cassert>
#else
# include <stdio.h>
# include <stdlib.h>
# include <stdint.h>
# include <string.h>
# include <assert.h>
#endif
#include <error.h>
#include <errno.h>
#include "json.h"
#if defined _WIN32
# define SEP "\\"
#else
# define SEP "/"
#endif
static char const * valid_files[] = {
"valid-0000.json", "valid-0001.json",
"valid-0002.json", "valid-0003.json"
};
static int const valid_file_size = sizeof(valid_files)/sizeof(valid_files[0]);
static char const * invalid_files[] = {
"invalid-0000.json", "invalid-0001.json",
"invalid-0002.json", "invalid-0003.json",
"invalid-0004.json", "invalid-0005.json"
};
static int const invalid_file_size = sizeof(invalid_files)/sizeof(invalid_files[0]);
static long file_size(FILE * fp) {
int curr = ftell(fp);
int size=0;
fseek(fp, 0 , SEEK_END); // begin of fp
size = ftell(fp);
fseek(fp, curr, SEEK_SET); // recovery offset
if (size==-1)
fprintf(stderr, "%s\n", strerror(errno));
return size;
}
// read all contents of given file
char * read_file (char const * file) {
FILE * fp = fopen(file, "r");
if (fp) {
int size = file_size(fp);
char * buf = (char*)malloc(size > 1 ? size : 1); // avoid undefined behaviour
if (buf) {
size_t rsize = fread(buf, 1, size, fp);
if (rsize<(size_t)size) {
fprintf(stderr, "%s\n", strerror(errno));
free(buf);
} else {
buf[rsize]='\0';
return buf;
}
}
}
return NULL;
}
// return true if parsing given file is successed
bool test_json_parse_file(char const * dir, char const * filename) {
char path[256];
char * buf=NULL;
sprintf(path, "%s" SEP "%s", dir, filename);
buf = read_file(path);
if (buf) {
json_value * v = json_parse(buf);
return json_value_free(v), v!=NULL;
} else {
fprintf(stderr, "read file <%s> failed\n", path);
return false;
}
}
bool test_json_parse (char const * s) {
json_value * v = json_parse(s);
json_value_free(v);
if (v)
printf("test parse (%s) passed\n", s);
else
printf("test parse (%s) failed\n", s);
return v!=NULL;
}
bool test_find_json_object(void) {
json_value * v = json_parse("{\"foo\":314}");
return v && find_json_object(v, "foo") ;
}
#if defined _WIN32
# define __func__ __FUNCTION__
#endif
#define TEST_JSON_VALUE_CMP(cmp, lhs, rhs) \
do { \
json_value * lhs_ = (lhs); \
json_value * rhs_ = (rhs); \
printf("%s:%5d@%-10s: ", __FILE__, __LINE__, __func__); \
if (cmp(lhs_, rhs_)) { \
printf("pass\n"); \
} else { \
json_value_dump(stdout, lhs); \
printf(" != "); \
json_value_dump(stdout, rhs); \
printf("\n"); \
} \
json_value_free(lhs_); \
json_value_free(rhs_); \
} while (0)
#define TEST_JSON_VALUE_EQ(lhs, rhs) TEST_JSON_VALUE_CMP( json_value_equal, lhs, rhs)
#define TEST_JSON_VALUE_NOT_EQ(lhs, rhs) TEST_JSON_VALUE_CMP(!json_value_equal, lhs, rhs)
#define TEST_JSON_TYPE_EQ(lhs, rhs) TEST_JSON_VALUE_CMP( json_type_equal, lhs, rhs)
#define TEST_JSON_TYPE_NOT_EQ(lhs, rhs) TEST_JSON_VALUE_CMP( !json_type_equal, lhs, rhs)
void test_json_value_equal(void) {
// expect equal
TEST_JSON_VALUE_EQ(NULL, NULL);
TEST_JSON_VALUE_EQ(json_parse("314"), json_parse("314"));
TEST_JSON_VALUE_EQ(json_parse("null"), json_parse("null"));
TEST_JSON_VALUE_EQ(json_parse("{}"), json_parse("{}"));
TEST_JSON_VALUE_EQ(json_parse("[]"), json_parse("[]"));
TEST_JSON_VALUE_EQ(json_parse("[1,2,3]"), json_parse("[1,2,3]"));
TEST_JSON_VALUE_EQ(json_parse("[]"), json_parse("[]"));
TEST_JSON_VALUE_EQ(json_parse("\"\""), json_parse("\"\""));
TEST_JSON_VALUE_EQ(json_parse("\"foo\""), json_parse("\"foo\""));
TEST_JSON_VALUE_EQ(json_parse("\"foo bar bazz\""), json_parse("\"foo bar bazz\""));
TEST_JSON_VALUE_EQ(json_parse("[7298,\"\",{}]") , json_parse("[7298,\"\",{}]"));
TEST_JSON_VALUE_EQ(json_parse("{\"foo\":123}"), json_parse("{\"foo\":123}"));
TEST_JSON_VALUE_EQ(json_parse("{\"test.c\":256, \"json.c\":512}"), json_parse("{\"json.c\":512, \"test.c\":256}"));
TEST_JSON_VALUE_EQ(json_parse("{\"alice\":[12,\"white rabbit\"] \
, \"knight\":[\"KJQ\" \
, \"as the Knight fell heavily on the top of his head exactly in the path where Alice was walking.\"]}")
, json_parse("{\"knight\":[\"KJQ\" \
, \"as the Knight fell heavily on the top of his head exactly in the path where Alice was walking.\"] \
, \"alice\":[12,\"white rabbit\"]}"));
TEST_JSON_VALUE_EQ(json_parse("{\"define\": [\"fib\", [\"lambda\", \"x\" \
, [\"cond\", \
[[\"eq\", \"x\", 0], 1], \
[[\"eq\", \"x\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"x\", 1]], [\"fib\", [\"-\", \"x\", 2]]]]]]]]}")
, json_parse("{\"define\": [\"fib\", [\"lambda\", \"x\" \
, [\"cond\", \
[[\"eq\", \"x\", 0], 1], \
[[\"eq\", \"x\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"x\", 1]], [\"fib\", [\"-\", \"x\", 2]]]]]]]]}"));
// expect *not* equal
TEST_JSON_VALUE_NOT_EQ(json_parse("[]"), json_parse("{}"));
TEST_JSON_VALUE_NOT_EQ(json_parse("314"), json_parse("315"));
TEST_JSON_VALUE_NOT_EQ(json_parse("1.42"), json_parse("1.42"));
TEST_JSON_VALUE_NOT_EQ(json_parse("\"foo bar bazz\""), json_parse("\"foo bar bazz \""));
TEST_JSON_VALUE_NOT_EQ(json_parse("\" foo bar bazz\""), json_parse("\"foo bar bazz\""));
TEST_JSON_VALUE_NOT_EQ(json_parse("[20, 30, 40]"), json_parse("[30, 40, 20]"));
TEST_JSON_VALUE_NOT_EQ(json_parse("{\"define\": [\"fib\", [\"lambda\", \"x\" \
, [\"cond\", \
[[\"eq\", \"x\", 0], 1], \
[[\"eq\", \"x\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"x\", 1]], [\"fib\", [\"-\", \"x\", 2]]]]]]]]}")
, json_parse("{\"define\": [\"fib\", [\"lambda\", \"y\" \
, [\"cond\", \
[[\"eq\", \"y\", 0], 1], \
[[\"eq\", \"y\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"y\", 1]], [\"fib\", [\"-\", \"y\", 2]]]]]]]]}"));
}
void test_json_type_equal (void) {
// expect equal
TEST_JSON_TYPE_EQ(NULL, NULL);
TEST_JSON_TYPE_EQ(json_parse("314"), json_parse("314"));
TEST_JSON_TYPE_EQ(json_parse("234"), json_parse("678"));
TEST_JSON_TYPE_EQ(json_parse("0"), json_parse("1"));
TEST_JSON_TYPE_EQ(json_parse("null"), json_parse("null"));
TEST_JSON_TYPE_EQ(json_parse("{}"), json_parse("{}"));
TEST_JSON_TYPE_EQ(json_parse("[]"), json_parse("[]"));
TEST_JSON_TYPE_EQ(json_parse("[1,2,3]"), json_parse("[1,2,3]"));
TEST_JSON_TYPE_EQ(json_parse("[1,[2,[3]]]"), json_parse("[1, [2, [ 3] ]]"));
TEST_JSON_TYPE_EQ(json_parse("[]"), json_parse("[]"));
TEST_JSON_TYPE_EQ(json_parse("\"\""), json_parse("\"\""));
TEST_JSON_TYPE_EQ(json_parse("\"foo\""), json_parse("\"foo\""));
TEST_JSON_TYPE_EQ(json_parse("\"foo bar bazz\""), json_parse("\"foo bar bazz\""));
TEST_JSON_TYPE_EQ(json_parse("[7298,\"\",{}]") , json_parse("[7298,\"\",{}]"));
TEST_JSON_TYPE_EQ(json_parse("{\"foo\":123}"), json_parse("{\"foo\":123}"));
TEST_JSON_TYPE_EQ(json_parse("{\"test.c\":256, \"json.c\":512}"), json_parse("{\"json.c\":512, \"test.c\":256}"));
TEST_JSON_TYPE_EQ(json_parse("{\"alice\":[12,\"white rabbit\"] \
, \"knight\":[\"KJQ\" \
, \"as the Knight fell heavily on the top of his head exactly in the path where Alice was walking.\"]}")
, json_parse("{\"knight\":[\"KJQ\" \
, \"as the Knight fell heavily on the top of his head exactly in the path where Alice was walking.\"] \
, \"alice\":[12,\"white rabbit\"]}"));
TEST_JSON_TYPE_EQ(json_parse("{\"define\": [\"fib\", [\"lambda\", \"x\" \
, [\"cond\", \
[[\"eq\", \"x\", 0], 1], \
[[\"eq\", \"x\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"x\", 1]], [\"fib\", [\"-\", \"x\", 2]]]]]]]]}")
, json_parse("{\"define\": [\"fib\", [\"lambda\", \"x\" \
, [\"cond\", \
[[\"eq\", \"x\", 0], 1], \
[[\"eq\", \"x\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"x\", 1]], [\"fib\", [\"-\", \"x\", 2]]]]]]]]}"));
// expect *not* equal
TEST_JSON_TYPE_NOT_EQ(json_parse("[]"), json_parse("{}"));
TEST_JSON_TYPE_NOT_EQ(json_parse("1.42"), json_parse("[1.42]"));
TEST_JSON_TYPE_NOT_EQ(json_parse("[1,[2,[3,[{}]]]]"), json_parse("[1,[2,[3]]]"));
TEST_JSON_TYPE_NOT_EQ(json_parse("\"foo bar bazz\""), json_parse("{\"\":\"foo bar bazz \"}"));
TEST_JSON_TYPE_NOT_EQ(json_parse("[\"foo\", \"bar\", \"bazz\"]"), json_parse("[\"foo\" \"bazz\", \"bar\"]"));
TEST_JSON_TYPE_NOT_EQ(json_parse("[20, 30, 40]"), json_parse("[30, [40, [20]]]"));
TEST_JSON_TYPE_NOT_EQ(json_parse("{\"define\": [\"fib\", [\"lambda\", \"x\" \
, {\"cond\": [\
[[\"eq\", \"x\", 0], 1], \
[[\"eq\", \"x\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"x\", 1]], [\"fib\", [\"-\", \"x\", 2]]]]]]}]]}")
, json_parse("{\"define\": [\"fib\", [\"lambda\", \"y\" \
, [\"cond\", \
[[\"eq\", \"y\", 0], 1], \
[[\"eq\", \"y\", 1], 1], \
[[\"other\", [\"+\", [\"fib\", [\"-\", \"y\", 1]], [\"fib\", [\"-\", \"y\", 2]]]]]]]]}"));
}
int main () {
int i;
for (i=0; i<valid_file_size; ++i) {
// require success
printf("test json_parse(%s) is %s\n", valid_files[i]
, test_json_parse_file("tests", valid_files[i]) ? "pass" : "fail");
}
for (i=0; i<invalid_file_size; ++i) {
// require fail
printf("test json_parse(%s) is %s\n", invalid_files[i]
, !test_json_parse_file("tests", invalid_files[i]) ? "pass" : "fail");
}
test_json_value_equal();
test_json_type_equal ();
return 0;
}
| 9a4547495149a2a88435ecb69e1d06234e79ebaa | [
"Markdown",
"C",
"Makefile"
] | 5 | Markdown | eldesh/json-parser | 33df83a863fcdc6576ac91ae5ad7bf5c66d4bde4 | 405886a87f69087e625e457bca38372712abd564 |
refs/heads/master | <file_sep>#include <iostream> //for cout
using std::cout;
//Requires T to implement + operator
template<class T>
T add(T a, T b) {
return a + b;
}
int main(int argc, char** argv) {
int a = 3, b = 4;
cout << "add(3,4): " << add(a,b) << "\n";
return 0;
}
<file_sep>#include <iostream> //for cout
using std::cout;
void incrVar(int *pointerToVal) {
//*pointerToVal to set value pointerToVal is pointing to
*pointerToVal = *pointerToVal + 1;
}
int main(int argc, char** argv) {
int i = 10;
cout << "i before incrVal(&i): " << i << "\n";
incrVar(&i);
cout << "i after incrVal(&i): " << i << "\n";
}<file_sep>// Requires T to implement "<" operator
// Requires startLeft <= startRight <= end
template<class T>
void merge(T* list, int startLeft, int startRight, int end) {
int posLeft = startLeft;
int posRight = startRight;
int posTemp = 0;
T* tempList = new T[end-startLeft+1];
while (posLeft < startRight && posRight <= end) {
if (list[posLeft] < list[posRight]) {
tempList[posTemp++] = list[posLeft++];
} else {
tempList[posTemp++] = list[posRight++];
}
}
while (posLeft < startRight) {
tempList[posTemp++] = list[posLeft++];
}
while (posRight <= end) {
tempList[posTemp++] = list[posRight++];
}
for (int i=startLeft; i<=end; i++) {
list[i] = tempList[i-startLeft];
}
delete[] tempList;
}
// Requires T to implement "<" operator
template<class T>
void mergeSort(T* list, int start, int end) {
if (start < end) {
int endLeft = (start + end)/2;
mergeSort(list, start, endLeft); //mergeSort left
mergeSort(list, endLeft+1, end); //mergeSort right
merge(list, start, endLeft+1, end); //merge sorted lists
}
}
<file_sep>#include "mergeSort.h"
#include <cassert>
void testMergeSingleElement() {
int list[2];
list[0] = 5;
list[1] = 3;
merge(list, 0, 0, 0); //left=[], right=[5]
//merge on single element moves nothing
assert(list[0] == 5);
assert(list[1] == 3);
}
//If left list is empty, should take all elements from right list
void testMergeEmptyLeftList() {
int list[3];
list[0] = 4;
list[1] = 3;
list[2] = 8;
merge(list, 1, 1, 2); //left=[],right=[3,8]
//merge uses all elements from right, expect same array
assert(list[0] == 4);
assert(list[1] == 3);
assert(list[2] == 8);
}
void testMergeTwoOutOfOrderElements() {
int list[2];
list[0] = 5;
list[1] = 3;
merge(list, 0, 1, 1); //left=[5], right=[3]
//merge should insert 3 before 5
assert(list[0] == 3);
assert(list[1] == 5);
}
void testMergeTwoSortedSublists() {
int list[5];
list[0] = 2;
list[1] = 4; //left = [2,4]
list[2] = 0;
list[3] = 3;
list[4] = 6; //right = [0,3,6]
merge(list, 0, 2, 4);
//expect [0,2,3,4,6]
assert(list[0] == 0);
assert(list[1] == 2);
assert(list[2] == 3);
assert(list[3] == 4);
assert(list[4] == 6);
}
void testMergeSortSingleElement() {
int list[1];
list[0] = 4;
mergeSort(list, 0, 0);
assert(list[0] == 4);
}
void testMergeSortFromReverseOrder() {
int list[3];
list[0] = 3;
list[1] = 2;
list[2] = 1;
mergeSort(list, 0, 2);
assert(list[0] == 1);
assert(list[1] == 2);
assert(list[2] == 3);
}
void testMergeSortRandomOrder() {
int list[5];
list[0] = 2;
list[1] = 1;
list[2] = 3;
list[3] = 5;
list[4] = 4;
mergeSort(list, 0, 4);
assert(list[0] == 1);
assert(list[1] == 2);
assert(list[2] == 3);
assert(list[3] == 4);
assert(list[4] == 5);
}
void testMerge() {
testMergeSingleElement();
testMergeEmptyLeftList();
testMergeTwoOutOfOrderElements();
testMergeTwoSortedSublists();
}
void testMergeSort() {
testMergeSortSingleElement();
testMergeSortFromReverseOrder();
testMergeSortRandomOrder();
}
int main(int argc, char** argv) {
testMerge();
testMergeSort();
}
| 876ad6582e0483ed7bdf3c699e3eece2233eeb2b | [
"C++"
] | 4 | C++ | seigensei/cppSamples | 436cef6bf24b244ce822b72e7a3f61d410359203 | 154397c9fdd181b10ee379df899c4292206bda4b |
refs/heads/master | <file_sep># Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Reading the dataset
dataset = pd.read_excel('./data/HousingPrice.xls')
# Define unused columns
ununsed_columns = ["Order", "PID"]
dataset = dataset.drop(ununsed_columns, axis = 1)
# dataset = dataset.dropna(how = 'any', axis = 0)
price = dataset["SalePrice"]
dataset = dataset.drop(['SalePrice'], axis = 1)
dataset.info()
dataset.describe()
# Separating the dataset and output
# X = dataset.iloc[:, :-1].values
# y = dataset.iloc[:, 21].values
# Label Encoding
from sklearn.preprocessing import LabelEncoder
labelencoder_X = LabelEncoder()
dataset["MS Zoning"] = labelencoder_X.fit_transform(dataset["MS Zoning"])
dataset["Lot Shape"] = labelencoder_X.fit_transform(dataset["Lot Shape"])
dataset["Utilities"] = labelencoder_X.fit_transform(dataset["Utilities"])
dataset["Condition 1"] = labelencoder_X.fit_transform(dataset["Condition 1"])
dataset["Condition 2"] = labelencoder_X.fit_transform(dataset["Condition 2"])
dataset["Bldg Type"] = labelencoder_X.fit_transform(dataset["Bldg Type"])
dataset["House Style"] = labelencoder_X.fit_transform(dataset["House Style"])
dataset["Foundation"] = labelencoder_X.fit_transform(dataset["Foundation"])
dataset["Bsmt Qual"] = labelencoder_X.fit_transform(dataset["Bsmt Qual"])
dataset["Central Air"] = labelencoder_X.fit_transform(dataset["Central Air"])
dataset["Kitchen Qual"] = labelencoder_X.fit_transform(dataset["Kitchen Qual"])
# Splitting the dataset into Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(dataset, price, test_size=0.20, random_state=42)
# Fitting MLR to the training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the Test set results
y_pred = regressor.predict(X_test)
from sklearn.metrics import r2_score
print(r2_score(y_test, y_pred))
| 7296aef4d48685d518913971377970d6a8c2ecdd | [
"Python"
] | 1 | Python | AJAjay/ML_Basics | 0091db3bb771bdb09b8447e33d7a0dfdf69ee606 | d91076f1c75db247dd4482dab0e65870e1c3e912 |
refs/heads/master | <file_sep>var DamageTypes = require('./damage-types');
var Roller = require('../roller/roller');
module.exports = {
Club: {
name: "Club",
image: "images/weapons/club.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Movements);
},
},
Dagger: {
name: "Dagger",
image: "images/weapons/dagger.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Greatclub: {
name: "Greatclub",
image: "images/weapons/greatclub.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Movements);
},
},
Handaxe: {
name: "Handaxe",
image: "images/weapons/handaxe.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Javelin: {
name: "Javelin",
image: "images/weapons/javelin.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Mace: {
name: "Mace",
image: "images/weapons/mace.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Movements);
},
},
Quarterstaff: {
name: "Quarterstaff",
image: "images/weapons/quaterstaff.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Movements);
},
},
Sickle: {
name: "Sickle",
image: "images/weapons/sickle.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Spear: {
name: "Spear",
image: "images/weapons/spear.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Battleaxe: {
name: "Battleaxe",
image: "images/weapons/battleaxe.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Flail: {
name: "Flail",
image: "images/weapons/flail.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Movements);
},
},
Glaive: {
name: "Glaive",
image: "images/weapons/glaive.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Greataxe: {
name: "Greataxe",
image: "images/weapons/greataxe.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Greatsword: {
name: "Greatsword",
image: "images/weapons/greatsword.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Halberd: {
name: "Halberd",
image: "images/weapons/halberd.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Lance: {
name: "Lance",
image: "images/weapons/lance.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Longsword: {
name: "Longsword",
image: "images/weapons/longsword.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Maul: {
name: "Maul",
image: "images/weapons/maul.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Movements);
},
},
Morningstar: {
name: "Morningstar",
image: "images/weapons/morningstar.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Pike: {
name: "Pike",
image: "images/weapons/pike.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Rapier: {
name: "Rapier",
image: "images/weapons/rapier.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Scimitar: {
name: "Scimitar",
image: "images/weapons/scimitar.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
},
Shortsword: {
name: "Shortsword",
image: "images/weapons/shortsword.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Trident: {
name: "Trident",
image: "images/weapons/trident.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
War_Pick: {
name: "<NAME>",
image: "images/weapons/warpick.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Piercing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Piercing.Movements);
},
},
Warhammer: {
name: "Warhammer",
image: "images/weapons/warhammer.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Bludgeoning.Movements);
},
},
Whip: {
name: "Whip",
image: "images/weapons/whip.png",
rollMotion: function() {
return Roller.selectFromList(DamageTypes.Slashing.Motions);
},
rollMovement: function() {
return Roller.selectFromList(DamageTypes.Slashing.Movements);
},
}
}<file_sep>var React = require('react');
var ReactDOM = require('react-dom');
module.exports = React.createClass({
render: function() {
if (this.props.children.reroll != undefined) {
return <span><a href="#" title="Reroll this part" onClick={() => {this.props.reRollDescriptionPart(this.props.descriptionKey, this.props.children.key)}}>{this.props.children.text}</a></span>
}
return <span>{this.props.children.text}</span>
}
});
<file_sep># html-description-roller
A tool to randomly generate and render a text description, with a focus on allowing re-rolling of individual components
<file_sep>var React = require('react');
var ReactDOM = require('react-dom');
module.exports = React.createClass({
render: function() {
return <div>
<ul className="weapon-list">{this.props.children.map(weapon => {
return <li className="weapon" key={weapon.name}><a href="#" onClick={() => {this.props.newAttack(weapon)}}><img src={weapon.image} />{weapon.name}</a></li>
})}</ul>
<div>Icons made by <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div>
<div>Icons made by <a href="http://www.flaticon.com/authors/nikita-golubev" title="<NAME>"><NAME></a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a>
<div>Icons made by <a href="http://www.flaticon.com/authors/madebyoliver" title="Madebyoliver">Madebyoliver</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div>
</div></div>
}
});
<file_sep>var React = require('react');
var ReactDOM = require('react-dom');
var DescriptionRenderer = require('./description');
module.exports = React.createClass({
render: function() {
return <div>{this.props.children.map(description => {
return <DescriptionRenderer key={description.key} reRollDescription={this.props.reRollDescription} reRollDescriptionPart ={this.props.reRollDescriptionPart}>{description}</DescriptionRenderer>
})}</div>
}
});
<file_sep>module.exports = {
getAttack: function(weapon) {
return {
image: weapon.image,
parts: [{
key: 0,
text: "You ",
reroll: undefined,
},{
key: 1,
text: weapon.rollMotion(),
reroll: weapon.rollMotion
},
{
key: 2,
text: " your ",
reroll: undefined,
},
{
key: 3,
text: weapon.name + " ",
reroll: undefined,
},{
key: 4,
text: weapon.rollMovement(),
reroll: weapon.rollMovement
}],
reroll: function() {
return module.exports.getAttack(weapon);
},
};
}
}<file_sep>module.exports = {
selectFromList(list) {
return list[Math.floor(Math.random()*list.length)];
}
} | e5ade7ad51a9b67329f37977526cea9bf7d5b569 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | adamlynam/html-description-roller | e325f99688f88e86f500057f5374cd78f73cf95a | 1cf6feb5b12bb24768c8a32ffdac71f14b9295b6 |
refs/heads/master | <file_sep>#ifndef PACKETLISTENER_H
#define PACKETLISTENER_H
#include <WS2tcpip.h>
#include <pcap.h>
#include "ThreadPool.h"
#include "PacketStructs.h"
#include "TrafficManagerList.h"
namespace PacketListenerClass {
struct AdapterInfo {
size_t frameHeaderLen;
};
class PacketListener {
public:
std::set<TrafficManagerListClass::ListItem> processes;
void *udp4Table = nullptr;
void *tcp4Table = nullptr;
PacketListener();
void StartListening();
void StopListening();
~PacketListener();
private:
char errbuf[PCAP_ERRBUF_SIZE];
bool stopListening;
ThreadPoolClass::ThreadPool *threadPool;
void StartListeningToDevice(pcap_if_t *device);
void SetPacketFilter(pcap_t *adapterHandle,
unsigned int netmask,
std::string expression);
void HandlePacket(PacketStructs::PacketInformation packet);
void InitNpcapDllPath();
char *IPv4ToStr(unsigned int ip, char *str, size_t strLen);
char *IPv6ToStr(struct sockaddr *sockaddr, char *address, int addrlen);
};
} // namespace PacketListenerClass
#endif // !PACKETLISTENER_H
<file_sep>#define WIN32_LEAN_AND_MEAN
#include <iostream>
#include "TrafficManager.h"
#include <windows.h>
//#pragma comment(lib, "Comctl32")
int WINAPI wWinMain(HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
PWSTR lpszArgument,
int nCmdShow) {
TrafficManagerClass::TrafficManager trafficManager;
if (trafficManager.Create(WS_EX_ACCEPTFILES, RGB(255, 255, 255))) {
return 1;
}
ShowWindow(trafficManager.GetHWnd(), nCmdShow);
MSG msg = {};
BOOL bRet;
while (bRet = GetMessage(&msg, NULL, 0, 0)) {
if (bRet == -1) {
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
<file_sep>#ifndef PACKETSTRUCTS_H
#define PACKETSTRUCTS_H
#include <chrono>
namespace PacketStructs {
struct IPv4Address {
unsigned char byte1;
unsigned char byte2;
unsigned char byte3;
unsigned char byte4;
IPv4Address(unsigned int ip)
: byte1(((unsigned char *)&ip)[0]),
byte2(((unsigned char *)&ip)[1]),
byte3(((unsigned char *)&ip)[2]),
byte4(((unsigned char *)&ip)[3]) {}
inline bool operator==(const int &r) const {
return *((int *)this) == r;
}
inline bool operator!=(const int &r) const {
return !(*this == r);
}
inline bool operator<(const int &r) const {
return *((int *)this) < r;
}
inline bool operator>(const int &r) const {
return *((int *)this) > r;
}
inline bool operator<=(const int &r) const {
return !(*this > r);
}
inline bool operator>=(const int &r) const {
return !(*this < r);
}
inline bool operator==(const IPv4Address &r) const {
return *this == *((int *)&r);
}
inline bool operator!=(const IPv4Address &r) const {
return !(*this == r);
}
inline bool operator<(const IPv4Address &r) const {
return *this < *((int *)&r);
}
inline bool operator>(const IPv4Address &r) const {
return r < *this;
}
inline bool operator<=(const IPv4Address &r) const {
return !(*this > r);
}
inline bool operator>=(const IPv4Address &r) const {
return !(*this < r);
}
};
struct IPHeader {
unsigned char versionAndInternetHeaderlen; // Version (4 bits) + Internet header
// length (4 bits)
unsigned char typeOfService;
unsigned short totalLen;
unsigned short identification;
unsigned short flagsAndFragmentOffset; // Flags (3 bits) + Fragment offset (13 bits)
unsigned char timeToLive;
unsigned char protocol;
unsigned short crc; // Header checksum
IPv4Address srcAddr;
IPv4Address destAddr;
unsigned int optionAndPadding; // Option + Padding
};
struct UDPHeader {
unsigned short srcPort;
unsigned short destPort;
unsigned short totalLen;
unsigned short crc; // Checksum
};
struct FullAddress {
IPv4Address ip;
unsigned short port;
FullAddress(IPv4Address ip, unsigned short port) : ip(ip), port(port) {}
inline bool operator==(const FullAddress &r) const {
return (this->ip == r.ip) && (this->port == r.port);
}
inline bool operator!=(const FullAddress &r) const {
return !(*this == r);
}
inline bool operator<(const FullAddress &r) const {
return (this->ip < r.ip
? true
: (this->ip == r.ip ? (this->port < r.port) : false));
}
};
struct PacketInformation {
unsigned short size;
FullAddress src;
FullAddress dest;
bool incoming;
std::chrono::milliseconds msSinceEpoch;
PacketInformation(unsigned short size,
FullAddress src,
FullAddress dest,
bool incoming,
std::chrono::milliseconds msSinceEpoch)
: size(size),
src(src),
dest(dest),
incoming(incoming),
msSinceEpoch(msSinceEpoch) {}
};
} // namespace PacketStructs
#endif // !PACKETSTRUCTS_H
<file_sep>#include "TrafficManagerList.h"
#include <commctrl.h>
#include <chrono>
#include "Debugger.h"
namespace TrafficManagerListClass {
TrafficManagerList::TrafficManagerList() {}
HWND TrafficManagerList::CreateControl(PCWSTR lpClassName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent,
HMENU hMenu,
HINSTANCE hInstance,
LPVOID lpParam) {
BaseWindowClass::BaseWindow<TrafficManagerList>::CreateControl(lpClassName,
dwStyle,
x,
y,
nWidth,
nHeight,
hWndParent,
hMenu,
hInstance,
lpParam);
LVCOLUMN lvc;
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT |
LVCF_SUBITEM; // LVCF_IMAGE | LVCF_ORDER | LVCF_MINWIDTH |
// LVCF_DEFAULTWIDTH | LVCF_IDEALWIDTH
lvc.fmt = LVCFMT_CENTER;
for (int i = 0; i < columns.size(); i++) {
lvc.cx = columns[i].width;
lvc.pszText = &(columns[i].name[0]);
lvc.iSubItem = i;
ListView_InsertColumn(hWnd, lvc.iSubItem, &lvc);
}
ListView_SetExtendedListViewStyleEx(hWnd, LVS_EX_DOUBLEBUFFER, LVS_EX_DOUBLEBUFFER);
return hWnd;
}
HWND TrafficManagerList::CreateControl(HWND hWndParent) {
RECT rcClient;
GetClientRect(hWndParent, &rcClient);
return CreateControl(
WC_LISTVIEW,
WS_VISIBLE | WS_CHILD | LVS_REPORT | LVS_EDITLABELS,
parentMargin.left,
parentMargin.top,
rcClient.right - parentMargin.right - parentMargin.left,
rcClient.bottom - parentMargin.bottom - parentMargin.top,
hWndParent);
}
void TrafficManagerList::InsertItems(std::set<TrafficManagerListClass::ListItem> &processes) {
LVITEM lvItem;
lvItem.mask = LVIF_TEXT | LVIF_STATE;
lvItem.stateMask = 0;
lvItem.state = 0;
int iItem = 0;
std::wstring wstr;
for (auto process : processes)
{
// Path
lvItem.iSubItem = 0;
lvItem.iItem = iItem;
lvItem.pszText = &process.name[0];
if (ListView_InsertItem(hWnd, &lvItem) == -1) {
DebuggerClass::Debugger::PrintlnW(L"Insertion of item ", iItem, " failed");
continue;
}
// PID
lvItem.iSubItem = 1;
wstr = std::to_wstring(process.pid);
lvItem.pszText = &wstr[0];
if (ListView_SetItem(hWnd, &lvItem) == false) {
DebuggerClass::Debugger::PrintlnW(L"Setting item ", iItem, " subitem 1 failed");
continue;
}
// Bytes/second
lvItem.iSubItem = 2;
wstr = std::to_wstring(process.bytesPerMinute/60);
lvItem.pszText = &wstr[0];
if (ListView_SetItem(hWnd, &lvItem) == false) {
DebuggerClass::Debugger::PrintlnW(L"Setting item ", iItem, " subitem 2 failed");
continue;
}
}
}
void TrafficManagerList::DeleteAllItems() {
ListView_DeleteAllItems(hWnd);
}
LRESULT CALLBACK TrafficManagerList::HandleMessage(UINT uMsg,
WPARAM wParam,
LPARAM lParam) {
switch (uMsg) {
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
} // namespace TrafficManagerListClass<file_sep>#ifndef BASEWINDOW_H
#define BASEWINDOW_H
#define LEAN_AND_MEAN
#include <windows.h>
namespace BaseWindowClass {
template <class T>
class BaseWindow {
public:
BaseWindow() : hWnd(nullptr) {}
static LRESULT CALLBACK WindowProc(HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam) {
T *pThis = nullptr;
if (uMsg == WM_CREATE) {
CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
pThis = static_cast<T *>(pCreate->lpCreateParams);
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis));
pThis->hWnd = hWnd;
} else {
pThis = reinterpret_cast<T *>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
}
if (pThis) {
return pThis->HandleMessage(uMsg, wParam, lParam);
} else {
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
HWND GetHWnd() const {
return hWnd;
}
protected:
HWND hWnd;
virtual int Create(DWORD dwExStyle = 0,
COLORREF backgroundColor = RGB(0, 0, 0),
PCWSTR lpWindowName = L"Sample Window Name",
DWORD dwStyle = WS_OVERLAPPEDWINDOW,
int x = CW_USEDEFAULT,
int y = CW_USEDEFAULT,
int nWidth = CW_USEDEFAULT,
int nHeight = CW_USEDEFAULT,
HWND hWndParent = nullptr,
HMENU hMenu = nullptr) {
WNDCLASS wndClass = {0};
wndClass.lpfnWndProc = T::WindowProc;
wndClass.hInstance = GetModuleHandle(NULL);
wndClass.lpszClassName = ClassName();
wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
wndClass.hbrBackground = CreateSolidBrush(backgroundColor);
RegisterClass(&wndClass);
hWnd = CreateWindowEx(dwExStyle,
ClassName(),
lpWindowName,
dwStyle,
x,
y,
nWidth,
nHeight,
hWndParent,
hMenu,
GetModuleHandle(NULL),
this);
return (hWnd ? true : false);
}
virtual HWND CreateControl(PCWSTR lpClassName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent,
HMENU hMenu = nullptr,
HINSTANCE hInstance = nullptr,
LPVOID lpParam = nullptr) {
hWnd = CreateWindow(lpClassName,
L"",
dwStyle,
x,
y,
nWidth,
nHeight,
hWndParent,
hMenu,
hInstance,
lpParam);
return hWnd;
}
virtual LRESULT CALLBACK HandleMessage(UINT, WPARAM, LPARAM) = 0;
virtual PCWSTR ClassName() const = 0;
};
} // namespace BaseWindowClass
#endif // !BASEWINDOW_H
<file_sep>#ifndef TRAFFICMANAGERLIST_H
#define TRAFFICMANAGERLIST_H
#include <queue>
#include <set>
#include <string>
#include <vector>
#include "PacketStructs.h"
#include "BaseWindow.h"
namespace TrafficManagerListClass {
struct Margin {
int left;
int top;
int right;
int bottom;
Margin(int width, int height)
: left(width), top(height), right(width), bottom(height) {}
Margin(int left, int top, int right, int bottom)
: left(left), top(top), right(right), bottom(bottom) {}
};
struct ListColumn {
std::wstring name;
int width;
ListColumn(std::wstring name, int width) : name(name), width(width) {}
};
struct ListItem {
mutable std::wstring name;
unsigned int pid;
mutable unsigned int bytesPerMinute;
mutable std::set<PacketStructs::FullAddress> addresses;
mutable std::queue<PacketStructs::PacketInformation> packetQueue;
ListItem(std::wstring name,
unsigned int pid,
unsigned int bytesPerMinute,
std::set<PacketStructs::FullAddress> addresses,
std::queue<PacketStructs::PacketInformation> packetQueue)
: name(name),
pid(pid),
bytesPerMinute(bytesPerMinute),
addresses(addresses),
packetQueue(packetQueue) {}
inline bool operator<(const ListItem &r) const {
return pid < r.pid;
}
};
class TrafficManagerList
: public BaseWindowClass::BaseWindow<TrafficManagerList> {
public:
TrafficManagerList();
HWND CreateControl(PCWSTR lpClassName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent,
HMENU hMenu = nullptr,
HINSTANCE hInstance = nullptr,
LPVOID lpParam = nullptr) override;
HWND CreateControl(HWND hWndParent);
void InsertItems(std::set<TrafficManagerListClass::ListItem> &processes);
void DeleteAllItems();
LRESULT CALLBACK HandleMessage(UINT, WPARAM, LPARAM) override;
PCWSTR ClassName() const override {
return className.c_str();
}
private:
const std::wstring className = L"TrafficManagerListClass";
const Margin parentMargin = Margin(0, 0, 0, 0);
std::vector<ListColumn> columns = {ListColumn(L"Path", 910),
ListColumn(L"PID", 70),
ListColumn(L"Bytes/second", 100)};
};
} // namespace TrafficManagerListClass
#endif // !TRAFFICMANAGERLIST_H
<file_sep>#ifndef TRAFFICMANAGER_H
#define TRAFFICMANAGER_H
#include <thread>
#include "PacketListener.h"
#include "TrafficManagerList.h"
#include "BaseWindow.h"
namespace TrafficManagerClass {
class TrafficManager : public BaseWindowClass::BaseWindow<TrafficManager> {
public:
TrafficManager();
int Create(DWORD dwExStyle = 0,
COLORREF backgroundColor = RGB(0, 0, 0),
PCWSTR lpWindowName = L"Traffic Manager",
DWORD dwStyle = WS_OVERLAPPEDWINDOW,
int x = CW_USEDEFAULT,
int y = CW_USEDEFAULT,
int nWidth = CW_USEDEFAULT,
int nHeight = CW_USEDEFAULT,
HWND hWndParent = nullptr,
HMENU hMenu = nullptr) override;
LRESULT CALLBACK HandleMessage(UINT, WPARAM, LPARAM) override;
PCWSTR ClassName() const override {
return className.c_str();
}
~TrafficManager();
private:
static const int viewUpdateTimerId = 1;
const double viewUpdateRate = 2; // fps
static const int udpTableUpdateTimerId = 2;
const int udpTableUpdateInterval = 5000; // msec
const std::wstring className = L"TrafficManagerClass";
TrafficManagerListClass::TrafficManagerList trafficManagerList;
PacketListenerClass::PacketListener packetListener;
std::thread packetListenerThread;
void HandleTimer(WPARAM wParam, LPARAM lParam);
void HandleNotify(WPARAM wParam, LPARAM lParam);
void UpdateIpTables();
void UpdateView();
};
} // namespace TrafficManagerClass
#endif // !TRAFFICMANAGER_H
<file_sep>#ifndef THREADPOOL
#define THREADPOOL
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
namespace ThreadPoolClass {
class ThreadPool {
public:
ThreadPool(size_t);
template <class F, class... Args>
std::future<typename std::result_of<F(Args...)>::type> EnqueueTask(
F &&f,
Args &&... args) {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(*mutex);
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task]() { (*task)(); });
// std::cout << "task emplaced" << std::endl;
}
condition.notify_one();
return res;
}
~ThreadPool();
private:
std::vector<std::thread> workers;
std::queue<std::function<void()> > tasks;
std::unique_ptr<std::mutex> mutex;
std::condition_variable condition;
bool stop;
};
} // namespace ThreadPoolClass
#endif // THREADPOOL
<file_sep>#ifndef DEBUGGER_H
#define DEBUGGER_H
//#include <windows.h>
#include <sstream>
namespace DebuggerClass {
class Debugger {
public:
// If UNIDODE defined expands to PrintlW, otherwise to PrintlnA
template <typename... Args>
static void Println(Args... args);
template <typename... Args>
static void PrintlnA(Args... args);
template <typename... Args>
static void PrintlnW(Args... args);
private:
template <typename T>
static void PlaceToSS(std::stringstream &ss, T t);
template <typename T, typename... Args>
static void PlaceToSS(std::stringstream &ss, T t, Args... args);
template <typename T>
static void PlaceToWSS(std::wstringstream &wss, T t);
template <typename T, typename... Args>
static void PlaceToWSS(std::wstringstream &wss, T t, Args... args);
};
template <typename... Args>
static void Debugger::Println(Args... args) {
#ifdef UNICODE
PrintlnW(args...);
#else
PrintlnA(args...);
#endif // UNICODE
}
template <typename T>
static void Debugger::PlaceToSS(std::stringstream &ss, T t) {
ss << t;
}
template <typename T, typename... Args>
static void Debugger::PlaceToSS(std::stringstream &ss, T t, Args... args) {
PlaceToSS(ss, t);
PlaceToSS(ss, args...);
}
template <typename... Args>
static void Debugger::PrintlnA(Args... args) {
std::stringstream ss;
PlaceToSS(ss, args...);
ss << "\n";
OutputDebugStringA(ss.str().c_str());
}
template <typename T>
static void Debugger::PlaceToWSS(std::wstringstream &wss, T t) {
wss << t;
}
template <typename T, typename... Args>
static void Debugger::PlaceToWSS(std::wstringstream &wss, T t, Args... args) {
PlaceToWSS(wss, t);
PlaceToWSS(wss, args...);
}
template <typename... Args>
static void Debugger::PrintlnW(Args... args) {
std::wstringstream wss;
PlaceToWSS(wss, args...);
wss << L"\n";
OutputDebugStringW(wss.str().c_str());
}
} // namespace DebuggerClass
#endif // !DEBUGGER_H
<file_sep>#include "PacketListener.h"
#include <iphlpapi.h>
#include <psapi.h>
#include <time.h>
#include <chrono>
#include "Debugger.h"
namespace PacketListenerClass {
PacketListener::PacketListener() : stopListening(false), threadPool(nullptr) {
InitNpcapDllPath();
}
void PacketListener::StartListeningToDevice(pcap_if_t *device) {
pcap_t *adapterHandle;
if ((adapterHandle = pcap_open(device->name,
65536,
0,
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
)) == nullptr) {
DebuggerClass::Debugger::PrintlnA("Unable to open the adapter. ",
device->name,
" is not supported by Npcap");
return;
}
AdapterInfo adapterInfo;
switch (pcap_datalink(adapterHandle)) {
case DLT_NULL:
adapterInfo.frameHeaderLen = 4;
return; // we don't need loopback traffic
case DLT_EN10MB:
adapterInfo.frameHeaderLen = 14;
break;
case DLT_IEEE802_11:
adapterInfo.frameHeaderLen = 30;
break;
case DLT_LOOP:
adapterInfo.frameHeaderLen = 4;
return; // we don't need loopback traffic
default:
adapterInfo.frameHeaderLen = 0;
}
SetPacketFilter(
adapterHandle,
(device->addresses ? ((struct sockaddr_in *)device->addresses->netmask)
->sin_addr.S_un.S_addr
: 0xffffff), // If the interface is without addresses,
// we suppose to be in a C class network
"");
int res;
struct pcap_pkthdr *header;
const u_char *packetData;
while ((res = pcap_next_ex(adapterHandle, &header, &packetData)) >= 0 &&
!stopListening) {
if (res == 0) {
continue;
}
PacketStructs::IPHeader *ipHeader =
(PacketStructs::IPHeader *)(packetData + adapterInfo.frameHeaderLen);
PacketStructs::UDPHeader *udpHeader =
(PacketStructs::UDPHeader *)((u_char *)ipHeader +
(ipHeader->versionAndInternetHeaderlen &
0xf) *
4);
pcap_addr *deviceAddress = device->addresses;
bool incoming = true;
if (deviceAddress->addr->sa_family == AF_INET) {
incoming = ((PacketStructs::IPv4Address)(
(struct sockaddr_in *)deviceAddress->addr)
->sin_addr.s_addr == ipHeader->destAddr);
}
// TODO make for ipv6
HandlePacket(PacketStructs::PacketInformation(
header->len,
PacketStructs::FullAddress(ipHeader->srcAddr, udpHeader->srcPort),
PacketStructs::FullAddress(ipHeader->destAddr, udpHeader->destPort),
incoming,
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())));
}
if (res == -1) {
DebuggerClass::Debugger::PrintlnA("Error reading the packets: ",
pcap_geterr(adapterHandle));
}
}
void PacketListener::SetPacketFilter(pcap_t *adapterHandle,
unsigned int netmask,
std::string expression) {
bpf_program fcode;
if (pcap_compile(adapterHandle, &fcode, expression.c_str(), 1, netmask) < 0) {
DebuggerClass::Debugger::PrintlnA(
"Unable to compile the packet filter. Check the syntax.");
return;
}
if (pcap_setfilter(adapterHandle, &fcode) < 0) {
DebuggerClass::Debugger::PrintlnA("Error setting the filter.");
return;
}
}
void PacketListener::StartListening() {
pcap_if_t *devices = nullptr;
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &devices, errbuf) == -1) {
DebuggerClass::Debugger::PrintlnA(L"Error in pcap_findalldevs_ex: ",
errbuf);
return;
}
if (devices == nullptr) {
DebuggerClass::Debugger::PrintlnA(
L"No interfaces found! Make sure Npcap is installed.");
return;
}
pcap_if_t *curDev = devices;
size_t deviceCount = 0;
for (; curDev != NULL; curDev = curDev->next, deviceCount++)
;
threadPool = new ThreadPoolClass::ThreadPool(deviceCount);
std::vector<std::future<void>> futures;
for (curDev = devices; curDev != NULL; curDev = curDev->next) {
futures.push_back(threadPool->EnqueueTask(
[this](pcap_if_t *curDev) { this->StartListeningToDevice(curDev); },
curDev));
}
for (int i = 0; i < futures.size(); i++) {
futures[i].get();
}
pcap_freealldevs(devices);
}
void PacketListener::StopListening() {
stopListening = true;
if (threadPool) {
delete threadPool;
threadPool = nullptr;
}
}
void PacketListener::HandlePacket(PacketStructs::PacketInformation packet) {
MIB_UDPROW_OWNER_PID *udp4TableLocal =
((MIB_UDPTABLE_OWNER_PID *)udp4Table)->table;
size_t udpTableSize = ((MIB_UDPTABLE_OWNER_PID *)udp4Table)->dwNumEntries;
PacketStructs::FullAddress valueToSearch =
packet.incoming ? packet.dest : packet.src;
// tables are not sorted!!!!!!!!!!!!!!!!!!
/*size_t left = 0;
size_t right = udpTableSize - 1;
while (left < right) {
size_t mid = (left + right) / 2;
if (valueToSearch.ip < udp4TableLocal[mid].dwLocalAddr) {
right = mid;
} else if (valueToSearch.ip == udp4TableLocal->dwLocalAddr) {
if (valueToSearch.port < udp4TableLocal[mid].dwLocalPort) {
right = mid;
} else {
left = mid + 1;
}
} else {
left = mid + 1;
}
}*/
size_t left = -1;
for (int i = 0; i < udpTableSize; i++) {
if (valueToSearch.ip == udp4TableLocal[i].dwLocalAddr &&
valueToSearch.port == udp4TableLocal[i].dwLocalPort) {
left = i;
}
}
const size_t ipv4StrLen = 4 * 4 + 3 + 1;
char ipv4Str[ipv4StrLen];
/*DebuggerClass::Debugger::PrintlnA(
"Packet\n",
" incoming: ",
packet.incoming,
"\n",
" ip: ",
IPv4ToStr(*(int *)(&valueToSearch.ip), ipv4Str, ipv4StrLen),
"\n",
" port: ",
valueToSearch.port,
"\n",
" Found:\n",
" ip: ",
IPv4ToStr(udp4TableLocal[left].dwLocalAddr, ipv4Str, ipv4StrLen),
"\n",
" port: ",
udp4TableLocal[left].dwLocalPort,
"\n");*/
if (left != -1) {
auto targetProcess = processes.find(TrafficManagerListClass::ListItem(
L"",
udp4TableLocal[left].dwOwningPid,
0,
std::set<PacketStructs::FullAddress>(),
std::queue<PacketStructs::PacketInformation>()));
if (targetProcess != processes.end()) {
targetProcess->addresses.insert(
PacketStructs::FullAddress(valueToSearch.ip, valueToSearch.port));
targetProcess->packetQueue.push(packet);
targetProcess->bytesPerMinute += packet.size;
} else {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
udp4TableLocal[left].dwOwningPid);
if (hProcess) {
wchar_t fileName[MAX_PATH];
if (GetModuleFileNameEx(hProcess, NULL, fileName, MAX_PATH)) {
processes.insert(TrafficManagerListClass::ListItem(
fileName,
udp4TableLocal[left].dwOwningPid,
packet.size,
std::set<PacketStructs::FullAddress>({valueToSearch}),
std::queue<PacketStructs::PacketInformation>({packet})));
} else {
DebuggerClass::Debugger::PrintlnW(
L"PacketListener::HandlePacket GetModuleFileNameEx failed. Error code: ",
GetLastError());
}
CloseHandle(hProcess);
}
}
}
MIB_TCPROW_OWNER_PID *tcp4TableLocal =
((MIB_TCPTABLE_OWNER_PID *)tcp4Table)->table;
size_t tcpTableSize = ((MIB_TCPTABLE_OWNER_PID *)tcp4Table)->dwNumEntries;
/*left = 0;
right = tcpTableSize - 1;
while (left < right) {
size_t mid = (left + right) / 2;
if (valueToSearch.ip < tcp4TableLocal[mid].dwLocalAddr) {
right = mid;
} else if (valueToSearch.ip == tcp4TableLocal->dwLocalAddr) {
if (valueToSearch.port < tcp4TableLocal[mid].dwLocalPort) {
right = mid;
} else {
left = mid + 1;
}
} else {
left = mid + 1;
}
}*/
left = -1;
for (int i = 0; i < tcpTableSize; i++) {
if (valueToSearch.ip == tcp4TableLocal[i].dwLocalAddr &&
valueToSearch.port == tcp4TableLocal[i].dwLocalPort) {
left = i;
}
}
/*DebuggerClass::Debugger::PrintlnA(
"Packet\n",
" incoming: ",
packet.incoming,
"\n",
" ip: ",
IPv4ToStr(*(int *)(&valueToSearch.ip), ipv4Str, ipv4StrLen),
"\n",
" port: ",
valueToSearch.port,
"\n",
" Found:\n",
" ip: ",
IPv4ToStr(tcp4TableLocal[left].dwLocalAddr, ipv4Str, ipv4StrLen),
"\n",
" port: ",
tcp4TableLocal[left].dwLocalPort,
"\n");*/
if (left != -1) {
auto targetProcess = processes.find(TrafficManagerListClass::ListItem(
L"",
tcp4TableLocal[left].dwOwningPid,
0,
std::set<PacketStructs::FullAddress>(),
std::queue<PacketStructs::PacketInformation>()));
if (targetProcess != processes.end()) {
targetProcess->addresses.insert(
PacketStructs::FullAddress(valueToSearch.ip, valueToSearch.port));
targetProcess->packetQueue.push(packet);
targetProcess->bytesPerMinute += packet.size;
} else {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
tcp4TableLocal[left].dwOwningPid);
if (hProcess) {
wchar_t fileName[MAX_PATH];
if (GetModuleFileNameEx(hProcess, NULL, fileName, MAX_PATH)) {
processes.insert(TrafficManagerListClass::ListItem(
fileName,
tcp4TableLocal[left].dwOwningPid,
packet.size,
std::set<PacketStructs::FullAddress>({valueToSearch}),
std::queue<PacketStructs::PacketInformation>({packet})));
} else {
DebuggerClass::Debugger::PrintlnW(
L"PacketListener::HandlePacket GetModuleFileNameEx failed. Error code: ",
GetLastError());
}
CloseHandle(hProcess);
}
}
}
}
void PacketListener::InitNpcapDllPath() {
BOOL(WINAPI * SetDllDirectory)(LPCTSTR);
wchar_t sysdir_name[512];
int len;
SetDllDirectory = (BOOL(WINAPI *)(LPCTSTR))GetProcAddress(
GetModuleHandle(L"kernel32.dll"), "SetDllDirectoryA");
if (SetDllDirectory == NULL) {
DebuggerClass::Debugger::PrintlnA(L"Error in SetDllDirectory");
} else {
len = GetSystemDirectory(sysdir_name, 480); // be safe
if (!len) {
DebuggerClass::Debugger::PrintlnA(L"Error in GetSystemDirectory: ",
GetLastError());
}
wcscat_s(sysdir_name, L"\\Npcap");
if (SetDllDirectory(sysdir_name) == 0) {
DebuggerClass::Debugger::PrintlnA(
L"Error in SetDllDirectory(\"System32\\Npcap\")");
}
}
}
char *PacketListener::IPv4ToStr(unsigned int ip, char *str, size_t strLen) {
u_char *p = (u_char *)&ip;
sprintf_s(str, strLen, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
return str;
}
char *PacketListener::IPv6ToStr(struct sockaddr *sockaddr,
char *address,
int addrlen) {
socklen_t sockaddrlen;
#ifdef WIN32
sockaddrlen = sizeof(struct sockaddr_in6);
#else
sockaddrlen = sizeof(struct sockaddr_storage);
#endif
/*int res;
if (res = getnameinfo(sockaddr,
sockaddrlen,
address,
addrlen,
NULL,
0,
NI_NUMERICHOST) != 0) {
address = nullptr;
cout << gai_strerror(res) << endl;
cout << WSAGetLastError() << endl;
}*/
return address;
}
PacketListener::~PacketListener() {
StopListening();
}
} // namespace PacketListenerClass<file_sep>#include "TrafficManager.h"
#include <CommCtrl.h>
#include <iphlpapi.h>
#include <chrono>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include "Debugger.h"
namespace TrafficManagerClass {
template <class T>
void SafeDelete(T *pT) {
if (pT) {
delete[] pT;
pT = nullptr;
}
}
TrafficManager::TrafficManager() {}
int TrafficManager::Create(DWORD dwExStyle,
COLORREF backgroundColor,
PCWSTR lpWindowName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent,
HMENU hMenu) {
if (!BaseWindowClass::BaseWindow<TrafficManager>::Create(dwExStyle,
backgroundColor,
lpWindowName,
dwStyle,
x,
y,
nWidth,
nHeight,
hWndParent,
hMenu)) {
return 1;
}
// for controls initialization.
INITCOMMONCONTROLSEX icex;
icex.dwICC = ICC_LISTVIEW_CLASSES;
InitCommonControlsEx(&icex);
SetTimer(hWnd, viewUpdateTimerId, 1000 / viewUpdateRate, (TIMERPROC) nullptr);
SetTimer(
hWnd, udpTableUpdateTimerId, udpTableUpdateInterval, (TIMERPROC) nullptr);
trafficManagerList.CreateControl(hWnd);
if (!trafficManagerList.GetHWnd()) {
DebuggerClass::Debugger::PrintlnW(L"List create failed");
return 1;
}
UpdateIpTables();
packetListenerThread = std::thread(
&PacketListenerClass::PacketListener::StartListening, &packetListener);
return 0;
}
void TrafficManager::HandleTimer(WPARAM wParam, LPARAM lParam) {
switch (wParam) {
case TrafficManager::udpTableUpdateTimerId:
UpdateIpTables();
break;
case TrafficManager::viewUpdateTimerId:
UpdateView();
break;
}
}
void TrafficManager::HandleNotify(WPARAM wParam, LPARAM lParam) {
NMLVDISPINFO *plvdi;
switch (((LPNMHDR)lParam)->code) {
case LVN_GETDISPINFO:
plvdi = (NMLVDISPINFO *)lParam;
auto process = packetListener.processes.begin();
for (int i = 0; i < plvdi->item.iItem; i++, process++)
;
switch (plvdi->item.iSubItem) {
case 0:
plvdi->item.pszText = &process->name[0];
break;
case 1:
plvdi->item.pszText = &std::to_wstring(process->pid)[0];
break;
case 2:
plvdi->item.pszText = &std::to_wstring(process->bytesPerMinute)[0];
break;
default:
break;
}
break;
}
}
void TrafficManager::UpdateIpTables() {
DWORD udp4TableSize;
if (GetExtendedUdpTable(packetListener.udp4Table,
&udp4TableSize,
true,
AF_INET,
UDP_TABLE_OWNER_PID,
0) == ERROR_INSUFFICIENT_BUFFER) {
SafeDelete(packetListener.udp4Table);
packetListener.udp4Table = new void *[udp4TableSize];
GetExtendedUdpTable(packetListener.udp4Table,
&udp4TableSize,
true,
AF_INET,
UDP_TABLE_OWNER_PID,
0);
}
DWORD tcp4TableSize;
if (GetExtendedTcpTable(packetListener.tcp4Table,
&tcp4TableSize,
true,
AF_INET,
TCP_TABLE_OWNER_PID_ALL,
0) == ERROR_INSUFFICIENT_BUFFER) {
packetListener.tcp4Table = new void *[tcp4TableSize];
GetExtendedTcpTable(packetListener.tcp4Table,
&tcp4TableSize,
true,
AF_INET,
TCP_TABLE_OWNER_PID_ALL,
0);
}
}
void TrafficManager::UpdateView() {
trafficManagerList.DeleteAllItems();
std::chrono::milliseconds now =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
for (auto process = packetListener.processes.begin(); process != packetListener.processes.end(); process++) {
while (!process->packetQueue.empty() &&
now - process->packetQueue.front().msSinceEpoch >=
std::chrono::milliseconds(60000)) {
process->bytesPerMinute -= process->packetQueue.front().size;
process->packetQueue.pop();
}
}
trafficManagerList.InsertItems(packetListener.processes);
}
LRESULT CALLBACK TrafficManager::HandleMessage(UINT uMsg,
WPARAM wParam,
LPARAM lParam) {
switch (uMsg) {
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_TIMER:
HandleTimer(wParam, lParam);
break;
// case WM_NOTIFY:
// HandleNotify(wParam, lParam);
// break;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
TrafficManager::~TrafficManager() {
packetListener.StopListening();
packetListenerThread.join();
}
} // namespace TrafficManagerClass
<file_sep>#include "ThreadPool.h"
namespace ThreadPoolClass {
ThreadPool::ThreadPool(size_t threads) : stop(false), mutex(new std::mutex) {
for (size_t i = 0; i < threads; ++i) {
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(*(this->mutex));
this->condition.wait(
lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop) {
return;
}
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
// std::cout << "task runned" << std::endl;
}
});
}
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(*(this->mutex));
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers) {
worker.join();
}
}
} // namespace ThreadPoolClass | ecca13256b9a3a66cacbf11f5e4b0dc4c80c8be1 | [
"C++"
] | 12 | C++ | KainWhite/TrafficManager | a8d92dfa17e9c1e7c7bcd1407498d0a9b5caa1b0 | 853b565b6c50d0e0c323509ef28e22bfb3bab80d |
refs/heads/master | <repo_name>cianeastwood/weakalign<file_sep>/options/options.py
import argparse
from util.torch_util import str_to_bool
class ArgumentParser():
def __init__(self,mode='train'):
self.parser = argparse.ArgumentParser(description='CNNGeometric PyTorch implementation')
self.add_base_parameters()
self.add_cnn_model_parameters()
if mode=='train_strong':
self.add_train_parameters()
self.add_synth_dataset_parameters()
if mode=='train_weak':
self.add_train_parameters()
self.add_weak_dataset_parameters()
self.add_weak_loss_parameters()
elif mode=='eval':
self.add_eval_parameters()
def add_base_parameters(self):
base_params = self.parser.add_argument_group('base')
# Image size
base_params.add_argument('--image-size', type=int, default=240, help='image input size')
# Pre-trained model file
base_params.add_argument('--model', type=str, default='', help='Pre-trained model filename')
base_params.add_argument('--model-aff', type=str, default='', help='Trained affine model filename')
base_params.add_argument('--model-tps', type=str, default='', help='Trained TPS model filename')
def add_synth_dataset_parameters(self):
dataset_params = self.parser.add_argument_group('dataset')
# Dataset parameters
dataset_params.add_argument('--dataset-csv-path', type=str, default='', help='path to training transformation csv folder')
dataset_params.add_argument('--dataset-image-path', type=str, default='', help='path to folder containing training images')
# Random synth dataset parameters
dataset_params.add_argument('--random-sample', type=str_to_bool, nargs='?', const=True, default=False, help='sample random transformations')
dataset_params.add_argument('--random-t', type=float, default=0.5, help='random transformation translation')
dataset_params.add_argument('--random-s', type=float, default=0.5, help='random transformation translation')
dataset_params.add_argument('--random-alpha', type=float, default=1/6, help='random transformation translation')
dataset_params.add_argument('--random-t-tps', type=float, default=0.4, help='random transformation translation')
def add_weak_dataset_parameters(self):
dataset_params = self.parser.add_argument_group('dataset')
# Image pair dataset parameters for train/val
dataset_params.add_argument('--dataset-csv-path', type=str, default='training_data/pf-pascal-flip/', help='path to training transformation csv folder')
dataset_params.add_argument('--dataset-image-path', type=str, default='datasets/proposal-flow-pascal/', help='path to folder containing training images')
dataset_params.add_argument('--categories', nargs='+', type=int, default=0, help='indices of categories for training/eval')
# Eval dataset parameters for early stopping
dataset_params.add_argument('--eval-dataset', type=str, default='pf-pascal', help='Validation dataset used for early stopping')
dataset_params.add_argument('--eval-dataset-path', type=str, default='', help='path to validation dataset used for early stopping')
dataset_params.add_argument('--pck-alpha', type=float, default=0.1, help='pck margin factor alpha')
dataset_params.add_argument('--eval-metric', type=str, default='pck', help='pck/distance')
# Random synth dataset parameters
dataset_params.add_argument('--random-crop', type=str_to_bool, nargs='?', const=True, default=True, help='use random crop augmentation')
def add_train_parameters(self):
train_params = self.parser.add_argument_group('train')
# Optimization parameters
train_params.add_argument('--lr', type=float, default=0.001, help='learning rate')
train_params.add_argument('--momentum', type=float, default=0.9, help='momentum constant')
train_params.add_argument('--num-epochs', type=int, default=10, help='number of training epochs')
train_params.add_argument('--batch-size', type=int, default=16, help='training batch size')
train_params.add_argument('--weight-decay', type=float, default=0, help='weight decay constant')
train_params.add_argument('--seed', type=int, default=1, help='Pseudo-RNG seed')
train_params.add_argument('--use-mse-loss', type=str_to_bool, nargs='?', const=True, default=False, help='Use MSE loss on tnf. parameters')
train_params.add_argument('--geometric-model', type=str, default='affine', help='geometric model to be regressed at output: affine or tps')
# Trained model parameters
train_params.add_argument('--result-model-fn', type=str, default='checkpoint_adam', help='trained model filename')
train_params.add_argument('--result-model-dir', type=str, default='trained_models', help='path to trained models folder')
# Dataset name (used for loading defaults)
train_params.add_argument('--training-dataset', type=str, default='pascal', help='dataset to use for training')
# Limit train/test dataset sizes
train_params.add_argument('--train-dataset-size', type=int, default=0, help='train dataset size limit')
train_params.add_argument('--test-dataset-size', type=int, default=0, help='test dataset size limit')
# Parts of model to train
train_params.add_argument('--train-fe', type=str_to_bool, nargs='?', const=True, default=True, help='Train feature extraction')
train_params.add_argument('--train-fr', type=str_to_bool, nargs='?', const=True, default=True, help='Train feature regressor')
train_params.add_argument('--train-bn', type=str_to_bool, nargs='?', const=True, default=True, help='train batch-norm layers')
train_params.add_argument('--fe-finetune-params', nargs='+', type=str, default=[''], help='String indicating the F.Ext params to finetune')
train_params.add_argument('--update-bn-buffers', type=str_to_bool, nargs='?', const=True, default=False, help='Update batch norm running mean and std')
def add_weak_loss_parameters(self):
loss_params = self.parser.add_argument_group('weak_loss')
# Parameters of weak loss
loss_params.add_argument('--tps-grid-size', type=int, default=3, help='tps grid size')
loss_params.add_argument('--tps-reg-factor', type=float, default=0.2, help='tps regularization factor')
loss_params.add_argument('--normalize-inlier-count', type=str_to_bool, nargs='?', const=True, default=True)
loss_params.add_argument('--dilation-filter', type=int, default=0, help='type of dilation filter: 0:no filter;1:4-neighs;2:8-neighs')
loss_params.add_argument('--use-conv-filter', type=str_to_bool, nargs='?', const=True, default=False, help='use conv filter instead of dilation')
def add_eval_parameters(self):
eval_params = self.parser.add_argument_group('eval')
# Evaluation parameters
eval_params.add_argument('--eval-dataset', type=str, default='pf', help='pf/caltech/tss')
eval_params.add_argument('--eval-dataset-path', type=str, default='', help='Path to PF dataset')
eval_params.add_argument('--flow-output-dir', type=str, default='results/', help='flow output dir')
eval_params.add_argument('--pck-alpha', type=float, default=0.1, help='pck margin factor alpha')
eval_params.add_argument('--eval-metric', type=str, default='pck', help='pck/distance')
eval_params.add_argument('--tps-reg-factor', type=float, default=0.0, help='regularisation factor for tps tnf')
def add_cnn_model_parameters(self):
model_params = self.parser.add_argument_group('model')
# Model parameters
model_params.add_argument('--feature-extraction-cnn', type=str, default='vgg', help='feature extraction CNN model architecture: vgg/resnet101')
model_params.add_argument('--feature-extraction-last-layer', type=str, default='', help='feature extraction CNN last layer')
model_params.add_argument('--fr-feature-size', type=int, default=15, help='image input size')
model_params.add_argument('--fr-kernel-sizes', nargs='+', type=int, default=[7,5], help='kernels sizes in feat.reg. conv layers')
model_params.add_argument('--fr-channels', nargs='+', type=int, default=[128,64], help='channels in feat. reg. conv layers')
def parse(self,arg_str=None):
if arg_str is None:
args = self.parser.parse_args()
else:
args = self.parser.parse_args(arg_str.split())
arg_groups = {}
for group in self.parser._action_groups:
group_dict={a.dest:getattr(args,a.dest,None) for a in group._group_actions}
arg_groups[group.title]=group_dict
return (args,arg_groups)
<file_sep>/image/normalization.py
import torch
from torchvision import transforms
from torch.autograd import Variable
class NormalizeImageDict(object):
"""
Normalizes Tensor images in dictionary
Args:
image_keys (list): dict. keys of the images to be normalized
normalizeRange (bool): if True the image is divided by 255.0s
"""
def __init__(self,image_keys,normalizeRange=True):
self.image_keys = image_keys
self.normalizeRange=normalizeRange
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
def __call__(self, sample):
for key in self.image_keys:
if self.normalizeRange:
sample[key] /= 255.0
sample[key] = self.normalize(sample[key])
return sample
def normalize_image(image, forward=True, mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]):
im_size = image.size()
mean=torch.FloatTensor(mean).unsqueeze(1).unsqueeze(2)
std=torch.FloatTensor(std).unsqueeze(1).unsqueeze(2)
if image.is_cuda:
mean = mean.cuda()
std = std.cuda()
if isinstance(image,torch.autograd.Variable):
mean = Variable(mean,requires_grad=False)
std = Variable(std,requires_grad=False)
if forward:
if len(im_size)==3:
result = image.sub(mean.expand(im_size)).div(std.expand(im_size))
elif len(im_size)==4:
result = image.sub(mean.unsqueeze(0).expand(im_size)).div(std.unsqueeze(0).expand(im_size))
else:
if len(im_size)==3:
result = image.mul(std.expand(im_size)).add(mean.expand(im_size))
elif len(im_size)==4:
result = image.mul(std.unsqueeze(0).expand(im_size)).add(mean.unsqueeze(0).expand(im_size))
return result<file_sep>/model/loss.py
from __future__ import print_function, division
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from geotnf.point_tnf import PointTnf
from scipy.ndimage.morphology import binary_dilation,generate_binary_structure
from util.torch_util import expand_dim
from geotnf.transformation import GeometricTnf,ComposedGeometricTnf
import torch.nn.functional as F
import scipy.signal
class TransformedGridLoss(nn.Module):
def __init__(self, geometric_model='affine', use_cuda=True, grid_size=20):
super(TransformedGridLoss, self).__init__()
self.geometric_model = geometric_model
# define virtual grid of points to be transformed
axis_coords = np.linspace(-1,1,grid_size)
self.N = grid_size*grid_size
X,Y = np.meshgrid(axis_coords,axis_coords)
X = np.reshape(X,(1,1,self.N))
Y = np.reshape(Y,(1,1,self.N))
P = np.concatenate((X,Y),1)
self.P = Variable(torch.FloatTensor(P),requires_grad=False)
self.pointTnf = PointTnf(use_cuda=use_cuda)
if use_cuda:
self.P = self.P.cuda();
def forward(self, theta, theta_GT):
# expand grid according to batch size
batch_size = theta.size()[0]
P = self.P.expand(batch_size,2,self.N)
# compute transformed grid points using estimated and GT tnfs
if self.geometric_model=='affine':
P_prime = self.pointTnf.affPointTnf(theta,P)
P_prime_GT = self.pointTnf.affPointTnf(theta_GT,P)
elif self.geometric_model=='tps':
P_prime = self.pointTnf.tpsPointTnf(theta.unsqueeze(2).unsqueeze(3),P)
P_prime_GT = self.pointTnf.tpsPointTnf(theta_GT,P)
# compute MSE loss on transformed grid points
loss = torch.sum(torch.pow(P_prime - P_prime_GT,2),1)
loss = torch.mean(loss)
return loss
class WeakInlierCount(nn.Module):
def __init__(self, geometric_model='affine', tps_grid_size=3, tps_reg_factor=0, h_matches=15, w_matches=15, use_conv_filter=False, dilation_filter=None, use_cuda=True, normalize_inlier_count=False, offset_factor=227/210):
super(WeakInlierCount, self).__init__()
self.normalize=normalize_inlier_count
self.geometric_model = geometric_model
self.geometricTnf = GeometricTnf(geometric_model=geometric_model,
tps_grid_size=tps_grid_size,
tps_reg_factor=tps_reg_factor,
out_h=h_matches, out_w=w_matches,
offset_factor = offset_factor,
use_cuda=use_cuda)
# define dilation filter
if dilation_filter is None:
dilation_filter = generate_binary_structure(2, 2)
# define identity mask tensor (w,h are switched and will be permuted back later)
mask_id = np.zeros((w_matches,h_matches,w_matches*h_matches))
idx_list = list(range(0, mask_id.size, mask_id.shape[2]+1))
mask_id.reshape((-1))[idx_list]=1
mask_id = mask_id.swapaxes(0,1)
# perform 2D dilation to each channel
if not use_conv_filter:
if not (isinstance(dilation_filter,int) and dilation_filter==0):
for i in range(mask_id.shape[2]):
mask_id[:,:,i] = binary_dilation(mask_id[:,:,i],structure=dilation_filter).astype(mask_id.dtype)
else:
for i in range(mask_id.shape[2]):
flt=np.array([[1/16,1/8,1/16],
[1/8, 1/4, 1/8],
[1/16,1/8,1/16]])
mask_id[:,:,i] = scipy.signal.convolve2d(mask_id[:,:,i], flt, mode='same', boundary='fill', fillvalue=0)
# convert to PyTorch variable
mask_id = Variable(torch.FloatTensor(mask_id).transpose(1,2).transpose(0,1).unsqueeze(0),requires_grad=False)
self.mask_id = mask_id
if use_cuda:
self.mask_id = self.mask_id.cuda();
def forward(self, theta, matches, return_outliers=False):
if isinstance(theta,Variable): # handle normal batch transformations
batch_size=theta.size()[0]
theta=theta.clone()
mask = self.geometricTnf(expand_dim(self.mask_id,0,batch_size),theta)
if return_outliers:
mask_outliers = self.geometricTnf(expand_dim(1.0-self.mask_id,0,batch_size),theta)
if self.normalize:
epsilon=1e-5
mask = torch.div(mask,
torch.sum(torch.sum(torch.sum(mask+epsilon,3),2),1).unsqueeze(1).unsqueeze(2).unsqueeze(3).expand_as(mask))
if return_outliers:
mask_outliers = torch.div(mask_outliers,
torch.sum(torch.sum(torch.sum(mask_outliers+epsilon,3),2),1).unsqueeze(1).unsqueeze(2).unsqueeze(3).expand_as(mask_outliers))
score = torch.sum(torch.sum(torch.sum(torch.mul(mask,matches),3),2),1)
if return_outliers:
score_outliers = torch.sum(torch.sum(torch.sum(torch.mul(mask_outliers,matches),3),2),1)
return (score,score_outliers)
elif isinstance(theta,list): # handle multiple transformations per batch item, batch is in list format (used for RANSAC)
batch_size = len(theta)
score = []
for b in range(batch_size):
sample_size=theta[b].size(0)
s=self.forward(theta[b],expand_dim(matches[b,:,:,:].unsqueeze(0),0,sample_size))
score.append(s)
return score
class TwoStageWeakInlierCount(WeakInlierCount):
def __init__(self,
tps_grid_size=3,
tps_reg_factor=0,
h_matches=15,
w_matches=15,
use_conv_filter=False,
dilation_filter=None,
use_cuda=True,
normalize_inlier_count=False,
offset_factor=227/210):
super(TwoStageWeakInlierCount, self).__init__(h_matches=h_matches,
w_matches=w_matches,
use_conv_filter=use_conv_filter,
dilation_filter=dilation_filter,
use_cuda=use_cuda,
normalize_inlier_count=normalize_inlier_count,
offset_factor=offset_factor)
self.compGeometricTnf = ComposedGeometricTnf(tps_grid_size=tps_grid_size,
tps_reg_factor=tps_reg_factor,
out_h=h_matches,
out_w=w_matches,
offset_factor=offset_factor,
use_cuda=use_cuda)
def forward(self, theta_aff, theta_aff_tps, matches,return_outliers=False):
batch_size=theta_aff.size()[0]
mask = self.compGeometricTnf(image_batch=expand_dim(self.mask_id,0,batch_size),
theta_aff=theta_aff,
theta_aff_tps=theta_aff_tps)
if return_outliers:
mask_outliers = self.compGeometricTnf(image_batch=expand_dim(1.0-self.mask_id,0,batch_size),
theta_aff=theta_aff,
theta_aff_tps=theta_aff_tps)
if self.normalize:
epsilon=1e-5
mask = torch.div(mask,
torch.sum(torch.sum(torch.sum(mask+epsilon,3),2),1).unsqueeze(1).unsqueeze(2).unsqueeze(3).expand_as(mask))
if return_outliers:
mask_outliers = torch.div(mask,
torch.sum(torch.sum(torch.sum(mask_outliers+epsilon,3),2),1).unsqueeze(1).unsqueeze(2).unsqueeze(3).expand_as(mask_outliers))
score = torch.sum(torch.sum(torch.sum(torch.mul(mask,matches),3),2),1)
if return_outliers:
score_outliers = torch.sum(torch.sum(torch.sum(torch.mul(mask_outliers,matches),3),2),1)
return (score,score_outliers)
return score<file_sep>/eval.py
from __future__ import print_function, division
import os
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from model.cnn_geometric_model import CNNGeometric,TwoStageCNNGeometric
from data.pf_dataset import PFDataset, PFPascalDataset
from data.pascal_parts_dataset import PascalPartsDataset
from data.caltech_dataset import CaltechDataset
from data.tss_dataset import TSSDataset
from data.download_datasets import *
from image.normalization import NormalizeImageDict
from util.torch_util import BatchTensorToVars, str_to_bool
from geotnf.point_tnf import *
from geotnf.transformation import GeometricTnf
from os.path import exists
from util.eval_util import pck_metric, area_metrics, flow_metrics, compute_metric
from collections import OrderedDict
from options.options import ArgumentParser
from util.dataloader import default_collate
from util.torch_util import collate_custom
"""
Script to evaluate a trained model as presented in the CNNGeometric CVPR'17 paper
on the ProposalFlow/Caltech-101 dataset
"""
print('WeakAlign evaluation script')
# Argument parsing
args,arg_groups = ArgumentParser(mode='eval').parse()
print(args)
# check provided models and deduce if single/two-stage model should be used
do_aff = args.model_aff!=""
do_tps = args.model_tps!=""
two_stage = args.model!='' or (do_aff and do_tps)
if args.eval_dataset_path=='' and args.eval_dataset=='pf':
args.eval_dataset_path='datasets/proposal-flow-willow/'
if args.eval_dataset_path=='' and args.eval_dataset=='pf-pascal':
args.eval_dataset_path='datasets/proposal-flow-pascal/'
if args.eval_dataset_path=='' and args.eval_dataset=='caltech':
args.eval_dataset_path='datasets/caltech-101/'
if args.eval_dataset_path=='' and args.eval_dataset=='tss':
args.eval_dataset_path='datasets/tss/'
if args.eval_dataset_path=='' and args.eval_dataset=='pascal-parts':
args.eval_dataset_path='datasets/pascal-parts/'
use_cuda = torch.cuda.is_available()
# Download dataset if needed
if args.eval_dataset=='pf' and not exists(args.eval_dataset_path):
download_PF_willow(args.eval_dataset_path)
elif args.eval_dataset=='pf-pascal' and not exists(args.eval_dataset_path):
download_PF_pascal(args.eval_dataset_path)
elif args.eval_dataset=='caltech' and not exists(args.eval_dataset_path):
download_caltech(args.eval_dataset_path)
elif args.eval_dataset=='tss' and not exists(args.eval_dataset_path):
download_TSS(args.eval_dataset_path)
elif args.eval_dataset=='pascal-parts' and not exists(args.eval_dataset_path):
download_pascal_parts(args.eval_dataset_path)
# Create model
print('Creating CNN model...')
# check type of given model and create model
if two_stage:
model = TwoStageCNNGeometric(use_cuda=use_cuda,
**arg_groups['model'])
if not two_stage and do_aff:
model = CNNGeometric(use_cuda=use_cuda,
output_dim=6,
**arg_groups['model'])
if not two_stage and do_tps:
model_tps = CNNGeometric(use_cuda=use_cuda,
output_dim=18,
**arg_groups['model'])
# load pretrained weights
if two_stage and args.model!='':
checkpoint = torch.load(args.model, map_location=lambda storage, loc: storage)
checkpoint['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint['state_dict'].items()])
for name, param in model.FeatureExtraction.state_dict().items():
model.FeatureExtraction.state_dict()[name].copy_(checkpoint['state_dict']['FeatureExtraction.' + name])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression.' + name])
for name, param in model.FeatureRegression2.state_dict().items():
model.FeatureRegression2.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression2.' + name])
if two_stage and args.model=='':
checkpoint_aff = torch.load(args.model_aff, map_location=lambda storage, loc: storage)
checkpoint_aff['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint_aff['state_dict'].items()])
checkpoint_tps = torch.load(args.model_tps, map_location=lambda storage, loc: storage)
checkpoint_tps['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint_tps['state_dict'].items()])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint_aff['state_dict']['FeatureRegression.' + name])
for name, param in model.FeatureRegression2.state_dict().items():
model.FeatureRegression2.state_dict()[name].copy_(checkpoint_tps['state_dict']['FeatureRegression.' + name])
if not two_stage:
model_fn = args.model_aff if do_aff else args.model_tps
checkpoint = torch.load(model_fn, map_location=lambda storage, loc: storage)
checkpoint['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint['state_dict'].items()])
for name, param in model.FeatureExtraction.state_dict().items():
model.FeatureExtraction.state_dict()[name].copy_(checkpoint['state_dict']['FeatureExtraction.' + name])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression.' + name])
# Dataset and dataloader
if args.eval_dataset=='pf':
Dataset = PFDataset
collate_fn = default_collate
csv_file = 'test_pairs_pf.csv'
if args.eval_dataset=='pf-pascal':
Dataset = PFPascalDataset
collate_fn = default_collate
csv_file = 'test_pairs_pf_pascal.csv'
elif args.eval_dataset=='caltech':
Dataset = CaltechDataset
collate_fn = default_collate
csv_file = 'test_pairs_caltech_with_category.csv'
elif args.eval_dataset=='tss':
Dataset = TSSDataset
collate_fn = default_collate
csv_file = 'test_pairs_tss.csv'
elif args.eval_dataset=='pascal-parts':
Dataset = PascalPartsDataset
collate_fn = collate_custom
csv_file = 'test_pairs_pascal_parts.csv'
cnn_image_size=(args.image_size,args.image_size)
dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file),
dataset_path=args.eval_dataset_path,
transform=NormalizeImageDict(['source_image','target_image']),
output_size=cnn_image_size)
if use_cuda:
batch_size=8
else:
batch_size=1
dataloader = DataLoader(dataset, batch_size=batch_size,
shuffle=False, num_workers=4,
collate_fn=collate_fn)
batch_tnf = BatchTensorToVars(use_cuda=use_cuda)
if args.eval_dataset=='pf' or args.eval_dataset=='pf-pascal':
metric = 'pck'
elif args.eval_dataset=='caltech':
metric = 'area'
elif args.eval_dataset=='pascal-parts':
metric = 'pascal_parts'
elif args.eval_dataset=='tss':
metric = 'flow'
model.eval()
stats=compute_metric(metric,model,dataset,dataloader,batch_tnf,batch_size,two_stage,do_aff,do_tps,args)
<file_sep>/data/download_datasets.py
from os.path import exists, join, basename, dirname, splitext
from os import makedirs, remove, rename
from six.moves import urllib
import tarfile
import zipfile
import requests
import sys
import click
def download_and_uncompress(url, dest=None, chunk_size=1024, replace="ask",
label="Downloading {dest_basename} ({size:.2f}MB)"):
dest = dest or "./"+url.split("/")[-1]
dest_dir = dirname(dest)
if not exists(dest_dir):
makedirs(dest_dir)
if exists(dest):
if (replace is False
or replace == "ask"
and not click.confirm("Replace {}?".format(dest))):
return
# download file
with open(dest, "wb") as f:
response = requests.get(url, stream=True, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36'})
total_length = response.headers.get('content-length')
if total_length is None: # no content length header
f.write(response.content)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(50 * dl / total_length)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) )
sys.stdout.write("{:.1%}".format(dl / total_length))
sys.stdout.flush()
sys.stdout.write("\n")
# uncompress
if dest.endswith("zip"):
file = zipfile.ZipFile(dest, 'r')
elif dest.endswith("tar"):
file = tarfile.open(dest, 'r')
elif dest.endswith("tar.gz"):
file = tarfile.open(dest, 'r:gz')
else:
return dest
print("Extracting data...")
file.extractall(dest_dir)
file.close()
return dest
def download_PF_willow(dest="datasets/proposal-flow-willow"):
print("Fetching PF Willow dataset ")
url = "http://www.di.ens.fr/willow/research/proposalflow/dataset/PF-dataset.zip"
file_path = join(dest, basename(url))
download_and_uncompress(url,file_path)
print('Downloading image pair list \n') ;
url = "http://www.di.ens.fr/willow/research/cnngeometric/other_resources/test_pairs_pf.csv"
file_path = join(dest,basename(url))
download_and_uncompress(url,file_path)
def download_PF_pascal(dest="datasets/proposal-flow-pascal"):
print("Fetching PF Pascal dataset ")
url = "http://www.di.ens.fr/willow/research/proposalflow/dataset/PF-dataset-PASCAL.zip"
file_path = join(dest, basename(url))
download_and_uncompress(url,file_path)
print('Downloading image pair list \n') ;
url = "http://www.di.ens.fr/willow/research/cnngeometric/other_resources/test_pairs_pf_pascal.csv"
file_path = join(dest,basename(url))
download_and_uncompress(url,file_path)
url = "http://www.di.ens.fr/willow/research/cnngeometric/other_resources/val_pairs_pf_pascal.csv"
file_path = join(dest,basename(url))
download_and_uncompress(url,file_path)
def download_pascal(dest="datasets/pascal-voc11"):
print("Fetching Pascal VOC2011 dataset")
url = "http://host.robots.ox.ac.uk/pascal/VOC/voc2011/VOCtrainval_25-May-2011.tar"
file_path = join(dest, basename(url))
download_and_uncompress(url, file_path)
def download_pascal_parts(dest="datasets/pascal-parts"):
print("Fetching Pascal Parts dataset")
url = "http://www.di.ens.fr/willow/research/cnngeometric/other_resources/pascal_data.tar"
file_path = join(dest, basename(url))
download_and_uncompress(url, file_path)
def download_caltech(dest="datasets/caltech-101"):
print("Fetching Caltech-101 dataset")
url = "http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz"
file_path = join(dest, basename(url))
download_and_uncompress(url,file_path)
print("Fetching Caltech-101 annotations")
url="http://www.vision.caltech.edu/Image_Datasets/Caltech101/Annotations.tar"
file_path = join(dest, basename(url))
download_and_uncompress(url,file_path)
print('Renaming some annotation directories\n') ;
rename(join(dest,'Annotations','Airplanes_Side_2'),join(dest,'Annotations','airplanes'))
rename(join(dest,'Annotations','Faces_2'),join(dest,'Annotations','Faces'))
rename(join(dest,'Annotations','Faces_3'),join(dest,'Annotations','Faces_easy'))
rename(join(dest,'Annotations','Motorbikes_16'),join(dest,'Annotations','Motorbikes'))
print('Done renaming\n') ;
print('Downloading image pair list \n') ;
url='http://www.di.ens.fr/willow/research/weakalign/other_resources/test_pairs_caltech_with_category.csv'
file_path = join(dest, basename(url))
download_and_uncompress(url,file_path)
def download_TSS(dest="datasets/tss"):
print("Fetching TSS dataset ")
url = "http://www.hci.iis.u-tokyo.ac.jp/datasets/data/JointCorrCoseg/TSS_CVPR2016.zip"
file_path = join(dest, basename(url))
download_and_uncompress(url,file_path)
print('Downloading image pair list \n') ;
url = "http://www.di.ens.fr/willow/research/cnngeometric/other_resources/test_pairs_tss.csv"
file_path = join(dest,basename(url))
download_and_uncompress(url,file_path)
<file_sep>/demo.py
from __future__ import print_function, division
import os
import argparse
import torch
import torch.nn as nn
from os.path import exists
from torch.utils.data import Dataset, DataLoader
from model.cnn_geometric_model import CNNGeometric, TwoStageCNNGeometric
from data.pf_dataset import PFDataset, PFPascalDataset
from data.download_datasets import download_PF_willow
from image.normalization import NormalizeImageDict, normalize_image
from util.torch_util import BatchTensorToVars, str_to_bool
from geotnf.transformation import GeometricTnf
from geotnf.point_tnf import *
import matplotlib.pyplot as plt
from skimage import io
from collections import OrderedDict
import torch.nn.functional as F
# for compatibility with Python 2
try:
input = raw_input
except NameError:
pass
"""
Script to demonstrate evaluation on a trained model
"""
print('WeakAlign demo script')
# Argument parsing
parser = argparse.ArgumentParser(description='WeakAlign PyTorch implementation')
# Paths
parser.add_argument('--model', type=str, default='trained_models/weakalign_resnet101_affine_tps.pth.tar', help='Trained two-stage model filename')
parser.add_argument('--model-aff', type=str, default='', help='Trained affine model filename')
parser.add_argument('--model-tps', type=str, default='', help='Trained TPS model filename')
parser.add_argument('--pf-path', type=str, default='datasets/proposal-flow-pascal', help='Path to PF dataset')
parser.add_argument('--feature-extraction-cnn', type=str, default='resnet101', help='feature extraction CNN model architecture: vgg/resnet101')
parser.add_argument('--tps-reg-factor', type=float, default=0.0, help='regularisation factor for tps tnf')
args = parser.parse_args()
use_cuda = torch.cuda.is_available()
do_aff = not args.model_aff==''
do_tps = not args.model_tps==''
if args.pf_path=='':
args.args.pf_path='datasets/proposal-flow-pascal/'
# Download dataset if needed
if not exists(args.pf_path):
download_PF_pascal(args.pf_path)
# Create model
print('Creating CNN model...')
model = TwoStageCNNGeometric(use_cuda=use_cuda,
return_correlation=False,
feature_extraction_cnn=args.feature_extraction_cnn)
# Load trained weights
print('Loading trained model weights...')
if args.model!='':
checkpoint = torch.load(args.model, map_location=lambda storage, loc: storage)
checkpoint['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint['state_dict'].items()])
for name, param in model.FeatureExtraction.state_dict().items():
model.FeatureExtraction.state_dict()[name].copy_(checkpoint['state_dict']['FeatureExtraction.' + name])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression.' + name])
for name, param in model.FeatureRegression2.state_dict().items():
model.FeatureRegression2.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression2.' + name])
else:
checkpoint_aff = torch.load(args.model_aff, map_location=lambda storage, loc: storage)
checkpoint_aff['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint_aff['state_dict'].items()])
for name, param in model.FeatureExtraction.state_dict().items():
model.FeatureExtraction.state_dict()[name].copy_(checkpoint_aff['state_dict']['FeatureExtraction.' + name])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint_aff['state_dict']['FeatureRegression.' + name])
checkpoint_tps = torch.load(args.model_tps, map_location=lambda storage, loc: storage)
checkpoint_tps['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint_tps['state_dict'].items()])
for name, param in model.FeatureRegression2.state_dict().items():
model.FeatureRegression2.state_dict()[name].copy_(checkpoint_tps['state_dict']['FeatureRegression.' + name])
# Dataset and dataloader
dataset = PFPascalDataset(csv_file=os.path.join(args.pf_path, 'test_pairs_pf_pascal.csv'),
dataset_path=args.pf_path,
transform=NormalizeImageDict(['source_image','target_image']))
dataloader = DataLoader(dataset, batch_size=1,
shuffle=True, num_workers=4)
batchTensorToVars = BatchTensorToVars(use_cuda=use_cuda)
# Instatiate image transformers
affTnf = GeometricTnf(geometric_model='affine', use_cuda=use_cuda)
def affTpsTnf(source_image, theta_aff, theta_aff_tps, use_cuda=use_cuda):
tpstnf = GeometricTnf(geometric_model = 'tps',use_cuda=use_cuda)
sampling_grid = tpstnf(image_batch=source_image,
theta_batch=theta_aff_tps,
return_sampling_grid=True)[1]
X = sampling_grid[:,:,:,0].unsqueeze(3)
Y = sampling_grid[:,:,:,1].unsqueeze(3)
Xp = X*theta_aff[:,0].unsqueeze(1).unsqueeze(2)+Y*theta_aff[:,1].unsqueeze(1).unsqueeze(2)+theta_aff[:,2].unsqueeze(1).unsqueeze(2)
Yp = X*theta_aff[:,3].unsqueeze(1).unsqueeze(2)+Y*theta_aff[:,4].unsqueeze(1).unsqueeze(2)+theta_aff[:,5].unsqueeze(1).unsqueeze(2)
sg = torch.cat((Xp,Yp),3)
warped_image_batch = F.grid_sample(source_image, sg)
return warped_image_batch
for i, batch in enumerate(dataloader):
# get random batch of size 1
batch = batchTensorToVars(batch)
source_im_size = batch['source_im_size']
target_im_size = batch['target_im_size']
source_points = batch['source_points']
target_points = batch['target_points']
# warp points with estimated transformations
target_points_norm = PointsToUnitCoords(target_points,target_im_size)
model.eval()
# Evaluate model
theta_aff,theta_aff_tps=model(batch)
warped_image_aff = affTnf(batch['source_image'],theta_aff.view(-1,2,3))
warped_image_aff_tps = affTpsTnf(batch['source_image'],theta_aff, theta_aff_tps)
# Un-normalize images and convert to numpy
source_image = normalize_image(batch['source_image'],forward=False)
source_image = source_image.data.squeeze(0).transpose(0,1).transpose(1,2).cpu().numpy()
target_image = normalize_image(batch['target_image'],forward=False)
target_image = target_image.data.squeeze(0).transpose(0,1).transpose(1,2).cpu().numpy()
warped_image_aff = normalize_image(warped_image_aff,forward=False)
warped_image_aff = warped_image_aff.data.squeeze(0).transpose(0,1).transpose(1,2).cpu().numpy()
warped_image_aff_tps = normalize_image(warped_image_aff_tps,forward=False)
warped_image_aff_tps = warped_image_aff_tps.data.squeeze(0).transpose(0,1).transpose(1,2).cpu().numpy()
# check if display is available
exit_val = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()" > /dev/null 2>&1')
display_avail = exit_val==0
if display_avail:
N_subplots = 4
fig, axs = plt.subplots(1,N_subplots)
axs[0].imshow(source_image)
axs[0].set_title('src')
axs[1].imshow(target_image)
axs[1].set_title('tgt')
axs[2].imshow(warped_image_aff)
axs[2].set_title('aff')
axs[3].imshow(warped_image_aff_tps)
axs[3].set_title('aff+tps')
for i in range(N_subplots):
axs[i].axis('off')
print('Showing results. Close figure window to continue')
plt.show()
else:
print('No display found. Writing results to:')
fn_src = 'source.png'
print(fn_src)
io.imsave(fn_src, source_image)
fn_tgt = 'target.png'
print(fn_tgt)
io.imsave(fn_tgt, target_image)
fn_aff = 'result_aff.png'
print(fn_aff)
io.imsave(fn_aff, warped_image_aff)
fn_aff_tps = 'result_aff_tps.png'
print(fn_aff_tps)
io.imsave(fn_aff_tps,warped_image_aff_tps)
res = input('Run for another example ([y]/n): ')
if res=='n':
break
<file_sep>/util/eval_util.py
import torch
import numpy as np
import os
from skimage import draw
from geotnf.transformation import GeometricTnf
from geotnf.flow import th_sampling_grid_to_np_flow, write_flo_file
import torch.nn.functional as F
from data.pf_dataset import PFDataset, PFPascalDataset
from data.caltech_dataset import CaltechDataset
from torch.autograd import Variable
from geotnf.point_tnf import PointTnf, PointsToUnitCoords, PointsToPixelCoords
from util.py_util import create_file_path
from model.loss import WeakInlierCount, TwoStageWeakInlierCount
def compute_metric(metric,model,dataset,dataloader,batch_tnf,batch_size,two_stage=True,do_aff=False,do_tps=False,args=None):
# Initialize stats
N=len(dataset)
stats={}
# decide which results should be computed aff/tps/aff+tps
if two_stage or do_aff:
stats['aff']={}
if not two_stage and do_tps:
stats['tps']={}
if two_stage:
stats['aff_tps']={}
# choose metric function and metrics to compute
if metric=='pck':
metrics = ['pck']
metric_fun = pck_metric
if metric=='dist':
metrics = ['dist']
metric_fun = point_dist_metric
elif metric=='area':
metrics = ['intersection_over_union',
'label_transfer_accuracy',
'localization_error']
metric_fun = area_metrics
elif metric=='pascal_parts':
metrics = ['intersection_over_union','pck']
metric_fun = pascal_parts_metrics
elif metric=='flow':
metrics = ['flow']
metric_fun = flow_metrics
elif metric=='inlier_count':
metrics = ['inlier_count']
metric_fun = inlier_count
model.return_correlation = True
# initialize vector for storing results for each metric
for key in stats.keys():
for metric in metrics:
stats[key][metric] = np.zeros((N,1))
# Compute
for i, batch in enumerate(dataloader):
batch = batch_tnf(batch)
batch_start_idx=batch_size*i
batch_end_idx=np.minimum(batch_start_idx+batch_size,N)
model.eval()
theta_aff=None
theta_tps=None
theta_aff_tps=None
if two_stage:
if model.return_correlation==False:
theta_aff,theta_aff_tps=model(batch)
else:
theta_aff,theta_aff_tps,corr_aff,corr_aff_tps=model(batch)
elif do_aff:
theta_aff=model(batch)
if isinstance(theta_aff,tuple):
theta_aff=theta_aff[0]
elif do_tps:
theta_tps=model(batch)
if isinstance(theta_tps,tuple):
theta_tps=theta_tps[0]
if metric=='inlier_count':
stats = inlier_count(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,corr_aff,corr_aff_tps,stats,args)
elif metric_fun is not None:
stats = metric_fun(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args)
print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader)))
# Print results
if metric == 'flow':
print('Flow files have been saved to '+args.flow_output_dir)
return stats
for key in stats.keys():
print('=== Results '+key+' ===')
for metric in metrics:
# print per-class brakedown for PFPascal, or caltech
if isinstance(dataset,PFPascalDataset):
N_cat = int(np.max(dataset.category))
for c in range(N_cat):
cat_idx = np.nonzero(dataset.category==c+1)[0]
print(dataset.category_names[c].ljust(15)+': ','{:.2%}'.format(np.mean(stats[key][metric][cat_idx])))
# print mean value
results=stats[key][metric]
good_idx = np.flatnonzero((results!=-1) * ~np.isnan(results))
print('Total: '+str(results.size))
print('Valid: '+str(good_idx.size))
filtered_results = results[good_idx]
print(metric+':','{:.2%}'.format(np.mean(filtered_results)))
print('\n')
return stats
def pck(source_points,warped_points,L_pck,alpha=0.1):
# compute precentage of correct keypoints
batch_size=source_points.size(0)
pck=torch.zeros((batch_size))
for i in range(batch_size):
p_src = source_points[i,:]
p_wrp = warped_points[i,:]
N_pts = torch.sum(torch.ne(p_src[0,:],-1)*torch.ne(p_src[1,:],-1))
point_distance = torch.pow(torch.sum(torch.pow(p_src[:,:N_pts]-p_wrp[:,:N_pts],2),0),0.5)
L_pck_mat = L_pck[i].expand_as(point_distance)
correct_points = torch.le(point_distance,L_pck_mat*alpha)
pck[i]=torch.mean(correct_points.float())
return pck
def mean_dist(source_points,warped_points,L_pck):
# compute precentage of correct keypoints
batch_size=source_points.size(0)
dist=torch.zeros((batch_size))
for i in range(batch_size):
p_src = source_points[i,:]
p_wrp = warped_points[i,:]
N_pts = torch.sum(torch.ne(p_src[0,:],-1)*torch.ne(p_src[1,:],-1))
point_distance = torch.pow(torch.sum(torch.pow(p_src[:,:N_pts]-p_wrp[:,:N_pts],2),0),0.5)
L_pck_mat = L_pck[i].expand_as(point_distance)
dist[i]=torch.mean(torch.div(point_distance,L_pck_mat))
return dist
def point_dist_metric(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):
do_aff = theta_aff is not None
do_tps = theta_tps is not None
do_aff_tps = theta_aff_tps is not None
source_im_size = batch['source_im_size']
target_im_size = batch['target_im_size']
source_points = batch['source_points']
target_points = batch['target_points']
# Instantiate point transformer
pt = PointTnf(use_cuda=use_cuda,
tps_reg_factor=args.tps_reg_factor)
# warp points with estimated transformations
target_points_norm = PointsToUnitCoords(target_points,target_im_size)
if do_aff:
# do affine only
warped_points_aff_norm = pt.affPointTnf(theta_aff,target_points_norm)
warped_points_aff = PointsToPixelCoords(warped_points_aff_norm,source_im_size)
if do_tps:
# do tps only
warped_points_tps_norm = pt.tpsPointTnf(theta_tps,target_points_norm)
warped_points_tps = PointsToPixelCoords(warped_points_tps_norm,source_im_size)
if do_aff_tps:
# do tps+affine
warped_points_aff_tps_norm = pt.tpsPointTnf(theta_aff_tps,target_points_norm)
warped_points_aff_tps_norm = pt.affPointTnf(theta_aff,warped_points_aff_tps_norm)
warped_points_aff_tps = PointsToPixelCoords(warped_points_aff_tps_norm,source_im_size)
L_pck = batch['L_pck'].data
current_batch_size=batch['source_im_size'].size(0)
indices = range(batch_start_idx,batch_start_idx+current_batch_size)
# import pdb; pdb.set_trace()
if do_aff:
dist_aff = mean_dist(source_points.data, warped_points_aff.data, L_pck)
if do_tps:
dist_tps = mean_dist(source_points.data, warped_points_tps.data, L_pck)
if do_aff_tps:
dist_aff_tps = mean_dist(source_points.data, warped_points_aff_tps.data, L_pck)
if do_aff:
stats['aff']['dist'][indices] = dist_aff.unsqueeze(1).cpu().numpy()
if do_tps:
stats['tps']['dist'][indices] = dist_tps.unsqueeze(1).cpu().numpy()
if do_aff_tps:
stats['aff_tps']['dist'][indices] = dist_aff_tps.unsqueeze(1).cpu().numpy()
return stats
def inlier_count(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,corr_aff,corr_aff_tps,stats,args,use_cuda=True):
inliersComposed = TwoStageWeakInlierCount(use_cuda=torch.cuda.is_available(),dilation_filter=0,normalize_inlier_count=True)
inliers_comp = inliersComposed(matches=corr_aff,theta_aff=theta_aff,theta_aff_tps=theta_aff_tps)
current_batch_size=batch['source_im_size'].size(0)
indices = range(batch_start_idx,batch_start_idx+current_batch_size)
stats['aff_tps']['inlier_count'][indices] = inliers_comp.unsqueeze(1).cpu().data.numpy()
return stats
def pck_metric(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):
alpha = args.pck_alpha
do_aff = theta_aff is not None
do_tps = theta_tps is not None
do_aff_tps = theta_aff_tps is not None
source_im_size = batch['source_im_size']
target_im_size = batch['target_im_size']
source_points = batch['source_points']
target_points = batch['target_points']
# Instantiate point transformer
pt = PointTnf(use_cuda=use_cuda,
tps_reg_factor=args.tps_reg_factor)
# warp points with estimated transformations
target_points_norm = PointsToUnitCoords(target_points,target_im_size)
if do_aff:
# do affine only
warped_points_aff_norm = pt.affPointTnf(theta_aff,target_points_norm)
warped_points_aff = PointsToPixelCoords(warped_points_aff_norm,source_im_size)
if do_tps:
# do tps only
warped_points_tps_norm = pt.tpsPointTnf(theta_tps,target_points_norm)
warped_points_tps = PointsToPixelCoords(warped_points_tps_norm,source_im_size)
if do_aff_tps:
# do tps+affine
warped_points_aff_tps_norm = pt.tpsPointTnf(theta_aff_tps,target_points_norm)
warped_points_aff_tps_norm = pt.affPointTnf(theta_aff,warped_points_aff_tps_norm)
warped_points_aff_tps = PointsToPixelCoords(warped_points_aff_tps_norm,source_im_size)
L_pck = batch['L_pck'].data
current_batch_size=batch['source_im_size'].size(0)
indices = range(batch_start_idx,batch_start_idx+current_batch_size)
# import pdb; pdb.set_trace()
if do_aff:
pck_aff = pck(source_points.data, warped_points_aff.data, L_pck, alpha)
if do_tps:
pck_tps = pck(source_points.data, warped_points_tps.data, L_pck, alpha)
if do_aff_tps:
pck_aff_tps = pck(source_points.data, warped_points_aff_tps.data, L_pck, alpha)
if do_aff:
stats['aff']['pck'][indices] = pck_aff.unsqueeze(1).cpu().numpy()
if do_tps:
stats['tps']['pck'][indices] = pck_tps.unsqueeze(1).cpu().numpy()
if do_aff_tps:
stats['aff_tps']['pck'][indices] = pck_aff_tps.unsqueeze(1).cpu().numpy()
return stats
def pascal_parts_metrics(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):
do_aff = theta_aff is not None
do_tps = theta_tps is not None
do_aff_tps = theta_aff_tps is not None
batch_size=batch['source_im_size'].size(0)
for b in range(batch_size):
idx = batch_start_idx+b
h_src = int(batch['source_im_size'][b,0].data.cpu().numpy())
w_src = int(batch['source_im_size'][b,1].data.cpu().numpy())
h_tgt = int(batch['target_im_size'][b,0].data.cpu().numpy())
w_tgt = int(batch['target_im_size'][b,1].data.cpu().numpy())
# do pck
if batch['keypoint_A'][b].size!=0:
src_points = Variable(torch.FloatTensor(batch['keypoint_A'][b])).unsqueeze(0)
tgt_points = Variable(torch.FloatTensor(batch['keypoint_B'][b])).unsqueeze(0)
L_pck = Variable(torch.FloatTensor([batch['L_pck'][b]])).unsqueeze(1)
if use_cuda:
src_points=src_points.cuda()
tgt_points=tgt_points.cuda()
L_pck = L_pck.cuda()
batch_b = {'source_im_size': batch['source_im_size'][b,:].unsqueeze(0),
'target_im_size': batch['target_im_size'][b,:].unsqueeze(0),
'source_points': src_points,
'target_points': tgt_points,
'L_pck': L_pck}
args.pck_alpha = 0.05
stats = pck_metric(batch_b,
idx,
theta_aff[b,:].unsqueeze(0) if do_aff else None,
theta_tps[b,:].unsqueeze(0) if do_tps else None,
theta_aff_tps[b,:].unsqueeze(0) if do_aff_tps else None,
stats,args,use_cuda)
else:
if do_aff:
stats['aff']['pck'][idx] = -1
if do_tps:
stats['tps']['pck'][idx] = -1
if do_aff_tps:
stats['aff_tps']['pck'][idx] = -1
# do area
source_mask = Variable(torch.FloatTensor(batch['part_A'][b].astype(np.float32)).unsqueeze(0).transpose(2,3).transpose(1,2))
target_mask = Variable(torch.FloatTensor(batch['part_B'][b].astype(np.float32)).unsqueeze(0).transpose(2,3).transpose(1,2))
if use_cuda:
source_mask = source_mask.cuda()
target_mask = target_mask.cuda()
grid_aff,grid_tps,grid_aff_tps=theta_to_sampling_grid(h_tgt,w_tgt,
theta_aff[b,:] if do_aff else None,
theta_tps[b,:] if do_tps else None,
theta_aff_tps[b,:] if do_aff_tps else None,
use_cuda=use_cuda,
tps_reg_factor=args.tps_reg_factor)
if do_aff:
warped_mask_aff = F.grid_sample(source_mask, grid_aff)
stats['aff']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff,target_mask)
if do_tps:
warped_mask_tps = F.grid_sample(source_mask, grid_tps)
stats['tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_tps,target_mask)
if do_aff_tps:
warped_mask_aff_tps = F.grid_sample(source_mask, grid_aff_tps)
stats['aff_tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff_tps,target_mask)
return stats
def area_metrics(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):
do_aff = theta_aff is not None
do_tps = theta_tps is not None
do_aff_tps = theta_aff_tps is not None
batch_size=batch['source_im_size'].size(0)
pt=PointTnf(use_cuda=use_cuda)
for b in range(batch_size):
h_src = int(batch['source_im_size'][b,0].data.cpu().numpy())
w_src = int(batch['source_im_size'][b,1].data.cpu().numpy())
h_tgt = int(batch['target_im_size'][b,0].data.cpu().numpy())
w_tgt = int(batch['target_im_size'][b,1].data.cpu().numpy())
target_mask_np,target_mask = poly_str_to_mask(batch['target_polygon'][0][b],
batch['target_polygon'][1][b],
h_tgt,w_tgt,use_cuda=use_cuda)
source_mask_np,source_mask = poly_str_to_mask(batch['source_polygon'][0][b],
batch['source_polygon'][1][b],
h_src,w_src,use_cuda=use_cuda)
grid_X,grid_Y = np.meshgrid(np.linspace(-1,1,w_tgt),np.linspace(-1,1,h_tgt))
grid_X = torch.FloatTensor(grid_X).unsqueeze(0).unsqueeze(3)
grid_Y = torch.FloatTensor(grid_Y).unsqueeze(0).unsqueeze(3)
grid_X = Variable(grid_X,requires_grad=False)
grid_Y = Variable(grid_Y,requires_grad=False)
if use_cuda:
grid_X = grid_X.cuda()
grid_Y = grid_Y.cuda()
grid_X_vec = grid_X.view(1,1,-1)
grid_Y_vec = grid_Y.view(1,1,-1)
grid_XY_vec = torch.cat((grid_X_vec,grid_Y_vec),1)
def pointsToGrid (x,h_tgt=h_tgt,w_tgt=w_tgt): return x.contiguous().view(1,2,h_tgt,w_tgt).transpose(1,2).transpose(2,3)
idx = batch_start_idx+b
if do_aff:
grid_aff = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),grid_XY_vec))
warped_mask_aff = F.grid_sample(source_mask, grid_aff)
flow_aff = th_sampling_grid_to_np_flow(source_grid=grid_aff,h_src=h_src,w_src=w_src)
stats['aff']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff,target_mask)
stats['aff']['label_transfer_accuracy'][idx] = label_transfer_accuracy(warped_mask_aff,target_mask)
stats['aff']['localization_error'][idx] = localization_error(source_mask_np, target_mask_np, flow_aff)
if do_tps:
grid_tps = pointsToGrid(pt.tpsPointTnf(theta_tps[b,:].unsqueeze(0),grid_XY_vec))
warped_mask_tps = F.grid_sample(source_mask, grid_tps)
flow_tps = th_sampling_grid_to_np_flow(source_grid=grid_tps,h_src=h_src,w_src=w_src)
stats['tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_tps,target_mask)
stats['tps']['label_transfer_accuracy'][idx] = label_transfer_accuracy(warped_mask_tps,target_mask)
stats['tps']['localization_error'][idx] = localization_error(source_mask_np, target_mask_np, flow_tps)
if do_aff_tps:
grid_aff_tps = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),pt.tpsPointTnf(theta_aff_tps[b,:].unsqueeze(0),grid_XY_vec)))
warped_mask_aff_tps = F.grid_sample(source_mask, grid_aff_tps)
flow_aff_tps = th_sampling_grid_to_np_flow(source_grid=grid_aff_tps,h_src=h_src,w_src=w_src)
stats['aff_tps']['intersection_over_union'][idx] = intersection_over_union(warped_mask_aff_tps,target_mask)
stats['aff_tps']['label_transfer_accuracy'][idx] = label_transfer_accuracy(warped_mask_aff_tps,target_mask)
stats['aff_tps']['localization_error'][idx] = localization_error(source_mask_np, target_mask_np, flow_aff_tps)
return stats
def flow_metrics(batch,batch_start_idx,theta_aff,theta_tps,theta_aff_tps,stats,args,use_cuda=True):
result_path=args.flow_output_dir
do_aff = theta_aff is not None
do_tps = theta_tps is not None
do_aff_tps = theta_aff_tps is not None
pt=PointTnf(use_cuda=use_cuda)
batch_size=batch['source_im_size'].size(0)
for b in range(batch_size):
h_src = int(batch['source_im_size'][b,0].data.cpu().numpy())
w_src = int(batch['source_im_size'][b,1].data.cpu().numpy())
h_tgt = int(batch['target_im_size'][b,0].data.cpu().numpy())
w_tgt = int(batch['target_im_size'][b,1].data.cpu().numpy())
grid_X,grid_Y = np.meshgrid(np.linspace(-1,1,w_tgt),np.linspace(-1,1,h_tgt))
grid_X = torch.FloatTensor(grid_X).unsqueeze(0).unsqueeze(3)
grid_Y = torch.FloatTensor(grid_Y).unsqueeze(0).unsqueeze(3)
grid_X = Variable(grid_X,requires_grad=False)
grid_Y = Variable(grid_Y,requires_grad=False)
if use_cuda:
grid_X = grid_X.cuda()
grid_Y = grid_Y.cuda()
grid_X_vec = grid_X.view(1,1,-1)
grid_Y_vec = grid_Y.view(1,1,-1)
grid_XY_vec = torch.cat((grid_X_vec,grid_Y_vec),1)
def pointsToGrid (x,h_tgt=h_tgt,w_tgt=w_tgt): return x.contiguous().view(1,2,h_tgt,w_tgt).transpose(1,2).transpose(2,3)
idx = batch_start_idx+b
if do_aff:
grid_aff = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),grid_XY_vec))
flow_aff = th_sampling_grid_to_np_flow(source_grid=grid_aff,h_src=h_src,w_src=w_src)
flow_aff_path = os.path.join(result_path,'aff',batch['flow_path'][b])
create_file_path(flow_aff_path)
write_flo_file(flow_aff,flow_aff_path)
if do_tps:
grid_tps = pointsToGrid(pt.tpsPointTnf(theta_tps[b,:].unsqueeze(0),grid_XY_vec))
flow_tps = th_sampling_grid_to_np_flow(source_grid=grid_tps,h_src=h_src,w_src=w_src)
flow_tps_path = os.path.join(result_path,'tps',batch['flow_path'][b])
create_file_path(flow_tps_path)
write_flo_file(flow_tps,flow_tps_path)
if do_aff_tps:
grid_aff_tps = pointsToGrid(pt.affPointTnf(theta_aff[b,:].unsqueeze(0),pt.tpsPointTnf(theta_aff_tps[b,:].unsqueeze(0),grid_XY_vec)))
flow_aff_tps = th_sampling_grid_to_np_flow(source_grid=grid_aff_tps,h_src=h_src,w_src=w_src)
flow_aff_tps_path = os.path.join(result_path,'aff_tps',batch['flow_path'][b])
create_file_path(flow_aff_tps_path)
write_flo_file(flow_aff_tps,flow_aff_tps_path)
idx = batch_start_idx+b
return stats
def poly_to_mask(vertex_row_coords, vertex_col_coords, shape):
fill_row_coords, fill_col_coords = draw.polygon(vertex_row_coords, vertex_col_coords, shape)
mask = np.zeros(shape, dtype=np.bool)
mask[fill_row_coords, fill_col_coords] = True
return mask
def poly_str_to_mask(poly_x_str,poly_y_str,out_h,out_w,use_cuda=True):
polygon_x = np.fromstring(poly_x_str,sep=',')
polygon_y = np.fromstring(poly_y_str,sep=',')
mask_np = poly_to_mask(vertex_col_coords=polygon_x,
vertex_row_coords=polygon_y,shape=[out_h,out_w])
mask = Variable(torch.FloatTensor(mask_np.astype(np.float32)).unsqueeze(0).unsqueeze(0))
if use_cuda:
mask = mask.cuda()
return (mask_np,mask)
#def intersection_over_union(warped_mask,target_mask):
# return torch.sum(warped_mask.data.gt(0.5) & target_mask.data.gt(0.5))/torch.sum(warped_mask.data.gt(0.5) | target_mask.data.gt(0.5))
def intersection_over_union(warped_mask,target_mask):
relative_part_weight = torch.sum(torch.sum(target_mask.data.gt(0.5).float(),2,True),3,True)/torch.sum(target_mask.data.gt(0.5).float())
part_iou = torch.sum(torch.sum((warped_mask.data.gt(0.5) & target_mask.data.gt(0.5)).float(),2,True),3,True)/torch.sum(torch.sum((warped_mask.data.gt(0.5) | target_mask.data.gt(0.5)).float(),2,True),3,True)
weighted_iou = torch.sum(torch.mul(relative_part_weight,part_iou))
return weighted_iou
def label_transfer_accuracy(warped_mask,target_mask):
return torch.mean((warped_mask.data.gt(0.5) == target_mask.data.gt(0.5)).double())
def localization_error(source_mask_np, target_mask_np, flow_np):
h_tgt, w_tgt = target_mask_np.shape[0],target_mask_np.shape[1]
h_src, w_src = source_mask_np.shape[0],source_mask_np.shape[1]
# initial pixel positions x1,y1 in target image
x1, y1 = np.meshgrid(range(1,w_tgt+1), range(1,h_tgt+1))
# sampling pixel positions x2,y2
x2 = x1 + flow_np[:,:,0]
y2 = y1 + flow_np[:,:,1]
# compute in-bound coords for each image
in_bound = (x2 >= 1) & (x2 <= w_src) & (y2 >= 1) & (y2 <= h_src)
row,col = np.where(in_bound)
row_1=y1[row,col].flatten().astype(np.int)-1
col_1=x1[row,col].flatten().astype(np.int)-1
row_2=y2[row,col].flatten().astype(np.int)-1
col_2=x2[row,col].flatten().astype(np.int)-1
# compute relative positions
target_loc_x,target_loc_y = obj_ptr(target_mask_np)
source_loc_x,source_loc_y = obj_ptr(source_mask_np)
x1_rel=target_loc_x[row_1,col_1]
y1_rel=target_loc_y[row_1,col_1]
x2_rel=source_loc_x[row_2,col_2]
y2_rel=source_loc_y[row_2,col_2]
# compute localization error
loc_err = np.mean(np.abs(x1_rel-x2_rel)+np.abs(y1_rel-y2_rel))
return loc_err
def obj_ptr(mask):
# computes images of normalized coordinates around bounding box
# kept function name from DSP code
h,w = mask.shape[0],mask.shape[1]
y, x = np.where(mask>0.5)
left = np.min(x);
right = np.max(x);
top = np.min(y);
bottom = np.max(y);
fg_width = right-left + 1;
fg_height = bottom-top + 1;
x_image,y_image = np.meshgrid(range(1,w+1), range(1,h+1));
x_image = (x_image - left)/fg_width;
y_image = (y_image - top)/fg_height;
return (x_image,y_image)
<file_sep>/train_weak.py
from __future__ import print_function, division
import argparse
import os
from os.path import exists, join, basename
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms
#from torch.utils.data import DataLoader
from util.dataloader import DataLoader # modified dataloader
from model.cnn_geometric_model import CNNGeometric, TwoStageCNNGeometric, FeatureCorrelation, featureL2Norm
from model.loss import TransformedGridLoss, WeakInlierCount, TwoStageWeakInlierCount
from data.synth_dataset import SynthDataset
from data.weak_dataset import ImagePairDataset
from data.pf_dataset import PFDataset, PFPascalDataset
from data.download_datasets import download_PF_pascal
from geotnf.transformation import SynthPairTnf,SynthTwoPairTnf,SynthTwoStageTwoPairTnf
from image.normalization import NormalizeImageDict
from util.torch_util import save_checkpoint, str_to_bool
from util.torch_util import BatchTensorToVars
from geotnf.transformation import GeometricTnf
from collections import OrderedDict
import numpy as np
import numpy.random
from scipy.ndimage.morphology import binary_dilation,generate_binary_structure
import torch.nn.functional as F
from model.cnn_geometric_model import featureL2Norm
from util.dataloader import default_collate
from util.eval_util import pck_metric, area_metrics, flow_metrics, compute_metric
from options.options import ArgumentParser
"""
Script to train the model using weak supervision
"""
print('WeakAlign training script using weak supervision')
# Argument parsing
args,arg_groups = ArgumentParser(mode='train_weak').parse()
print(args)
use_cuda = torch.cuda.is_available()
# Seed
torch.manual_seed(args.seed)
if use_cuda:
torch.cuda.manual_seed(args.seed)
np.random.seed(args.seed)
# CNN model and loss
print('Creating CNN model...')
model = TwoStageCNNGeometric(use_cuda=use_cuda,
return_correlation=True,
**arg_groups['model'])
# Download validation dataset if needed
if args.eval_dataset_path=='' and args.eval_dataset=='pf-pascal':
args.eval_dataset_path='datasets/proposal-flow-pascal/'
if args.eval_dataset=='pf-pascal' and not exists(args.eval_dataset_path):
download_PF_pascal(args.eval_dataset_path)
# load pre-trained model
if args.model!='':
checkpoint = torch.load(args.model, map_location=lambda storage, loc: storage)
checkpoint['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint['state_dict'].items()])
for name, param in model.FeatureExtraction.state_dict().items():
model.FeatureExtraction.state_dict()[name].copy_(checkpoint['state_dict']['FeatureExtraction.' + name])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression.' + name])
for name, param in model.FeatureRegression2.state_dict().items():
model.FeatureRegression2.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression2.' + name])
if args.model_aff!='':
checkpoint_aff = torch.load(args.model_aff, map_location=lambda storage, loc: storage)
checkpoint_aff['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint_aff['state_dict'].items()])
for name, param in model.FeatureExtraction.state_dict().items():
model.FeatureExtraction.state_dict()[name].copy_(checkpoint_aff['state_dict']['FeatureExtraction.' + name])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint_aff['state_dict']['FeatureRegression.' + name])
if args.model_tps!='':
checkpoint_tps = torch.load(args.model_tps, map_location=lambda storage, loc: storage)
checkpoint_tps['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint_tps['state_dict'].items()])
for name, param in model.FeatureRegression2.state_dict().items():
model.FeatureRegression2.state_dict()[name].copy_(checkpoint_tps['state_dict']['FeatureRegression.' + name])
# set which parts of model to train
for name,param in model.FeatureExtraction.named_parameters():
param.requires_grad = False
if args.train_fe and np.sum([name.find(x)!=-1 for x in args.fe_finetune_params]):
param.requires_grad = True
if args.train_fe and name.find('bn')!=-1 and np.sum([name.find(x)!=-1 for x in args.fe_finetune_params]):
param.requires_grad = args.train_bn
for name,param in model.FeatureExtraction.named_parameters():
print(name.ljust(30),param.requires_grad)
for name,param in model.FeatureRegression.named_parameters():
param.requires_grad = args.train_fr
if args.train_fr and name.find('bn')!=-1:
param.requires_grad = args.train_bn
for name,param in model.FeatureRegression2.named_parameters():
param.requires_grad = args.train_fr
if args.train_fr and name.find('bn')!=-1:
param.requires_grad = args.train_bn
# define loss
print('Using weak loss...')
if args.dilation_filter==0:
dilation_filter = 0
else:
dilation_filter = generate_binary_structure(2, args.dilation_filter)
inliersAffine = WeakInlierCount(geometric_model='affine',**arg_groups['weak_loss'])
inliersTps = WeakInlierCount(geometric_model='tps',**arg_groups['weak_loss'])
inliersComposed = TwoStageWeakInlierCount(use_cuda=use_cuda,**arg_groups['weak_loss'])
def inlier_score_function(theta_aff,theta_aff_tps,corr_aff,corr_aff_tps,minimize_outliers=False):
inliers_comp = inliersComposed(matches=corr_aff,
theta_aff=theta_aff,
theta_aff_tps=theta_aff_tps)
inliers_aff = inliersAffine(matches=corr_aff,
theta=theta_aff)
inlier_score=inliers_aff+inliers_comp
return inlier_score
def loss_fun(batch):
theta_aff,theta_aff_tps,corr_aff,corr_aff_tps=model(batch)
inlier_score_pos = inlier_score_function(theta_aff,
theta_aff_tps,
corr_aff,
corr_aff_tps)
loss = torch.mean(-inlier_score_pos)
return loss
# dataset
train_dataset_size = args.train_dataset_size if args.train_dataset_size!=0 else None
dataset = ImagePairDataset(csv_file=os.path.join(args.dataset_csv_path,'train_pairs.csv'),
training_image_path=args.dataset_image_path,
transform=NormalizeImageDict(['source_image','target_image']),
dataset_size = train_dataset_size,
random_crop=args.random_crop)
dataset_eval = PFPascalDataset(csv_file=os.path.join(args.eval_dataset_path, 'val_pairs_pf_pascal.csv'),
dataset_path=args.eval_dataset_path,
transform=NormalizeImageDict(['source_image','target_image']))
# filter training categories
if args.categories!=0:
keep = np.zeros((len(dataset.set),1))
for i in range(len(dataset.set)):
keep[i]=np.sum(dataset.set[i]==args.categories)
keep_idx = np.nonzero(keep)[0]
dataset.set = dataset.set[keep_idx]
dataset.img_A_names = dataset.img_A_names[keep_idx]
dataset.img_B_names = dataset.img_B_names[keep_idx]
batch_tnf = BatchTensorToVars(use_cuda=use_cuda)
# dataloader
dataloader = DataLoader(dataset, batch_size=args.batch_size,
shuffle=True, num_workers=4)
dataloader_eval = DataLoader(dataset_eval, batch_size=8,
shuffle=False, num_workers=4)
# define checkpoint name
checkpoint_suffix = '_' + args.feature_extraction_cnn
if args.tps_reg_factor != 0:
checkpoint_suffix += '_regfact' + str(args.tps_reg_factor)
checkpoint_name = os.path.join(args.result_model_dir,
args.result_model_fn + checkpoint_suffix + '.pth.tar')
print(checkpoint_name)
# define epoch function
def process_epoch(mode,epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn,use_cuda=True,log_interval=50):
epoch_loss = 0
for batch_idx, batch in enumerate(dataloader):
if mode=='train':
optimizer.zero_grad()
tnf_batch = batch_preprocessing_fn(batch)
loss = loss_fn(tnf_batch)
loss_np = loss.data.cpu().numpy()[0]
epoch_loss += loss_np
if mode=='train':
loss.backward()
optimizer.step()
else:
loss=None
if batch_idx % log_interval == 0:
print(mode.capitalize()+' Epoch: {} [{}/{} ({:.0f}%)]\t\tLoss: {:.6f}'.format(
epoch, batch_idx , len(dataloader),
100. * batch_idx / len(dataloader), loss_np))
epoch_loss /= len(dataloader)
print(mode.capitalize()+' set: Average loss: {:.4f}'.format(epoch_loss))
return epoch_loss
# compute initial value of evaluation metric used for early stopping
if args.eval_metric=='dist':
metric = 'dist'
if args.eval_metric=='pck':
metric = 'pck'
do_aff = args.model_aff!=""
do_tps = args.model_tps!=""
two_stage = args.model!='' or (do_aff and do_tps)
if args.categories==0:
eval_categories = np.array(range(20))+1
else:
eval_categories = np.array(args.categories)
eval_flag = np.zeros(len(dataset_eval))
for i in range(len(dataset_eval)):
eval_flag[i]=sum(eval_categories==dataset_eval.category[i])
eval_idx = np.flatnonzero(eval_flag)
model.eval()
stats=compute_metric(metric,model,dataset_eval,dataloader_eval,batch_tnf,8,two_stage,do_aff,do_tps,args)
eval_value=np.mean(stats['aff_tps'][metric][eval_idx])
print(eval_value)
# train
best_test_loss = float("inf")
train_loss = np.zeros(args.num_epochs)
test_loss = np.zeros(args.num_epochs)
optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, weight_decay=args.weight_decay)
print('Starting training...')
for epoch in range(1, args.num_epochs+1):
if args.update_bn_buffers==False:
model.eval()
else:
model.train()
train_loss[epoch-1] = process_epoch('train',epoch,model,loss_fun,optimizer,dataloader,batch_tnf,log_interval=1)
model.eval()
stats=compute_metric(metric,model,dataset_eval,dataloader_eval,batch_tnf,8,two_stage,do_aff,do_tps,args)
eval_value=np.mean(stats['aff_tps'][metric][eval_idx])
print(eval_value)
if args.eval_metric=='pck':
test_loss[epoch-1] = -eval_value
else:
test_loss[epoch-1] = eval_value
# remember best loss
is_best = test_loss[epoch-1] < best_test_loss
best_test_loss = min(test_loss[epoch-1], best_test_loss)
save_checkpoint({
'epoch': epoch + 1,
'args': args,
'state_dict': model.state_dict(),
'best_test_loss': best_test_loss,
'optimizer' : optimizer.state_dict(),
'train_loss': train_loss,
'test_loss': test_loss,
}, is_best,checkpoint_name)
print('Done!')<file_sep>/train_strong.py
from __future__ import print_function, division
import os
from os.path import exists, join, basename
import torch
import torch.nn as nn
import torch.optim as optim
#from torch.utils.data import Dataset, DataLoader
from util.dataloader import DataLoader # modified dataloader
from torch.utils.data import Dataset
from model.cnn_geometric_model import CNNGeometric
from model.loss import TransformedGridLoss
from data.synth_dataset import SynthDataset
from data.download_datasets import download_pascal
from geotnf.transformation import SynthPairTnf
from image.normalization import NormalizeImageDict
#from util.train_test_fn import train_fun_strong, test_fun_strong
from util.torch_util import save_checkpoint, str_to_bool
import numpy as np
import numpy.random
from collections import OrderedDict
from options.options import ArgumentParser
"""
Script to train the model as presented in the CNNGeometric CVPR'17 paper
using synthetically warped image pairs and strong supervision
"""
print('CNNGeometric training script using strong supervision')
# Argument parsing
args,arg_groups = ArgumentParser(mode='train_strong').parse()
print(args)
# Seed and CUDA
use_cuda = torch.cuda.is_available()
torch.manual_seed(args.seed)
if use_cuda:
torch.cuda.manual_seed(args.seed)
np.random.seed(args.seed)
# Download dataset if needed and set paths
if args.training_dataset == 'pascal':
if args.dataset_image_path == '':
if not exists('datasets/pascal-voc11/TrainVal'):
download_pascal('datasets/pascal-voc11/')
args.dataset_image_path = 'datasets/pascal-voc11/'
if args.dataset_csv_path == '' and args.geometric_model=='affine':
args.dataset_csv_path = 'training_data/pascal-synth-aff'
elif args.dataset_csv_path == '' and args.geometric_model=='tps':
args.dataset_csv_path = 'training_data/pascal-synth-tps'
arg_groups['dataset']['dataset_image_path']=args.dataset_image_path
# CNN model and loss
print('Creating CNN model...')
if args.geometric_model=='affine':
cnn_output_dim = 6
elif args.geometric_model=='tps':
cnn_output_dim = 18
model = CNNGeometric(use_cuda=use_cuda,
output_dim=cnn_output_dim,
**arg_groups['model'])
# Load pretrained model
if args.model!='':
checkpoint = torch.load(args.model, map_location=lambda storage, loc: storage)
checkpoint['state_dict'] = OrderedDict([(k.replace('vgg', 'model'), v) for k, v in checkpoint['state_dict'].items()])
for name, param in model.FeatureExtraction.state_dict().items():
model.FeatureExtraction.state_dict()[name].copy_(checkpoint['state_dict']['FeatureExtraction.' + name])
for name, param in model.FeatureRegression.state_dict().items():
model.FeatureRegression.state_dict()[name].copy_(checkpoint['state_dict']['FeatureRegression.' + name])
if args.use_mse_loss:
print('Using MSE loss...')
loss = nn.MSELoss()
else:
print('Using grid loss...')
loss = TransformedGridLoss(use_cuda=use_cuda,geometric_model=args.geometric_model)
# Dataset and dataloader
dataset = SynthDataset(geometric_model=args.geometric_model,
transform=NormalizeImageDict(['image']),
dataset_csv_file = 'train.csv',
**arg_groups['dataset'])
dataloader = DataLoader(dataset, batch_size=args.batch_size,
shuffle=True,
num_workers=4) # don't change num_workers, as they copy the rnd seed
dataset_test = SynthDataset(geometric_model=args.geometric_model,
transform=NormalizeImageDict(['image']),
dataset_csv_file='test.csv',
**arg_groups['dataset'])
dataloader_test = DataLoader(dataset_test, batch_size=args.batch_size,
shuffle=True, num_workers=4)
cnn_image_size=(args.image_size,args.image_size)
pair_generation_tnf = SynthPairTnf(geometric_model=args.geometric_model,
output_size=cnn_image_size,
use_cuda=use_cuda)
# Optimizer
optimizer = optim.Adam(model.FeatureRegression.parameters(), lr=args.lr)
# Define checkpoint name
checkpoint_suffix = '_strong'
checkpoint_suffix += '_' + str(args.num_epochs)
checkpoint_suffix += '_' + args.training_dataset
checkpoint_suffix += '_' + args.geometric_model
checkpoint_suffix += '_' + args.feature_extraction_cnn
if args.use_mse_loss:
checkpoint_suffix += '_mse_loss'
else:
checkpoint_suffix += '_grid_loss'
checkpoint_name = os.path.join(args.result_model_dir,
args.result_model_fn + checkpoint_suffix + '.pth.tar')
print(checkpoint_name)
# Train
best_test_loss = float("inf")
# define epoch function
def process_epoch(mode,epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn,use_cuda=True,log_interval=50):
epoch_loss = 0
for batch_idx, batch in enumerate(dataloader):
if mode=='train':
optimizer.zero_grad()
tnf_batch = batch_preprocessing_fn(batch)
theta = model(tnf_batch)
loss = loss_fn(theta,tnf_batch['theta_GT'])
loss_np = loss.data.cpu().numpy()[()]
epoch_loss += loss_np
if mode=='train':
loss.backward()
optimizer.step()
else:
loss=None
if batch_idx % log_interval == 0:
print(mode.capitalize()+' Epoch: {} [{}/{} ({:.0f}%)]\t\tLoss: {:.6f}'.format(
epoch, batch_idx , len(dataloader),
100. * batch_idx / len(dataloader), loss_np))
epoch_loss /= len(dataloader)
print(mode.capitalize()+' set: Average loss: {:.4f}'.format(epoch_loss))
return epoch_loss
train_loss = np.zeros(args.num_epochs)
test_loss = np.zeros(args.num_epochs)
print('Starting training...')
model.FeatureExtraction.eval()
for epoch in range(1, args.num_epochs+1):
model.FeatureRegression.train()
train_loss[epoch-1] = process_epoch('train',epoch,model,loss,optimizer,dataloader,pair_generation_tnf,log_interval=100)
model.FeatureRegression.eval()
test_loss[epoch-1] = process_epoch('test',epoch,model,loss,optimizer,dataloader_test,pair_generation_tnf,log_interval=100)
# remember best loss
is_best = test_loss[epoch-1] < best_test_loss
best_test_loss = min(test_loss[epoch-1], best_test_loss)
save_checkpoint({
'epoch': epoch + 1,
'args': args,
'state_dict': model.state_dict(),
'best_test_loss': best_test_loss,
'optimizer' : optimizer.state_dict(),
'train_loss': train_loss,
'test_loss': test_loss,
}, is_best,checkpoint_name)
print('Done!')
| 8d0535c0af835ef24649dfeb600c3090cb74a196 | [
"Python"
] | 9 | Python | cianeastwood/weakalign | c610a29f82cc2ff18a3415bef6b440aa538a4f7d | de89ee69a3930e65577668847df70793a68486fc |
refs/heads/master | <repo_name>AzamatSharipov/vitae-bot<file_sep>/requirements.txt
certifi==2020.6.20
chardet==3.0.4
geographiclib==1.50
geopy==2.0.0
idna==2.10
pyTelegramBotAPI==3.7.3
requests==2.24.0
six==1.15.0
urllib3==1.25.10
<file_sep>/main.py
import telebot
from telebot import types
from geopy.geocoders import Nominatim
bot =telebot.TeleBot('1372088219:AAEFWaIZq_tbzQ8MWoqA3YIt2MgcTGuYAUg')
data = {'contact': "", 'type': "", 'weight': ""}
bot.state = None # create own value `.state` in `bot` - so I don't have to use `global state`. Similar way I could create and use `bot.data`
@bot.message_handler(commands=['start'])
def start(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
btn1 =types.KeyboardButton('Kontakt 📲', request_contact=True)
markup.add(btn1)
send_mess = f"<b>Salom, {message.from_user.first_name}! </b> \nBuyurtma berishdan avval o'z kontaklaringiz bilan ulashing!"
bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=markup)
global user_id
user_id = message.from_user.id
@bot.message_handler(content_types=['contact'])
def mess(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
btn1 =types.KeyboardButton('Lokatsiya 📍', request_location=True)
btn2 = types.KeyboardButton("O'tkazib yuborish ➡️")
markup.add(btn1, btn2)
send_mess = f"Rahmat, davom etish uchun lokatsiyani ham ulashing"
bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=markup)
data['contact'] = message.contact.phone_number
global user_number
user_number = message.contact.phone_number
@bot.message_handler(content_types=['location'])
def mess(message):
send_mess = f"<b>Rahmat {message.from_user.first_name} </b>!"
bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=mainkeyboard)
coord = (message.location.latitude, message.location.longitude)
geolocator = Nominatim(user_agent="main.py")
location = geolocator.reverse(f'{coord[0]}, {coord[1]}')
data['type'] = location.address
msg = "<b>Имя:</b> {} \n<b>Номер:</b> {} \n<b>Адрес:</b> {} ".format(message.from_user.first_name, data['contact'], data['type'])
bot.send_message(-452474686, msg, parse_mode='html')
bot.send_location(-452474686, message.location.latitude, message.location.longitude)
global mainkeyboard
global keyboard
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2, one_time_keyboard=True)
btn1 = types.KeyboardButton('1kg')
btn2 = types.KeyboardButton('5kg')
btn3 = types.KeyboardButton('10kg')
btn4 = types.KeyboardButton("20kg")
btn5 = types.KeyboardButton("50kg")
btn6 = types.KeyboardButton("Boshqasi")
btn7 = types.KeyboardButton('Bekor qilish ❌')
keyboard.add(btn1, btn2, btn3, btn4, btn5, btn6, btn7)
mainkeyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton('Mahsulotlarimiz 🐛')
btn2 = types.KeyboardButton('Bizning manzilimiz 📍')
btn3 = types.KeyboardButton("Bog'lanish uchun ☎️")
btn4 = types.KeyboardButton('Vitae.uz ✅')
mainkeyboard.add(btn1, btn2, btn3, btn4)
order = {'product': "", 'weight': ""}
@bot.message_handler(content_types=['text'])
def mess(message):
get_message_bot = message.text.strip().lower()
if get_message_bot == "o'tkazib yuborish ➡️":
send_mess = f"<b>Rahmat {message.from_user.first_name} </b>!"
bot.send_message(message.chat.id, send_mess, parse_mode='html', reply_markup=mainkeyboard)
msg = "<b>Имя:</b> {} \n<b>Номер:</b> {} ".format(message.from_user.first_name, data['contact'])
bot.send_message(-452474686, msg, parse_mode='html')
elif get_message_bot == "ortga qaytish ⬅️":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi')
btn2 = types.KeyboardButton('Quritilgan lichinka')
btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia»')
btn4 = types.KeyboardButton("Organik o'g'it «Germecia» Biohumus")
btn5 = types.KeyboardButton("Yog'li «Germecia»")
btn6 = types.KeyboardButton('Boshiga ⬅️')
markup.add(btn1, btn2, btn3, btn4, btn5, btn6)
final_message = "Sizni nima qiziqtirmoqda?"
bot.send_message(message.chat.id, final_message, parse_mode='html', reply_markup=markup)
elif get_message_bot == "boshiga ⬅️":
final_message = "Sizni nima qiziqtirmoqda?"
bot.send_message(message.chat.id, final_message, parse_mode='html', reply_markup=mainkeyboard)
elif get_message_bot == "bizning manzilimiz 📍":
manzil = "Toshkent tumani, Taraqqiy ko’chasi"
bot.send_message(message.chat.id, manzil,)
bot.send_location(message.chat.id, 41.436964, 69.372849)
elif get_message_bot == "bog'lanish uchun ☎️":
telefon = f"<b>Телефон:</b>\n+99899 871-17-04 \n+99890 319-62-68\n\n" \
f"<b>E-mail:</b>\n<EMAIL>"
bot.send_message(message.chat.id, telefon, parse_mode='html')
elif get_message_bot == "mahsulotlarimiz 🐛":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi')
btn2 = types.KeyboardButton('Quritilgan lichinka')
btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia»')
btn4 = types.KeyboardButton("Organik o'g'it «Germecia» Biohumus")
btn5 = types.KeyboardButton("Yog'li «Germecia»")
btn6 = types.KeyboardButton('Buyurtma berish 📌')
btn7 = types.KeyboardButton('Boshiga ⬅️')
markup.add(btn1, btn2, btn3, btn4, btn5, btn6, btn7)
finaal_message = "Sizni nima qiziqtirmoqda??"
bot.send_message(message.chat.id, finaal_message, parse_mode='html', reply_markup=markup)
elif get_message_bot == "vitae.uz ✅":
p = open("images/vita.jpg", 'rb')
about = "<b>Kuniga 10.000kg ozuqa xomashyosi</b> \n\n" \
"Bizning ishlab chiqarish quvvatlarimiz kuniga 10 tonnagacha ozuqa xomashyosini qayta ishlashga imkon beradi. " \
"Shunday qilib, biz O’zbekistondagi eng yirik qora lichinka baliqlari mahsulotlarini ishlab chiqaruvchilarmiz. " \
"Faqat o’simlik materiallaridan foydalanish sanitariya va veterinariya me’yorlariga javob beradigan eng xavfsiz mahsulotni olishga imkon beradi. " \
"Amaldagi texnologiya va uskunalar lichinkaning biologik qiymatini va uni qayta ishlash mahsulotlarini saqlashga imkon beradi \n\n" \
"<b>✅ Yanada kuchli tuxum po’stlari. Har bir cho’qish bilan 50 barobarko’proq kaltsiy oling.\n\n" \
"✅ Qurtlar – quritilgan qora askar chivinlari lichinkalari, tovuqlar uchun kunlik sog’lik garovidir.\n\n" \
"✅ Yaxlitlash osonroq. Ovqatlanish paytida lichinkalarni tuting va muhabbat bilan o’rab oling. ular yugurib kelishadi.</b>"
bot.send_photo(message.chat.id, p, about, parse_mode='html')
elif get_message_bot == "quritilgan lichinka":
p = open("images/ql.jpg", 'rb')
info = "<b>Quritilgan lichinka:</b>\n\n" \
"<b>Tavsif:</b> Qora lvinkaning (Hermetia illusens) quritilgan butun lichinkasi\n\n" \
"<b>Tarkibi:</b> 100% qora lvinka lichinkalaridan iborat\n\n" \
"<b>Ilova:</b> U qishloq xo’jaligi hayvonlari, parrandalar, suv xo’jaligi va mahsuldor bo’lmagan hayvonlar uchun ozuqada oqsil, yog ‘va uglevodlarning manbai sifatida ishlatiladi.\n\n" \
"<b>Jismoniy xususiyatlari:</b>\n\n" \
"<b>Hidi:</b> o’ziga xos, qattiq emas, chirigan emas, yumshoq rang.\n" \
"<b>Rangi:</b> Kulrangdan jigarranggacha.\n" \
"<b>Xavfsizlik ko’rsatkichlari:</b> Toksik emas Anaeroblar – yo’q\n" \
"<b>Salmonella</b> – yo’q\n" \
"<b>Escherichia coli</b> – yo’q\n" \
"<b>Proteus</b> – yo’q\n" \
"<b>Qadoq:</b>…, …, …, litr sumkalar\n\n" \
"<b>Saqlash muddati:</b> 12 oy"
bot.send_photo(message.chat.id, p, info, parse_mode='html')
elif get_message_bot == "qora lvinkaning tirik lichinkasi":
p = open("images/tk.jpg", 'rb')
info = "<b>Tirik Lichinka:</b>\n\n" \
"<b>Tavsif:</b> Qora lvinkaning jonli lichinkasi( Hermetia illusens). Lichinkaning uzunligi 25 mm gacha, kengligi 5 mm gacha – yoshga qarab.\n\n" \
"<b>Tarkibi:</b> 100% qora lvinka lichinkalaridan iborat.\n\n" \
"<b>Ilova:</b> U hasharotlar, qushlar, sudralib yuruvchilar, amfibiyalar va baliqlar uchun jonli ovqat sifatida ishlatiladi. U baliq ovlashda jonli o’lja sifatida ishlatiladi. Baliq ovi uchun ishlatiladigan goʻshtli pashhaga alternativ sifatida. Lichinkani turli yoshlarda olib tashlash orqali biz turli o’lchamdagi lichinkalarni olamiz – 10 dan 25 mm gacha.\n\n" \
"<b>Jismoniy xususiyatlari:</b>\n\n" \
"<b>Hid:</b> o’ziga xos, qattiq emas, chirigan emas, yumshoq\n" \
"<b>Rang:</b> oqdan qora ranggacha.\n" \
"<b>Xavfsizlik ko’rsatkichlari:</b> toksik bo’lmagan\n" \
"<b>Anaeroblar</b> – yo’q\n" \
"<b>Salmonella</b> – yo’q\n" \
"<b>Escherichia coli</b> - yo’q\n" \
"<b>Proteus</b> – yo’q\n" \
"<b>Qadoq:</b> … ml idishlar\n\n" \
"<b>Saqlash shartlari:</b> Voyaga yetgan va undan avvaligi prepupani 4 haftagacha 8-120C haroratda saqlang.\n\n" \
"Yosh lichinkalarni 2 oygacha 10-250C haroratda saqlang"
bot.send_photo(message.chat.id, p, info, parse_mode='html')
elif get_message_bot == "proteinli konsentrat «germecia»":
p = open("images/pk.jpg", 'rb')
info = "<b>Proteinli konsentrat «Germecia»</b>\n\n" \
"<b>Tavsif:</b> Qora lvinka qurtlari (Hermetia illucens) quritilgan yog’sizlangan va maydalangan biomassasi. Quritish infraqizil qurilmalarda barcha biologik faol xususiyatlarni saqlab qolish bilan amalga oshiriladi.\n\n"\
"<b>Tarkibi:</b> Antioksidant bo’lgan qora sher lichinkalarining kam yog’li biomassasi.\n\n" \
"<b>Ilova:</b> Makro va mikroelementlar manbai, tuproqni yaxshilagich sifatida ishlatiladi. Foydasi kam tuproqlarni foydali mikroflora bilan boyitadi.\n\n" \
"<b>Jismoniy xususiyatlari:</b>\n\n" \
"<b>Hidi:</b> kuchli emas, oʻtkir emas, chirigan hid kelmaydi\n" \
"<b>Rang:</b> kulrangdan jigarranggacha.\n" \
"<b>Shakli:</b> qumsimon va granular\n" \
"<b>Xavfsizlik ko’rsatkichlari:</b> Toksik bo’lmagan\n" \
"<b>Anaeroblar</b> – yo’q\n" \
"<b>Salmonella</b> – yo’q\n" \
"<b>Escherichia coli</b> – yo’q\n" \
"<b>Proteus</b> – yo’q\n" \
"<b>Qadoq:</b> 10-40 kg lik qoplarda\n\n" \
"<b>Saqlash muddati:</b> 12 oy"
bot.send_photo(message.chat.id, p, info, parse_mode='html')
elif get_message_bot == "organik o'g'it «germecia» biohumus":
p = open("images/oo.png", 'rb')
info = "<b>Organik o'g'it «Germecia» Biohumus:</b>\n\n" \
"<b>Tavsif:</b> Qora lvinka (Hermetia illusens) lichinkasining quritilgan, yogʻsizlantirilgan va maydalangan biomassasi. Quritish barcha biologik xususiyatlarni saqlab qilgan holda infro qizil qurilmalarda amalga oshiriladi.\n\n" \
"<b>Tarkibi:</b> Qora lvinka lichinkalarining yogʻsizlantirilgan biomassasi, antioksidant.\n\n" \
"<b>Qo’llash:</b> Qishloq xoʻjaligi hayvonlari, parrandalar, suv hayvonlarini va uy hayvonlari uchun moʻljallangan ozuqada oqsil, yogʻ va biologik faol moddalar manbai sifatida qoʻllaniladi.\n\n" \
"<b>Jismoniy xususiyatlari:</b>\n\n" \
"<b>Hidi:</b> o’ziga xos, yoqimli.\n" \
"<b>Rang:</b> kulrangdan jigarranggacha.\n" \
"<b>Xavfsizlik ko’rsatkichlari:</b> Toksik emas – yo’q mavjud emas\n" \
"<b>Anaeroblar</b> – yo’q\n" \
"<b>Salmonella</b> – yo’q\n" \
"<b>Escherichia coli</b> – yo’q\n" \
"<b>Proteus</b> – yo’q\n" \
"<b>Qadoq:</b> 10-40 kg lik qoplarda\n\n" \
"<b>Saqlash muddati:</b> 12 oy"
bot.send_photo(message.chat.id, p, info, parse_mode='html')
elif get_message_bot == "yog'li «germecia»":
p = open("images/yh.jpg", 'rb')
info = "<b>Yog'li «Hermecia»:</b>\n\n" \
"<b>Tavsif:</b> Qora lichinka yog’i lichinka biomassasidan yog ‘bosish va ajratish yo’li bilan olinadi.\n\n" \
"<b>Tarkibi:</b> Qora lichinka lichinkalaridan 100% yog ‘mavjud\n\n" \
"<b>Ilova:</b> Bu ozuqa ishlab chiqarish, sovun tayyorlash, kosmetologiya va farmatsevtika sohasida foydalanish uchun tavsiya etiladi.\n\n" \
"<b>Jismoniy xususiyatlari:</b>\n\n" \
"<b>Erish nuqtasi:</b> 400S\n" \
"<b>Hidi:</b> o’ziga xos, qattiq emas, chirigan emas, yumshoq\n" \
"<b>Rang:</b> oqdan jigarranggacha.\n" \
"<b>Xavfsizlik ko’rsatkichlari:</b> Toksik bo’lmagan\n" \
"<b>Anaeroblar</b> – yo’q\n" \
"<b>Salmonella</b> – yo’q\n" \
"<b>Escherichia coli</b> – yo’q\n" \
"<b>Proteus</b> – yo’q\n" \
"<b>Qadoq:</b> litr bochkalari\n\n" \
"<b>Saqlash muddati:</b>12 oy"
bot.send_photo(message.chat.id, p, info, parse_mode='html')
elif get_message_bot == "buyurtma berish 📌":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi.')
btn2 = types.KeyboardButton('Quritilgan lichinka.')
btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia».')
btn4 = types.KeyboardButton("Organik o'g'it «Germecia» Biohumus.")
btn5 = types.KeyboardButton("Yog'li «Germecia».")
btn6 = types.KeyboardButton('Bekor qilish ❌')
markup.add(btn1, btn2, btn3, btn4, btn5, btn6)
messa = "Marxamat mahsulotni tanlang"
bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=markup)
elif get_message_bot == "bekor qilish ❌":
msg = "Bekor qilindi"
bot.send_message(message.chat.id, msg, reply_markup=mainkeyboard )
elif get_message_bot == "qora lvinkaning tirik lichinkasi.":
messa = "Buyurtma hajmini tanlang"
bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)
order['product'] = message.text
elif get_message_bot == "quritilgan lichinka.":
messa = "Buyurtma hajmini tanlang"
bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)
order['product'] = message.text
elif get_message_bot == "proteinli konsentrat «germecia».":
messa = "Buyurtma hajmini tanlang"
bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)
order['product'] = message.text
elif get_message_bot == "organik o'g'it «germecia» biohumus.":
messa = "Buyurtma hajmini tanlang"
bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)
order['product'] = message.text
elif get_message_bot == "yog'li «germecia».":
messa = "Buyurtma hajmini tanlang"
bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=keyboard)
order['product'] = message.text
elif get_message_bot == "1kg":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Tasdiqlash")
btn2 = types.KeyboardButton("Bekor qilish ❌")
markup.add(btn1, btn2)
order['weight'] = message.text
messag= """<b>Siznining buyurmangiz</b>📎\n\n<b>Mahsulot:</b> {}\n\n<b>Hajmi</b>: {}""".format(order['product'], order['weight'])
bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)
elif get_message_bot == "5kg":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Tasdiqlash")
btn2 = types.KeyboardButton("Bekor qilish ❌")
markup.add(btn1, btn2)
order['weight'] = message.text
messag = """<b>Siznining buyurmangiz</b>📎\n\n<b>Mahsulot:</b> {}\n\n<b>Hajmi</b>: {}""".format(
order['product'], order['weight'])
bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)
elif get_message_bot == "10kg":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Tasdiqlash")
btn2 = types.KeyboardButton("Bekor qilish ❌")
markup.add(btn1, btn2)
order['weight'] = message.text
messag= """<b>Siznining buyurmangiz</b>📎\n\n<b>Mahsulot:</b> {}\n\n<b>Hajmi</b>: {}""".format(order['product'], order['weight'])
bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)
elif get_message_bot == "20kg":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Tasdiqlash")
btn2 = types.KeyboardButton("Bekor qilish ❌")
markup.add(btn1, btn2)
order['weight'] = message.text
messag= """<b>Siznining buyurmangiz</b>📎\n\n<b>Mahsulot:</b> {}\n\n<b>Hajmi</b>: {}""".format(order['product'], order['weight'])
bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)
elif get_message_bot == "50kg":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Tasdiqlash")
btn2 = types.KeyboardButton("Bekor qilish ❌")
markup.add(btn1, btn2)
order['weight'] = message.text
messag = """<b>Siznining buyurmangiz</b>📎\n\n<b>Mahsulot:</b> {}\n\n<b>Hajmi</b>: {}""".format(
order['product'], order['weight'])
bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)
elif get_message_bot == "boshqasi":
mess = bot.send_message(message.chat.id, "Kerakli bo'lgan hajimni kiriting")
bot.register_next_step_handler(mess, get_custom_weight)
elif get_message_bot == "tasdiqlash":
mes = "Yana buyurtma berasizmi?"
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Ha, albatta")
btn2 = types.KeyboardButton("Bekor qilish ❌")
markup.add(btn1,btn2)
buyurtma= """<b>Buyurtma</b>📎\n\n<b>Buyurtmachi:</b> {}\n<b>Telefon raqami:</b> {}\n<b>Mahsulot:</b> {}\n<b>Hajmi</b>: {}""".format(message.from_user.first_name, data['contact'], order['product'], order['weight'])
bot.send_message(message.chat.id, mes, reply_markup=markup)
bot.send_message(-452474686, buyurtma, parse_mode='html')
bot.state = None
elif get_message_bot == "ha, albatta":
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton('Qora lvinkaning tirik lichinkasi.')
btn2 = types.KeyboardButton('Quritilgan lichinka.')
btn3 = types.KeyboardButton('Proteinli konsentrat «Germecia».')
btn4 = types.KeyboardButton("Organik o'g'it «Germecia» Biohumus.")
btn5 = types.KeyboardButton("Yog'li «Germecia».")
btn6 = types.KeyboardButton('Bekor qilish ❌')
markup.add(btn1, btn2, btn3, btn4, btn5, btn6)
messa = "<NAME>i tanlang"
bot.send_message(message.chat.id, messa, parse_mode='html', reply_markup=markup)
else:
fiinal_message = f"Noaniq so'rov, {message.from_user.first_name} iltimos kerakli yonalishni tanlang"
bot.send_message(message.chat.id, fiinal_message, parse_mode='html', reply_markup=mainkeyboard)
def get_custom_weight(message):
age = message.text
if not age.isdigit():
msg = bot.reply_to(message, 'Iltimos kerakli hajimni faqat son shaklida kiriting')
bot.register_next_step_handler(msg, get_custom_weight)
else:
order['weight'] = message.text
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
btn1 = types.KeyboardButton("Tasdiqlash")
btn2 = types.KeyboardButton("Bekor qilish ❌")
markup.add(btn1, btn2)
messag = """<b>Siznining buyurmangiz</b>📎\n\n<b>Mahsulot:</b> {}\n\n<b>Hajmi</b>: {} kg""".format(
order['product'], order['weight'])
bot.send_message(message.chat.id, messag, parse_mode='html', reply_markup=markup)
bot.polling(none_stop=True)
#
| 4d07784ac5fb33d5056a988835cb4a48377e3377 | [
"Python",
"Text"
] | 2 | Text | AzamatSharipov/vitae-bot | 4b5102d8efb031a92906cb36ffb6c6c72245c5f6 | c2125dca814cab06c84bc8c72cb040fac331d205 |
refs/heads/master | <repo_name>sharonrussell/fizzbuzz-ruby<file_sep>/spec/fizzbuzz_spec.rb
require 'spec_helper'
describe FizzBuzz do
before :each do
@fizzbuzz = FizzBuzz.new
end
it "returns fizz when number is divisible 3" do
expect(@fizzbuzz.get(3)).to eq("Fizz")
end
it "returns buzz when number is divisible 5" do
expect(@fizzbuzz.get(5)).to eq("Buzz")
end
it "returns fizzbuzz when number is both divisible by 5 and 3" do
expect(@fizzbuzz.get(15)).to eq("FizzBuzz")
end
it "returns the number when number is not divisible by 5 or 3" do
expect(@fizzbuzz.get(1)).to eq(1)
end
it "returns 0 when the number is 0" do
expect(@fizzbuzz.get(0)).to eq(0)
end
end
<file_sep>/app.rb
require_relative 'fizzbuzz'
fizzbuzz = FizzBuzz.new
for i in 1..100
puts fizzbuzz.get(i)
end
<file_sep>/fizzbuzz.rb
class FizzBuzz
def get(number)
return number if number == 0
return "FizzBuzz" if number % 15 == 0
return "Fizz" if number % 3 == 0
return "Buzz" if number % 5 == 0
number
end
end
| 5c943facf9451790fee96ce3cccd6166d8317045 | [
"Ruby"
] | 3 | Ruby | sharonrussell/fizzbuzz-ruby | 0e5a17fdaa583ed162d0088cb6a7c5f03bfe45cc | 1acf98c9581e15b7e7b9708c8ccff6ec873be00d |
refs/heads/master | <repo_name>Sidimoctar/programming-courses-e8wz5h<file_sep>/index.ts
//######################################################################
//########################### SSTech ###################
//########################### Programming Courses ###################
//######################################################################
console.log('bonjour tout le monde');
let us: number;
let we: number;
us = 144;
we = 22;
console.log(us * we);
let pp: number;
let pp2: number;
pp = 22;
pp2 = 33;
console.log(pp + pp2);
let pp3: number;
pp3 = 55;
let pp4: number;
pp4 = 44;
let pp5: number;
pp5 = 66;
console.log(pp4 + pp5);
let pp6: number;
pp6 = 110;
let pp7: number;
pp7 = 77;
let pp8: number;
pp8 = 88;
console.log(pp7 + pp8);
let pp00: number;
pp00 = 165;
console.log(pp6 + pp00);
let pp60: number;
let fifa: number;
fifa = 11;
let fifa11: number;
fifa11 = 12;
console.log(fifa * fifa11);
| 77c773a3e9d7309d3f7080b3ec39c1a91477d5f3 | [
"TypeScript"
] | 1 | TypeScript | Sidimoctar/programming-courses-e8wz5h | 8a3cc7e08535deb7f984c7de54f8654d0dd09035 | b24daedbb169adc27ecccf4dcc508fc6445f4b2f |
refs/heads/main | <file_sep>import sys
import os
import random
import pygame as pg
from moviepy.editor import *
from pygame.locals import *
sys.path.append(os.path.join("/home", "pi", "Desktop", "ChimpPygames", "PygameTools"))
import PgTools
# initialize pygame and screen
pg.init()
screen = PgTools.Screen()
file = open("Social_Stimuli_As_Rewards/parameters.dat")
params = PgTools.get_params(file)
file.close()
subjectName = str(params["subject_name"])
trialsAmt = int(params["number_of_trials"]) + 1
stimRadius = int(params["stimulus_radius"])
stimTime = int(params["stimulus_duration"])
def start_trial(radius):
"""
Initiates a new trial, draws stimulus
:param radius: radius of stimulus
"""
screen.refresh()
global stimulus
stimulus = pg.draw.circle(
screen.fg,
PgTools.GREEN,
(
int(PgTools.SCREEN_SIZE[0] / 2),
int(PgTools.SCREEN_SIZE[1] / 2),
),
radius,
)
PgTools.write_ln(
filename="Social_Stimuli_As_Rewards/results.csv",
data=["subject_name", "trial", "stimulus_size", "image", "image_duration",],
)
path = os.path.join("/home", "pi", "Desktop", "ChimpPygames", "Social_Stimuli_As_Rewards", "Social_Stimuli",)
file = random.choice(os.listdir(path))
if(file.endswith((".mp4", ".mov"))):
video = VideoFileClip(os.path.join(path, file))
else:
image = pg.image.load(os.path.join(path, file))
# lags video a lot
# video = video.margin(top=int((PgTools.SCREEN_SIZE[1]-video.h)/2), bottom=int((PgTools.SCREEN_SIZE[1]-video.h)/2), left=int((PgTools.SCREEN_SIZE[0]-video.w)/2), right=int((PgTools.SCREEN_SIZE[0]-video.w)/2))
trialNum = 1
start_trial(stimRadius)
# game loop
running = True
while running:
for event in pg.event.get():
PgTools.quit_pg(event)
if event.type == MOUSEBUTTONDOWN:
xCoord, yCoord = event.pos
if stimulus.collidepoint(xCoord, yCoord):
screen.refresh()
if(file.endswith((".mp4", ".mov"))):
video = VideoFileClip(os.path.join(path, file))
# if fullscreen doesnt work for some reason
# marginH = int(PgTools.SCREEN_SIZE[1] / 2 - video.h / 2)
# marginW = int(PgTools.SCREEN_SIZE[0] / 2 - video.w / 2)
# video = video.margin(top=marginH, bottom=marginH, left=marginW, right=marginW)
video.preview(fullscreen=True)
screen = PgTools.Screen()
else:
image = pg.image.load(os.path.join(path, file))
screen.fg.blit(image, (int((PgTools.SCREEN_SIZE[0] - image.get_width()) / 2), int((PgTools.SCREEN_SIZE[1] - image.get_height()) / 2)))
pg.display.update()
pg.time.delay(stimTime)
file = random.choice(os.listdir(path))
pg.event.clear()
PgTools.write_ln(
filename="Social_Stimuli_As_Rewards/results.csv",
data=[
subjectName,
trialNum,
int(stimRadius),
"foo",
stimTime,
],
)
else:
pg.event.clear()
continue
trialNum += 1
if trialNum == trialsAmt:
PgTools.end_screen(screen)
while True:
for event in pg.event.get():
PgTools.quit_pg(event)
start_trial(stimRadius)
pg.display.update()
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Oddity_Testing/python_scripts/OddityTesting.py
sleep 5
<file_sep>import subprocess
import sys
import os
sys.path.append(os.path.join("home", "pi", "Desktop", "ChimpPygames"))
"""
Basic work in progress command line UI
"""
class pcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
cmd_dict = {
"tt1": "TrainingTaskP1.sh",
"tt2": "TrainingTaskP2.sh",
"tcd": "TwoChoiceDiscrim.sh",
"mts": "MatchToSample.sh",
"dmts": "DelayedMatchToSample.sh",
"ot": "OddityTesting.sh",
"drt": "DelayedResponseTask.sh",
"ssar": "SocialStimuli.sh",
}
wd_dict = {
"tt1": "Training_Task",
"tt2": "Training_Task",
"tcd": "Two_Choice_Discrimination",
"mts": "Match_To_Sample",
"dmts": "Delayed_Match_To_Sample",
"ot": "Oddity_Testing",
"drt": "Delayed_Response_Task",
"ssar": "Social_Stimuli_As_Rewards",
}
def main():
"""
Main frontend program. Allows user to run all expirements and clear csv files.
"""
print(pcolors.HEADER + "Please choose an expirement to run by entering the corresponding abreviation or q to exit program:" + pcolors.ENDC)
while True:
print("\ntt1 : Training_Task_1")
print("tt2 : Training_Task_2")
print("tcd : Two_Choice_Discimination")
print("mts : Match_To_Sample")
print("dmts : Delayed_Match_To_Sample")
print("ot : Oddity_Testing")
print("drt : Delayed_Response_Task")
print("ssar : Social_Stimuli_As_Rewards")
print("ecsv : Empties ALL results.csv files")
print("q : Exits Program\n")
usrInput = input(pcolors.OKCYAN + "Enter command: " + pcolors.ENDC)
if usrInput == "q":
print(pcolors.WARNING + "Exiting program...")
exit()
elif usrInput == "ecsv":
msgStr = "ALL results.csv files within ChimpPygames will cleared and any data not stored outside will be lost!"
if ynPrompt(msgStr, True):
print(pcolors.OKGREEN + "Clearing all results.csv files..." + pcolors.ENDC)
empty_csv()
print(pcolors.OKBLUE + "Files cleared." + pcolors.ENDC)
else:
print(pcolors.OKBLUE + "Exited prompt." + pcolors.ENDC)
continue
elif not usrInput in cmd_dict:
print(pcolors.FAIL + "Command invalid: Please enter a valid command." + pcolors.ENDC)
else:
if ynPrompt("Please make sure all of the parameters in parameters.txt in the "
+ wd_dict.get(usrInput) + " folder are set correctly before continuing!"):
print(pcolors.OKGREEN + "Starting " + wd_dict.get(usrInput) + pcolors.ENDC)
subprocess.call(['sh', cmd_dict.get(usrInput)], cwd = wd_dict.get(usrInput))
print(pcolors.OKBLUE + "Results Recorded. Exited " + wd_dict.get(usrInput) + pcolors.ENDC)
else:
print(pcolors.OKBLUE + "Exited prompt." + pcolors.ENDC)
continue
def ynPrompt(message="", warning=False):
"""
Prompts the user with a yes or no question to continue with a message
:param message: message displayed to user
:param warning: puts warning labels around message if True and not if False
"""
if warning:
print(pcolors.WARNING + "### WARNING ###")
print(message)
print("### WARNING ###" + pcolors.ENDC)
else:
print(pcolors.WARNING + message + pcolors.ENDC)
promptInput = input(pcolors.OKCYAN + "Do you want to continue? (enter y to continue or anything else to exit): " + pcolors.ENDC)
if(promptInput == 'y'):
return True
else:
return False
def empty_csv():
"""
empties all csv files in ChimpPygames
"""
fname = "results.csv"
for cmd in wd_dict:
os.chdir(wd_dict.get(cmd))
print(os.getcwd())
f = open(fname, "w+")
f.close()
os.chdir('../')
os.chdir(wd_dict.get("tt1"))
f = open("resultsP1.csv", "w+")
f.close()
f = open("resultsP2.csv", "+w")
f.close()
os.chdir('../')
main()
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Match_To_Sample/python_scripts/MatchToSample.py
sleep 5<file_sep>import sys
import os
import pygame as pg
from pygame.locals import *
sys.path.append(os.path.join("/home", "pi", "Desktop", "ChimpPygames", "PygameTools"))
import PgTools
import random
import time
import glob
# initialize pygame and screen
pg.init()
screen = PgTools.Screen()
# init font for trial counter
font = pg.font.SysFont(None, 48)
file = open("Training_Task/parametersP2.dat")
params = PgTools.get_params(file)
file.close()
subjectName = str(params["subject_name"])
trialsAmt = int(params["number_of_trials"])
stimLength = int(params["stimulus_length"])
stimHeight = int(params["stimulus_height"])
passDelay = int(params["passed_inter_trial_interval"])
failDelay = int(params["failed_inter_trial_interval"])
if "y" in str(params["randomly_shaped_stimuli"]) or "Y" in str(params["randomly_shaped_stimuli"]):
randShapes = True
else:
randShapes = False
def start_trial(length, height):
"""
Initiates a new trial, draws stimulus
:param length: length of new stimulus
:param height: width of new stimulus
"""
screen.refresh()
global stimulus
xCoord = PgTools.rand_x_coord(stimLength)
yCoord = PgTools.rand_y_coord(stimHeight)
s = pg.Surface((length, height))
s.blit(images[random.randint(0, len(images)-1)], (0, 0))
# s.blit(test_image, (0, 0)) # use to debug clipart
screen.fg.blit(s, (xCoord, yCoord))
stimulus = pg.draw.rect(screen.fg, Color('goldenrod'),(xCoord, yCoord, length, height), 15)
# randInt = random.choice([0, 1, 2, 3, 4])
# if randShapes:
# PgTools.rand_shape(screen.fg, (xCoord, yCoord), (length, height), randInt)
PgTools.write_ln(
filename="Training_Task/resultsP2.csv",
data=["subject_name", "trial", "input_coordinates", "accuracy",],
)
trialNum = 1
passedTrials = 0
# randInt = random.randint(0, 99999) # seed
# load all our images
images = []
list_of_stimuli = glob.glob("/home/pi/Desktop/ChimpPygames/Images/samples/*.jpg")
for filepath in list_of_stimuli:
images.append(pg.transform.scale(pg.image.load(filepath), (stimLength, stimHeight)))
# test_image = pg.transform.scale(pg.image.load("/home/pi/Desktop/ChimpPygames/Images/samples/80.jpg"), (stimLength, stimHeight))
start_trial(stimLength, stimHeight)
# game loop
running = True
# params for deliberate touch
touched_down = False # tells us whether the animal has already touched
when_they_started_their_touch = 0
min_touch_ms_required = 150
max_touch_ms = 3000
while running:
# disply trial number in upper left corner
# text = font.render('Trial #{}'.format(trialNum), True, Color('salmon'))
# screen.fg.blit(text, (20, 20))
for event in pg.event.get():
PgTools.quit_pg(event)
if event.type == MOUSEBUTTONDOWN:
xCoord, yCoord = event.pos
when_they_started_their_touch = pg.time.get_ticks()
touched_down = True
elif (event.type == MOUSEBUTTONUP):
touched_down = False
if (pg.time.get_ticks()-when_they_started_their_touch<min_touch_ms_required) and \
(pg.time.get_ticks()-when_they_started_their_touch>max_touch_ms):
continue
elif (pg.time.get_ticks()-when_they_started_their_touch>min_touch_ms_required) and \
(pg.time.get_ticks()-when_they_started_their_touch<max_touch_ms):
if stimulus.collidepoint(xCoord, yCoord):# and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
PgTools.response(screen, True, passDelay)
PgTools.write_ln(
filename="Training_Task/resultsP2.csv",
data=[subjectName, trialNum, ("\"" + str(xCoord) + ", " + str(yCoord) + "\""), "passed",],
)
passedTrials += 1
else:
PgTools.response(screen, False, failDelay)
PgTools.write_ln(
filename="Training_Task/resultsP2.csv",
data=[subjectName, trialNum, ("\"" + str(xCoord) + ", " + str(yCoord) + "\""), "failed",],
)
trialNum += 1
if passedTrials == trialsAmt:
PgTools.end_screen(screen)
while True:
for event in pg.event.get():
PgTools.quit_pg(event)
start_trial(stimLength, stimHeight)
pg.display.update()
<file_sep>import sys
import os
import random
from random import randint
import pygame as pg
from pygame.locals import *
sys.path.append(os.path.join("/home", "pi", "Desktop", "ChimpPygames", "PygameTools"))
import PgTools
# initialize pygame and screen
pg.init()
screen = PgTools.Screen()
file = open("Match_To_Sample/parameters.dat")
params = PgTools.get_params(file)
file.close()
# gathers parameters data
subjectName = str(params["subject_name"])
posStimName = str(params["sample/positive_stimulus_name"])
negStimName = str(params["negative_stimulus_name"])
trialsAmt = int(params["number_of_trials"]) + 1
stimAmt = int(params["number_of_comparison_stimuli"])
stimLength = int(params["stimulus_length"])
stimHeight = int(params["stimulus_height"])
passDelay = int(params["passed_inter_trial_interval"])
failDelay = int(params["failed_inter_trial_interval"])
if("y" in str(params["sample_stimulus_visible"]) or "Y" in str(params["sample_stimulus_visible"])):
sampleStimVis = True
else:
sampleStimVis = False
if "y" in str(params["randomly_shaped_stimuli"]) or "Y" in str(params["randomly_shaped_stimuli"]):
randShapes = True
else:
randShapes = False
posLocation = randint(0, stimAmt - 1)
def trial_P1(length, height):
"""
Initiates part 1 of a new trial, draws sample stimulus
:param length: length of stimuli
:param height: height of stimuli
"""
screen.refresh()
global trialStart
global sampleStim
trialStart = True
sampleStim = pg.draw.rect(
screen.fg,
posColor,
(
int((PgTools.SCREEN_SIZE[0] - length) / 2),
int((PgTools.SCREEN_SIZE[1] - height) / 5),
length,
height,
),
)
PgTools.rand_pattern(
screen.fg,
(
int((PgTools.SCREEN_SIZE[0] - length) * 0.5),
int((PgTools.SCREEN_SIZE[1] - height) * 0.2),
),
(length, height),
patColor,
randNums,
)
if randShapes:
PgTools.rand_shape(screen.fg, ((PgTools.SCREEN_SIZE[0] - length)/2,
(PgTools.SCREEN_SIZE[1] - height) / 5), (stimLength, stimHeight), seed)
def trial_P2(posColor):
"""
Initiates part 2 of a trial, draws comparison stimuli
:param colorPair: pair of random colors for stimuli base colors
"""
if not sampleStimVis:
screen.refresh()
global stimList
currentLength = int(maxLength / 4)
currentHeight = int(maxHeight * 0.4)
for i in range(stimAmt):
if i == posLocation:
stimList.append(
pg.draw.rect(
screen.fg,
posColor,
(currentLength, currentHeight, stimLength, stimHeight,),
)
)
PgTools.rand_pattern(
screen.fg, (currentLength, currentHeight), (stimLength, stimHeight), patColor, randNums,
)
if randShapes:
PgTools.rand_shape(screen.fg, (currentLength, currentHeight),(stimLength, stimHeight), seed)
else:
stimList.append(
pg.draw.rect(
screen.fg,
PgTools.rand_color(),
(currentLength, currentHeight, stimLength, stimHeight,),
)
)
PgTools.rand_pattern(
screen.fg, (currentLength, currentHeight), (stimLength, stimHeight), PgTools.rand_color(), (randint(0,2), randint(0,2))
)
if randShapes:
PgTools.rand_shape(screen.fg, (currentLength, currentHeight),(stimLength, stimHeight), randint(0, 99999))
currentLength += maxLength / 2
currentLength = int(currentLength)
if i == 1:
currentLength = int(maxLength / 4)
currentHeight= int(maxHeight * 0.8)
def check_stim(xCoord, yCoord):
for i in range(stimAmt):
if i != posLocation and stimList[i].collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
return True
PgTools.write_ln(
filename="Match_To_Sample/results.csv",
data=[
"subject_name",
"trial",
"comparison_stimuli",
"accuracy",
],
)
maxLength = PgTools.SCREEN_SIZE[0] - stimLength
maxHeight = PgTools.SCREEN_SIZE[1] - stimHeight
trialNum = 1
posColor = PgTools.rand_color()
patColor = PgTools.rand_color()
randNums = [randint(0, 2), randint(0, 1)]
stimList = []
seed = random.randint(0, 99999)
trial_P1(stimLength, stimHeight)
# game loop
running = True
while running:
for event in pg.event.get():
PgTools.quit_pg(event)
if event.type == MOUSEBUTTONDOWN:
xCoord, yCoord = event.pos
if trialStart:
if sampleStim.collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
trial_P2(posColor)
trialStart = False
continue
else:
if stimList[posLocation].collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
PgTools.response(screen, True, passDelay)
PgTools.write_ln(
filename="Match_To_Sample/results.csv",
data=[
subjectName,
trialNum,
stimAmt,
"passed",
],
)
elif check_stim(xCoord, yCoord):
PgTools.response(screen, False, failDelay)
PgTools.write_ln(
filename="Match_To_Sample/results.csv",
data=[
subjectName,
trialNum,
stimAmt,
"failed",
],
)
else:
pg.event.clear()
continue
trialNum += 1
if trialNum == trialsAmt:
PgTools.end_screen(screen)
while True:
for event in pg.event.get():
PgTools.quit_pg(event)
posColor = PgTools.rand_color()
patColor = PgTools.rand_color()
randNums = [randint(0, 2), randint(0, 1)]
seed = random.randint(0, 99999)
trial_P1(stimLength, stimHeight)
posLocation = randint(0, stimAmt - 1)
pg.display.update()
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Social_Stimuli_As_Rewards/python_scripts/SocialStimuli.py
sleep 5
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python3 Front_End/front_end.py
sleep 3
<file_sep>"""
Provides other programs with useful functions and elements
"""
import os
import random
import pygame as pg
from pygame.locals import *
from datetime import datetime
import colorsys
import numpy as np
# Reads globalParameters.dat
# file = open("PygameTools/globalParameters.dat")
file = open('/home/pi/Desktop/ChimpPygames/PygameTools/globalParameters.dat')
params = {}
for line in file:
line = line.strip()
key_value = line.split("=")
if len(key_value) == 2:
params[key_value[0].strip()] = key_value[1].strip()
file.close()
# Constants
SCREEN_SIZE = (int(params["screen_width"]), int(params["screen_height"])) # (length/width, height) of Elo Touchscreen in px
BLACK = (0, 0, 0)
GREEN = (0, 128, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
AQUA = (0, 255, 255)
YELLOW = (255, 255, 0)
CURSOR_VISIBLE = True
if("y" in str(params["cursor_hidden"]) or "Y" in str(params["cursor_hidden"])):
CURSOR_VISIBLE = False
# Screen Tools
class Screen(object):
def __init__(self, size=SCREEN_SIZE, col=BLACK, fullscreen=True):
"""
Pygame screen on which to draw stimuli, etc.
:param size: screen resolution in pixels
:param col: screen bg color
:param fullscreen: fullscreen if True, not fullscreen if False
"""
self.rect = pg.Rect((0, 0), size)
self.bg = pg.Surface(size) # static objects go in background (bg)
self.bg.fill(col)
if fullscreen:
self.fg = pg.display.set_mode(
size, (NOFRAME and FULLSCREEN)
) # dynamic objects go in foreground (fg)
else:
self.fg = pg.display.set_mode(size)
def refresh(self):
"""
Blit background to screen and update display.
"""
self.fg.blit(self.bg, (0, 0))
pg.display.update()
self.fg.blit(self.bg, (0, 0))
# Game Tools
def get_params(fileObj):
"""
reads all parameter variables in opened file 'fileObj'
:return: parameter's values in a dictionary
"""
if not CURSOR_VISIBLE: # sets mouse to invisible
pg.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))
params = {}
for line in fileObj:
line = line.strip()
key_value = line.split("=")
if len(key_value) == 2:
params[key_value[0].strip()] = key_value[1].strip()
return params
def quit_pg(event):
"""
Quit pygame on QUIT, [Esc], and [Q].
"""
if event.type == QUIT or (event.type == KEYDOWN and (event.key in (K_ESCAPE, K_q))):
pg.quit()
raise SystemExit
def response(screen, accuracy=None, delay=5000):
"""
Game's response to inputs
:param screen: surface to draw response
:param accuracy: calls pellet() and sound(correct=True) if True, sound(correct=False) if False
"""
if accuracy:
screen.bg.fill(YELLOW)
sound(correct=True)
screen.refresh()
pg.time.delay(1000)
screen.bg.fill(BLACK)
screen.refresh()
pellet()
elif not accuracy:
screen.bg.fill(RED)
sound(correct=False)
screen.refresh()
pg.time.delay(1000)
screen.bg.fill(BLACK)
screen.refresh()
pg.event.get()
pg.time.delay(delay-1000)
pg.event.clear()
def rand_x_coord(length):
"""
:param length: length of stimulus
:return: random x coordinate that fits the stimulus inside the screen
"""
return random.randint(0, (SCREEN_SIZE[0] - length))
def rand_y_coord(height):
"""
:param height: height of stimulus
:return: random y coordinate that fits the stimulus inside the screen
"""
return random.randint(0, (SCREEN_SIZE[1] - height))
def rand_color(bright=True):
"""
:param bright: returns only colors that work well on a black background if true
:return: random rgb color value (x,y,z)
"""
if bright:
h,s,l = random.random(), 0.5 + random.random()/2.0, 0.4 + random.random()/5.0
return tuple([int(256*i) for i in colorsys.hls_to_rgb(h,l,s)])
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
def two_rand_color(bright=True):
"""
:param bright: returns only colors that work well on a black background if true
:return: two random rgb color values
"""
colA = ()
colB = ()
if bright:
h,s,l = random.random(), 0.5 + random.random()/2.0, 0.4 + random.random()/5.0
colA = tuple([int(256*i) for i in colorsys.hls_to_rgb(h,l,s)])
h,s,l = random.random(), 0.5 + random.random()/2.0, 0.4 + random.random()/5.0
colB = tuple([int(256*i) for i in colorsys.hls_to_rgb(h,l,s)])
return colA, colB
colA = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
colB = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
return colA, colB
def rand_line_point(seed=random.randint(0, 999999), pointA=(0, 0), pointB=(0, 0)):
"""
Finds a random point between two points on a line.
:param seed: random seed to be used
:param pointA: first and lesser point being measured
:param pointB: Second and greater point being measured
:return: (x coordinate, y coordinate)
"""
xCoord = pointA[0]
yCoord = pointA[1]
if int(pointA[0]) != int(pointB[0]):
xCoord = np.random.randint(int(pointA[0]), int(pointB[0]))
if int(pointA[1]) != int(pointB[1]):
yCoord = np.random.randint(int(pointA[1]), int(pointB[1]))
return (xCoord, yCoord)
def rand_shape(screen, coords=(0, 0), size=(0, 0), seed=random.randint(0, 999999),):
"""
Draws random black shapes on a rectangular surface to alter the shape of a
rectangle to be a random shape
:param screen: surface pattern is drawn on
:param coords: (x, y) coordinates of the top-left corner of the pattern square
:param size: (length, height) size of the pattern square
:param seed: random seed of the shapes
"""
np.random.seed(seed)
randInt = np.random.randint(0,4)
if randInt == 0:
return
cornerCoords = [coords, (coords[0] + size[0], coords[1]),
(coords[0], coords[1] + size[1]), (coords[0] + size[0], coords[1] + size[1]),]
midpointCoords = [(int(coords[0] + size[0]/2), coords[1]),(coords[0], int(coords[1] + size[1]/2)),
(cornerCoords[1][0], int(coords[1] + size[1]/2)), (int(coords[0] + size[0]/2), cornerCoords[2][1])]
if randInt == 1: # makes the rectangle a triangle in 1 of 4 directions
i = np.random.randint(0, 4)
if i == 0:
pg.draw.polygon(screen, 0, (cornerCoords[0], cornerCoords[1], cornerCoords[2]))
elif i == 1:
pg.draw.polygon(screen, 0, (cornerCoords[0], cornerCoords[1], cornerCoords[3]))
elif i == 2:
pg.draw.polygon(screen, 0, (cornerCoords[1], cornerCoords[2], cornerCoords[3]))
else:
pg.draw.polygon(screen, 0, (cornerCoords[0], cornerCoords[2], cornerCoords[3]))
elif randInt == 2: # cuts out a square in 1 of 4 corners
i = np.random.randint(0, 4)
if i == 0:
pg.draw.rect(screen, 0, (cornerCoords[0][0], cornerCoords[0][1],
(midpointCoords[0][0] - cornerCoords[0][0]),
(midpointCoords[1][1] - cornerCoords[0][1])))
elif i == 1:
pg.draw.rect(screen, 0, (cornerCoords[2][0], cornerCoords[2][1],
(midpointCoords[3][0] - cornerCoords[2][0]),
(midpointCoords[1][1] - cornerCoords[2][1])))
elif i == 2:
pg.draw.rect(screen, 0, (midpointCoords[0][0], midpointCoords[0][1],
(cornerCoords[1][0] - midpointCoords[0][0]),
(midpointCoords[2][1] - cornerCoords[1][1])))
else:
pg.draw.rect(screen, 0, (midpointCoords[3][0],
midpointCoords[2][1],
(cornerCoords[3][0] - midpointCoords[3][0]),
(cornerCoords[3][1] - midpointCoords[2][1])))
elif randInt == 3: # cuts out randomly sized triangles to make random polygons
randBool = np.random.randint(0, 2, size=4)
if bool(randBool[0]):
pg.draw.polygon(screen, 0, (cornerCoords[0], rand_line_point(seed, cornerCoords[0], midpointCoords[0]),
rand_line_point(seed, cornerCoords[0], midpointCoords[1])))
if bool(randBool[1]):
pg.draw.polygon(screen, 0, (cornerCoords[1], rand_line_point(seed, midpointCoords[0], cornerCoords[1]),
rand_line_point(seed, cornerCoords[1], midpointCoords[2])))
if bool(randBool[2]):
pg.draw.polygon(screen, 0, (cornerCoords[2], rand_line_point(seed, cornerCoords[2], midpointCoords[3]),
rand_line_point(seed, midpointCoords[1], cornerCoords[2])))
if bool(randBool[3]):
pg.draw.polygon(screen, 0, (cornerCoords[3], rand_line_point(seed, midpointCoords[3], cornerCoords[3]),
rand_line_point(seed, midpointCoords[2], cornerCoords[3])))
def rand_pattern(
screen,
coords=(0, 0),
size=(0, 0),
col=rand_color(),
i=(random.randint(0, 2), random.randint(0, 1)),
):
"""
Draws a random pattern in a set area
:param screen: surface pattern is drawn on
:param coords: (x, y) coordinates of the top-left corner of the pattern square
:param size: (length, height) size of the pattern square
:param col: rgb color of pattern
:param i: i[0] determines which pattern is chosen, i[1] determines if it is pattern type A or B
"""
clip = Rect((coords[0], coords[1], size[0], size[1]))
screen.set_clip(clip)
if i[0] == 0:
circle_pat(screen, coords, size, col, i)
elif i[0] == 1:
square_pat(screen, coords, size, col, i)
elif i[0] == 2:
pass
screen.set_clip(None)
def circle_pat(screen, coords, size, col, i):
"""
Draws a circle pattern in a set area
:param screen: surface pattern is drawn on
:param coords: (x, y) coordinates of the top-left corner of the pattern square
:param size: (length, height) size of the pattern square
:param col: rgb color of pattern
:param i: i[1] determines if it is pattern type A or B
"""
xCoord = 0
yCoord = 0
radius = 10
status = True
rowCount = 0
for j in range(size[1] + radius):
if (j - yCoord) == radius:
for k in range(size[0] + radius):
if (k - xCoord) == radius and status:
pg.draw.circle(screen, col, (coords[0] + k, coords[1] + j), radius)
xCoord += radius * 2
status = False
elif (k - xCoord) == radius and not status:
xCoord += radius * 2
status = True
if rowCount % 2 == 0:
status = False
else:
status = True
rowCount += 1
xCoord = 0
yCoord += radius * 2
if i[1] == 0: # determines if pattern is type A or B
status = True
def square_pat(screen, coords, size, col, i):
"""
Draws a square pattern in a set area
:param screen: surface pattern is drawn on
:param coords: (x, y) coordinates of the top-left corner of the pattern square
:param size: (length, height) size of the pattern square
:param col: rgb color of pattern
:param i: i[1] determines if it is pattern type A or B
"""
xCoord = 0
yCoord = 0
sideLength = 20
status = True
rowCount = 0
for j in range(size[1] + sideLength):
if (j - yCoord) == sideLength:
for k in range(size[0] + sideLength):
if (k - xCoord) == sideLength and status:
pg.draw.rect(
screen,
col,
(coords[0] + k - sideLength, coords[1] + j - sideLength,
sideLength, sideLength),
)
xCoord += sideLength
status = False
elif (k - xCoord) == sideLength and not status:
xCoord += sideLength
status = True
if rowCount % 2 == 0:
status = False
else:
status = True
rowCount += 1
xCoord = 0
yCoord += sideLength
if i[1] == 0: # determines if pattern is type A or B
status = True
def pellet(num=1):
"""
Dispense pellets.
:param num: number of pellets to dispense
"""
for i in range(num):
os.system(
"sudo python /home/pi/Desktop/ChimpPygames/PygameTools/PelletFeeder/new-relay.py"
)
print("pellet")
def sound(correct=None):
"""
Pass True to play whoop (correct.wav); pass False to play buzz (incorrect.wav).
:param correct: Play one sound if correct is True and another if correct is False
"""
if correct:
pg.mixer.Sound(os.path.join("reqs", "sounds", "correct.wav")).play()
print("correct sound")
else:
pg.mixer.Sound(os.path.join("reqs", "sounds", "incorrect.wav")).play()
print("not correct sound")
def end_screen(screen):
screen.refresh()
font = pg.font.SysFont("piday", 50)
text = font.render('Trials Completed. Press \'esc\' or \'q\' to end expirement.', True, BLACK, RED)
screen.fg.blit(text, (75, SCREEN_SIZE[1] /2))
pg.display.update()
def write_ln(filename=None, data="", csv=True, date=True):
"""
Write a list to a file as comma- or tab-delimited. Not passing a list
results in a blank line.
:param filename: filepath to datafile
:param data: list of data to be output
:param csv: comma-delimited if True, tab-delimited if False
:param csv: Adds date/time on each line if True, not if False
"""
if(date == True):
data.append(datetime.now().strftime("\"D:%m/%d/%y T:%H:%M:%S\""))
with open(filename, "a+") as data_file:
if csv:
data_file.write(", ".join(map(str, data)) + "\n")
else:
data_file.write("\t".join(map(str, data)) + "\n")
<file_sep>import sys
import os
from random import randint
import pygame as pg
from pygame.locals import *
sys.path.append(os.path.join("/home", "pi", "Desktop", "ChimpPygames", "PygameTools"))
import PgTools
# initialize pygame and screen
pg.init()
screen = PgTools.Screen()
file = open("Oddity_Testing/parameters.dat")
params = PgTools.get_params(file)
file.close()
subjectName = str(params["subject_name"])
sampleStimName = str(params["sample_stimulus_name"])
oddStimName = str(params["odd_stimulus_name"])
trialsAmt = int(params["number_of_trials"]) + 1
stimAmt = int(params["number_of_stimuli"])
stimLength = int(params["stimulus_length"])
stimHeight = int(params["stimulus_height"])
passDelay = int(params["passed_inter_trial_interval"])
failDelay = int(params["failed_inter_trial_interval"])
if "y" in str(params["randomly_shaped_stimuli"]) or "Y" in str(params["randomly_shaped_stimuli"]):
randShapes = True
else:
randShapes = False
def trial(length, height):
"""
Initiates a new trial, draws stimuli
:param length: length of stimuli
:param height: height of stimuli
"""
screen.refresh()
global stimList
global oddLength
global oddHeight
currentLength = int(maxLength / 4)
currentHeight = int(maxHeight / 4)
for i in range(stimAmt):
if i == oddLocation:
oddLength = currentLength
oddHeight = currentHeight
stimList.append(
pg.draw.rect(
screen.fg,
PgTools.rand_color(),
(currentLength, currentHeight, length, height,),
)
)
PgTools.rand_pattern(
screen.fg,
(
currentLength,
currentHeight,
),
(length, height),
i=(randint(0, 2), randint(0, 1)),
)
if randShapes:
PgTools.rand_shape(screen.fg, (currentLength, currentHeight),(length, height), oddSeed)
else:
stimList.append(
pg.draw.rect(
screen.fg,
color,
(currentLength, currentHeight, length, height,),
)
)
PgTools.rand_pattern(
screen.fg,
(
currentLength,
currentHeight,
),
(length, height),
patColor,
randNums,
)
if randShapes:
PgTools.rand_shape(screen.fg, (currentLength, currentHeight),(length, height), regSeed)
currentLength += maxLength / 4
currentLength = int(currentLength)
if (i + 1) % 3 == 0:
currentLength = maxLength / 4
currentLength = int(currentLength)
currentHeight += maxHeight / 4
currentHeight= int(currentHeight)
def check_stim(xCoord, yCoord):
for i in range(stimAmt):
if i != oddLocation and stimList[i].collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
return True
PgTools.write_ln(
filename="Oddity_Testing/results.csv",
data=[
"subject_name",
"trial",
"odd_stim_location",
"accuracy",
],
)
trialNum = 1
colorPair = PgTools.two_rand_color()
patColor = PgTools.rand_color()
randNums = [randint(0, 2), randint(0, 1)]
color = PgTools.rand_color()
patColor = PgTools.rand_color()
oddLocation = randint(0, stimAmt - 1)
stimList = []
maxLength = PgTools.SCREEN_SIZE[0] - stimLength
maxHeight = PgTools.SCREEN_SIZE[1] - stimHeight
oddLength = 0
oddHeight = 0
if randShapes:
regSeed = randint(0, 99999)
oddSeed = randint(0, 99999)
trial(stimLength, stimHeight)
# game loop
running = True
while running:
for event in pg.event.get():
PgTools.quit_pg(event)
if event.type == MOUSEBUTTONDOWN:
xCoord, yCoord = event.pos
if stimList[oddLocation].collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
PgTools.response(screen, True, passDelay)
PgTools.write_ln(
filename="Oddity_Testing/results.csv",
data=[
subjectName,
trialNum,
oddLocation + 1,
"passed",
],
)
elif check_stim(xCoord, yCoord):
PgTools.response(screen, False, failDelay)
PgTools.write_ln(
filename="Oddity_Testing/results.csv",
data=[
subjectName,
trialNum,
oddLocation + 1,
"failed",
],
)
else:
pg.event.clear()
continue
trialNum += 1
if trialNum == trialsAmt:
PgTools.end_screen(screen)
while True:
for event in pg.event.get():
PgTools.quit_pg(event)
colorPair = PgTools.two_rand_color()
patColor = PgTools.rand_color()
randNums = [randint(0, 2), randint(0, 1)]
color = PgTools.rand_color()
patColor = PgTools.rand_color()
oddLocation = randint(0, stimAmt - 1)
if randShapes:
regSeed = randint(0, 99999)
oddSeed = randint(0, 99999)
trial(stimLength, stimHeight)
pg.display.update()
<file_sep>import sys
import os
import pygame as pg
from pygame.locals import *
sys.path.append(os.path.join("/home", "pi", "Desktop", "ChimpPygames", "PygameTools"))
import PgTools
from random import randint
# initialize pygame and screen
pg.init()
screen = PgTools.Screen()
file = open("Two_Choice_Discrimination/parameters.dat")
params = PgTools.get_params(file)
file.close()
subjectName = str(params["subject_name"])
posStimName = str(params["positive_stimulus_name"])
negStimName = str(params["negative_stimulus_name"])
consecutiveAmt = int(params["number_of_correct_in_a_row"])
setsAmt = int(params["number_of_stimulus_pairs"]) + 1
stimLength = int(params["stimulus_length"])
stimHeight = int(params["stimulus_height"])
passDelay = int(params["passed_inter_trial_interval"])
failDelay = int(params["failed_inter_trial_interval"])
if "y" in str(params["randomly_shaped_stimuli"]) or "Y" in str(params["randomly_shaped_stimuli"]):
randShapes = True
else:
randShapes = False
def start_trial(length, height, cols):
"""
Initiates a new trial, draws stimuli
:param length: length of stimuli
:param height: height of stimuli
:param cols: (color1, color2) of stimuli
"""
screen.refresh()
while True:
posX = PgTools.rand_x_coord(length)
posY = PgTools.rand_y_coord(height)
negX = PgTools.rand_x_coord(length)
negY = PgTools.rand_y_coord(height)
global posStim
global negStim
posStim = pg.draw.rect(
screen.fg,
cols[0],
(
posX,
posY,
length,
height,
),
)
negStim = pg.draw.rect(
screen.fg,
cols[1],
(
negX,
negY,
length,
height,
),
)
if posStim.colliderect(negStim):
screen.refresh()
continue
else:
if randShapes:
PgTools.rand_shape(screen.fg, (posX, posY,),(length, height), posSeed)
PgTools.rand_shape(screen.fg, (negX, negY,),(length, height), negSeed)
break
PgTools.write_ln(
filename="Two_Choice_Discrimination/results.csv",
data=[
"subject_name",
"set",
"trial",
"total_trial",
posStimName,
negStimName,
"input_coordinates",
"accuracy",
],
)
trialNum = 1
setNum = 1
passedTrials = 0
colorPair = PgTools.two_rand_color()
color = PgTools.rand_color()
totalTrial = 1
if randShapes:
posSeed = randint(0, 99999)
negSeed = randint(0, 99999)
start_trial(stimLength, stimHeight, colorPair)
# game loop
running = True
while running:
for event in pg.event.get():
PgTools.quit_pg(event)
if event.type == MOUSEBUTTONDOWN:
xCoord, yCoord = event.pos
if posStim.collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
PgTools.response(screen, True, passDelay)
PgTools.write_ln(
filename="Two_Choice_Discrimination/results.csv",
data=[
subjectName,
setNum,
trialNum,
totalTrial,
"\"" + str(colorPair[0]) + "\"",
"\"" + str(colorPair[1]) + "\"",
"\"" + str((xCoord, yCoord)) + "\"",
"passed",
],
)
passedTrials += 1
elif negStim.collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
PgTools.response(screen, False, failDelay)
PgTools.write_ln(
filename="Two_Choice_Discrimination/results.csv",
data=[
subjectName,
setNum,
trialNum,
totalTrial,
"\"" + str(colorPair[0]) + "\"",
"\"" + str(colorPair[1]) + "\"",
"\"" + str((xCoord, yCoord)) + "\"",
"failed",
],
)
passedTrials = 0
else:
pg.event.clear()
continue
trialNum += 1
totalTrial += 1
if passedTrials == consecutiveAmt:
setNum += 1
colorPair = PgTools.two_rand_color()
trialNum = 1
passedTrials = 0
if randShapes:
posSeed = randint(0, 99999)
negSeed = randint(0, 99999)
if setNum == setsAmt:
PgTools.end_screen(screen)
while True:
for event in pg.event.get():
PgTools.quit_pg(event)
start_trial(stimLength, stimHeight, colorPair)
pg.display.update()
<file_sep>import sys
import os
import pygame as pg
from pygame.locals import *
sys.path.append(os.path.join("/home", "pi", "Desktop", "ChimpPygames", "PygameTools"))
import PgTools
import time
# initialize pygame and screen
pg.init()
screen = PgTools.Screen()
# init font for trial counter
font = pg.font.SysFont(None, 48)
file = open("Training_Task/parametersP1.dat")
params = PgTools.get_params(file)
file.close()
subjectName = str(params["subject_name"])
trialsAmt = int(params["number_of_trials"]) + 1
stimLength = int(params["first_stimulus_length"])
stimHeight = int(params["first_stimulus_height"])
lastLength = int(params["last_stimulus_length"])
lastHeight = int(params["last_stimulus_height"])
passDelay = int(params["passed_inter_trial_interval"])
failDelay = int(params["failed_inter_trial_interval"])
if "y" in str(params["randomly_shaped_stimuli"]) or "Y" in str(params["randomly_shaped_stimuli"]):
randShapes = True
else:
randShapes = False
# lengthDecrease = (stimLength - lastLength) / (trialsAmt - 1)
# heightDecrease = (stimHeight - lastHeight) / (trialsAmt - 1)
lengthDecrease = 5
heightDecrease = 5
def start_trial(length, height):
"""
Initiates a new trial, draws stimulus
:param length: length of new stimulus
:param height: width of new stimulus
"""
screen.refresh()
global stimulus
stimulus = pg.draw.rect(screen.fg,PgTools.BLUE,((int((PgTools.SCREEN_SIZE[0] - length) / 2),
int((PgTools.SCREEN_SIZE[1] - height) / 2),),
(length, height),),)
if randShapes:
PgTools.rand_shape(screen.fg, (
int((PgTools.SCREEN_SIZE[0] - length) / 2),
int((PgTools.SCREEN_SIZE[1] - height) / 2),
),(length, height))
PgTools.write_ln(
filename="Training_Task/resultsP1.csv",
data=["subject_name", "trial", "stimulus_size", "input_coordinates", "accuracy",],
)
trialNum = 1
start_trial(stimLength, stimHeight)
# game loop
running = True
# params for deliberate touch
touched_down = False # tells us whether the animal has already touched
when_they_started_their_touch = 0
min_touch_ms_required = 50
max_touch_ms = 3000
# int to track color changes
color_tracker = 0
while running:
# ensure stimulus does not get smaller than specified size
if stimHeight < lastHeight:
stimHeight = lastHeight
if stimLength < lastLength:
stimLength = lastLength
# disply trial number and stimulus size in upper left corner
text = font.render('Trial #{} ({}, {})'.format(trialNum, stimLength, stimHeight), True, Color('salmon'))
screen.fg.blit(text, (20, 20))
# set stimulus flicker rate and colors
color_tracker = color_tracker + 1
if color_tracker % 10 == 0:
pg.draw.rect(screen.fg, PgTools.AQUA,((int((PgTools.SCREEN_SIZE[0] - stimLength) / 2),
int((PgTools.SCREEN_SIZE[1] - stimHeight) / 2),), (stimLength, stimHeight),),)
else:
pg.draw.rect(screen.fg, PgTools.BLUE,((int((PgTools.SCREEN_SIZE[0] - stimLength) / 2),
int((PgTools.SCREEN_SIZE[1] - stimHeight) / 2),), (stimLength, stimHeight),),)
for event in pg.event.get():
PgTools.quit_pg(event)
if event.type == MOUSEBUTTONDOWN:
xCoord, yCoord = event.pos
when_they_started_their_touch = pg.time.get_ticks()
touched_down = True
elif (event.type == MOUSEBUTTONUP):
touched_down = False
if (pg.time.get_ticks()-when_they_started_their_touch<min_touch_ms_required) and \
(pg.time.get_ticks()-when_they_started_their_touch>max_touch_ms):
continue
elif (pg.time.get_ticks()-when_they_started_their_touch>min_touch_ms_required) and \
(pg.time.get_ticks()-when_they_started_their_touch<max_touch_ms):
if stimulus.collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
PgTools.response(screen, True, passDelay)
PgTools.write_ln(
filename="Training_Task/resultsP1.csv",
data=[
subjectName,
trialNum,
"\"" + str((stimLength, stimHeight)) + "\"",
"\"" + str((xCoord, yCoord)) + "\"",
"passed",
],
)
stimLength -= lengthDecrease
stimHeight -= heightDecrease
else:
PgTools.response(screen, False, failDelay)
PgTools.write_ln(
filename="Training_Task/resultsP1.csv",
data=[
subjectName,
trialNum,
"\"" + str((stimLength, stimHeight)) + "\"",
"\"" + str((xCoord, yCoord)) + "\"",
"failed",
],
)
trialNum += 1
if trialNum == trialsAmt:
PgTools.end_screen(screen)
while True:
for event in pg.event.get():
PgTools.quit_pg(event)
start_trial(stimLength, stimHeight)
pg.display.update()
pg.time.delay(100)
<file_sep>run:
./program_run.sh
setup: moveRepo
./setup.sh
moveRepo:
cd .. && mv ChimpPygames Desktop
<file_sep>#!/bin/bash
sudo apt-get update
sudo apt-get install python3
# (for marmpygames) sudo apt-get install qjoypad
chmod +x setup.sh
chmod +x Training_Task/TrainingTaskP1.sh
chmod +x Training_Task/TrainingTaskP2.sh
chmod +x Delayed_Match_To_Sample/DelayedMatchToSample.sh
chmod +x Delayed_Response_Task/DelayedResponseTask.sh
chmod +x Match_To_Sample/MatchToSample.sh
chmod +x Oddity_Testing/OddityTesting.sh
chmod +x Social_Stimuli_As_Rewards/SocialStimuli.sh
chmod +x Two_Choice_Discrimination/TwoChoiceDiscrim.sh
chmod +x program_run.sh
sleep 10
whiptail \
--title "ChimpPygames Setup" \
--msgbox "Setup Complete" 8 45
echo "setup complete"
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Training_Task/python_scripts/TrainingTaskP2.py
sleep 5
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Two_Choice_Discrimination/python_scripts/TwoChoiceDiscrim.py
sleep 5
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Delayed_Match_To_Sample/python_scripts/DelayedMatchToSample.py
sleep 5
<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Delayed_Response_Task/python_scripts/DelayedResponseTask.py
sleep 5<file_sep>#!/bin/bash
cd /home/pi/Desktop/ChimpPygames
source cpg_env/bin/activate
python Training_Task/python_scripts/TrainingTaskP1.py
sleep 5
<file_sep>import sys
import os
import random
import pygame as pg
from pygame.locals import *
sys.path.append(os.path.join("/home", "pi", "Desktop", "ChimpPygames", "PygameTools"))
import PgTools
# initialize pygame, screen, and clock
pg.init()
screen = PgTools.Screen()
clock = pg.time.Clock()
pg.time.get_ticks()
file = open("Delayed_Response_Task/parameters.dat")
params = PgTools.get_params(file)
file.close()
subjectName = str(params["subject_name"])
SCSStimName = str(params["spatially_cued_stimulus_name"])
otherStimName = str(params["other_stimuli_name"])
trialsAmt = int(params["number_of_trials"]) + 1
stimAmt = int(params["number_of_stimuli"])
locationsAmt = int(params["number_of_possible_SCS_locations"])
stimLength = int(params["stimulus_length"])
stimHeight = int(params["stimulus_height"])
strLengths = str(params["retention_interval_lengths"]).split(", ")
RILengths = [int(strLength) for strLength in strLengths]
passDelay = int(params["passed_inter_trial_interval"])
failDelay = int(params["failed_inter_trial_interval"])
if "y" in str(params["randomly_shaped_stimuli"]) or "Y" in str(params["randomly_shaped_stimuli"]):
randShapes = True
else:
randShapes = False
if locationsAmt > stimAmt:
locationsAmt = stimAmt
def trial_P1(length, height):
"""
Initiates part 1 of a new trial, draws stimuli
:param length: length of stimuli
:param height: height of stimuli
"""
screen.refresh()
global stimList
global trialStart
global SCSLength
global SCSHeight
trialStart = True
currentLength = int(maxLength / 4)
currentHeight = int(maxHeight / 4)
for i in range(stimAmt):
stimList.append(
pg.draw.rect(
screen.fg,
color,
(currentLength, currentHeight, length, height,),
)
)
if randShapes:
PgTools.rand_shape(screen.fg, (currentLength, currentHeight),(length, height), seed)
if i == SCSLocation:
SCSLength = currentLength
SCSHeight = currentHeight
currentLength += maxLength / 4
currentLength = int(currentLength)
if (i + 1) % 3 == 0:
currentLength = maxLength / 4
currentLength = int(currentLength)
currentHeight += maxHeight / 4
currentHeight= int(currentHeight)
def trial_P2():
"""
Initiates part 2 of a trial, redraws stimuli
"""
screen.refresh()
global stimList
global trialStart
global SCSLength
global SCSHeight
trialStart = True
currentLength = int(maxLength / 4)
currentHeight = int(maxHeight / 4)
for i in range(stimAmt):
stimList.append(
pg.draw.rect(
screen.fg,
color,
(currentLength, currentHeight, stimLength, stimHeight,),
)
)
if randShapes:
PgTools.rand_shape(screen.fg, (currentLength, currentHeight),(stimLength, stimHeight), seed)
if i == SCSLocation:
SCSLength = currentLength
SCSHeight = currentHeight
currentLength += maxLength / 4
if (i + 1) % 3 == 0:
currentLength = maxLength / 4
currentLength = int(currentLength)
currentHeight += maxHeight / 4
currentHeight= int(currentHeight)
def check_stim(xCoord, yCoord):
for i in range(stimAmt):
if i != SCSLocation and stimList[i].collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
return True
PgTools.write_ln(
filename="Delayed_Response_Task/results.csv",
data=[
"subject_name",
"number_of_possible_locations",
"trial",
SCSStimName,
"SCS_location",
"RI",
"accuracy",
],
)
trialNum = 1
color = PgTools.rand_color()
patColor = PgTools.rand_color()
randRI = random.choice(RILengths)
possibleLocations = random.sample(range(stimAmt), locationsAmt)
SCSLocation = random.choice(possibleLocations)
stimList = []
maxLength = PgTools.SCREEN_SIZE[0] - stimLength
maxHeight = PgTools.SCREEN_SIZE[1] - stimHeight
SCSLength = 0
SCSHeight = 0
currentTime = pg.time.get_ticks()
delay = 500
changeTime = currentTime + delay
show = True
blinking = True
seed = random.randint(0, 99999)
trial_P1(stimLength, stimHeight)
# game loop
running = True
while running:
for event in pg.event.get():
PgTools.quit_pg(event)
if event.type == MOUSEBUTTONDOWN:
xCoord, yCoord = event.pos
if trialStart:
if stimList[SCSLocation].collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
screen.refresh()
pg.event.get()
pg.time.delay(randRI)
pg.event.clear()
blinking = False
trial_P2()
pg.display.update()
trialStart = False
continue
else:
if stimList[SCSLocation].collidepoint(xCoord, yCoord) and screen.fg.get_at((xCoord, yCoord)) != (0,0,0):
PgTools.response(screen, True, passDelay)
PgTools.write_ln(
filename="Delayed_Response_Task/results.csv",
data=[
subjectName,
locationsAmt,
trialNum,
"\"" + str(color) + "\"",
SCSLocation + 1,
randRI,
"passed",
],
)
elif check_stim(xCoord, yCoord):
PgTools.response(screen, False, failDelay)
PgTools.write_ln(
filename="Delayed_Response_Task/results.csv",
data=[
subjectName,
locationsAmt,
trialNum,
"\"" + str(color) + "\"",
SCSLocation + 1,
randRI,
"failed",
],
)
else:
pg.event.clear()
continue
trialNum += 1
if trialNum == trialsAmt:
PgTools.end_screen(screen)
while True:
for event in pg.event.get():
PgTools.quit_pg(event)
color = PgTools.rand_color()
patColor = PgTools.rand_color()
randRI = random.choice(RILengths)
SCSLocation = random.choice(possibleLocations)
blinking = True
seed = random.randint(0, 99999)
trial_P1(stimLength, stimHeight)
currentTime = pg.time.get_ticks()
if blinking:
if currentTime >= changeTime:
changeTime = currentTime + delay
show = not show
stimList[SCSLocation] = pg.draw.rect(
screen.fg, PgTools.BLACK, (SCSLength, SCSHeight, stimLength, stimHeight,),
)
if show:
stimList[SCSLocation] = pg.draw.rect(
screen.fg, color, (SCSLength, SCSHeight, stimLength, stimHeight,),
)
if randShapes:
PgTools.rand_shape(screen.fg, (SCSLength, SCSHeight),(stimLength, stimHeight), seed)
pg.display.update()
<file_sep>These programs are for conducting expirements and gathering data for primate research running on a Raspberry PI 4, Elo Touchscreen, Ontrak Relay I/O interface, and a custom Pellet Dispenser.
- SETUP -
1. Make sure Raspberry PI is connected to the internet by checking the wifi/ethernet symbol in the top right corner.
2. Open Terminal on Raspberry PI by clicking the raspberry button in the top left corner > Accessories > Terminal
3. Update apt by entering into the terminal: sudo apt update
4. After it has finished, download/update git by entering into the terminal: sudo apt install git
5. After it has finished, download the ChimpPygames repo by entering into the terminal: git clone https://github.com/mdberkey/ChimpPygames.git
6. After it has finished change directory into ChimpPygames by entering into the terminal: cd ChimpPygames
7. Start the setup by entering into the terminal: make setup
8. Wait for the terminal shell to display "setup complete" then hit enter
9. The ChimpPygames folder should appear on the desktop.
10. If no errors occured then everything should be set up and ready to run.
- HOW TO USE - (after setup)
1. Make sure touchscreen, relay, and pellet dispenser are all plugged in correctly (Dispencer Relay Output wires should be in K1 sockets).
2. Edit the globalParameters.dat file in the ChimpPygames/PygameTools folder to alter parameters for every program.
3. Open Terminal on Raspberry PI and enter: cd Desktop/ChimpPygames
4. Start the program by entering into the terminal: make
5. A list of commands should appear in the terminal which contain every expirement.
6. Before starting however, one should make sure the parameters are set right:
1. Open the ChimpPygames folder on the desktop and then the corresponding folder to the desired experiment.
2. Edit the desired parameters in parameters.dat in the folder and SAVE the file.
- ALTERNATIVE METHOD TO USE - (old way)
1. Open the ChimpPygames folder on the desktop and then the corresponding folder to the desired experiment.
2. Double click on the <experiment_name>.sh file, a box should pop up, then click "execute" to begin the experiments.
5. After the expirement is done or exited manually, open the results.csv file to gather data from the experiment/s.
- HOW TO UPDATE -
1. Make sure Raspberry is connected to internet.
2. Open Terminal and enter: cd Desktop/ChimpPygames
3. Enter into the Terminal: git pull
4. run setup.sh by double clicking on the file and clicking execute
5. After it has completed, ChimpPygames should be updated.
*Important Notes*
- Press ESC, Q, or DOWNKEY to stop and exit the experiment.
- Data is recorded every trial during an expirement. So data is saved even if one exits the expirement early.
- The experiments will simply add new data on top of any data already present within results.csv so be sure to clear it from time to time. See the ecsv command.
- parameters.dat MUST be saved after changing variables for them to take effect
- Read the parameters.dat closely and be sure to save it with the correct value format or else an error might occur
- If a program wont run, check that the parameters are completley correct
- Touchscreen calibration: xinput set-prop 7 'Coordinate Transformation Matrix' 1 0 0.015 0 1 0.075 0 0 1
Author: <NAME> (<EMAIL>)
| 6fb9945d3ae3048f2eff20f1b415391ae16a5d0b | [
"Text",
"Python",
"Makefile",
"Shell"
] | 21 | Python | SquirrelMonkeyPrincess/ChimpPygames | 00809111e7eb28728fdbdba11612c444440c4e6e | d91326241650f0cc096bd92a19ec97d4f6e87ada |
refs/heads/main | <repo_name>SlavKoVrn/Doubletapp<file_sep>/controllers/RestController.php
<?php
namespace app\controllers;
use Yii;
use yii\web\ForbiddenHttpException;
class RestController extends \yii\rest\ActiveController
{
public function init()
{
parent::init();
if (Yii::$app->request->headers->get('Secret') != Yii::$app->params['API_SECRET']){
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
throw new ForbiddenHttpException('У Вас нет доступа');
}
}
}
<file_sep>/models/Levels.php
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%levels}}".
*
* @property int $id
* @property string|null $name
* @property string|null $code
*/
class Levels extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%levels}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name', 'code'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'Ид',
'name' => 'Название',
'code' => 'Код',
];
}
/**
* {@inheritdoc}
*/
public static function getLevelsList() {
return ArrayHelper::map(self::find()->all(), 'id', 'name');
}
/**
* {@inheritdoc}
*/
public function formName()
{
return 's';
}
/**
* {@inheritdoc}
*/
public function beforeSave($insert)
{
$this->code = strtoupper($this->code);
return parent::beforeSave($insert);
}
}
<file_sep>/controllers/WordsController.php
<?php
namespace app\controllers;
use app\models\Words;
use app\models\WordsSearch;
use Yii;
class WordsController extends RestController
{
public $modelClass = Words::class;
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$searchModel = new WordsSearch();
return $searchModel->search(Yii::$app->request->queryParams);
}
}
<file_sep>/models/Categories.php
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%categories}}".
*
* @property int $id
* @property string|null $name
* @property string|null $icon
*/
class Categories extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%categories}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name', 'icon'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'Ид',
'name' => 'Название',
'icon' => 'Картинка',
];
}
/**
* {@inheritdoc}
*/
public static function getCategoriesList() {
return ArrayHelper::map(self::find()->all(), 'id', 'name');
}
/**
* {@inheritdoc}
*/
public function formName()
{
return 's';
}
}
<file_sep>/views/category/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Categories */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="categories-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'icon')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
<div class="form-group">
<img id="img_look" class="img-responsive" src="<?= $model->icon ?>" />
</div>
<div class="form-group">
<?= Html::submitButton('Посмотреть ссылку', ['id'=>'look','class' => 'btn btn-success']) ?>
</div>
</div>
<?php
$js=<<<JS
$('#look').on('click',function(){
if ($('#s-icon').val()==''){
alert('Укажите ссылку на картинку');
return;
}
$('#img_look').attr('src',$('#s-icon').val());
});
JS;
$this->registerJs($js);<file_sep>/views/word/_form.php
<?php
use app\models\Themes;
use app\models\Words;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
/* @var $this yii\web\View */
/* @var $model app\models\Words */
/* @var $form yii\widgets\ActiveForm */
/* @var $themes array */
?>
<div class="words-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'themes')->widget(Select2::class, [
'data' => Themes::getThemesList(),
'maintainOrder' => true,
'options' => [
'placeholder' => 'Выберите тему ...',
'multiple' => true
],
'pluginOptions' => [
'tags' => true,
'maximumInputLength' => 10
],
])->label('Темы') ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'translation')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'transcription')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'example')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'sound')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
<div class="form-group">
<audio id="player" src="<?= $model->sound ?>" controls></audio>
</div>
<div class="form-group">
<?= Html::submitButton('Посмотреть ссылку', ['id'=>'look','class' => 'btn btn-success']) ?>
</div>
</div>
<?php
$js=<<<JS
$('#look').on('click',function(){
if ($('#s-sound').val()==''){
alert('Укажите ссылку на звук');
return;
}
$('#player').attr('src',$('#s-sound').val());
document.getElementById('player').play();
});
JS;
$this->registerJs($js);<file_sep>/models/Themes.php
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%themes}}".
*
* @property int $id
* @property int|null $category
* @property int|null $level
* @property string|null $name
* @property string|null $photo
*/
class Themes extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%themes}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['category', 'level'], 'integer'],
[['name', 'photo'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'Ид',
'category' => 'Категория',
'level' => 'Уровень',
'name' => 'Название',
'photo' => 'Фото',
'wordsCount' => 'Слова',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCategoryModel()
{
return $this->hasOne(Categories::class, ['id' => 'category']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getLevelModel()
{
return $this->hasOne(Levels::class, ['id' => 'level']);
}
/**
* @return array
*/
public static function getThemesList()
{
return ArrayHelper::map(self::find()->all(), 'id', 'name');
}
/**
* @param $id
* @return int|string
*/
public static function getWordsCountForTheme($id)
{
return Word2theme::find()->where(['theme_id' => $id])->count();
}
public function getWord2theme()
{
return $this->hasMany(Word2theme::class,['theme_id'=>'id']);
}
public function getWordsCount()
{
return count($this->word2theme);
}
public function extraFields()
{
return [
'words'=>'words'
];
}
public function getWords()
{
return $this->hasMany(Words::class, ['id' => 'word_id'])->viaTable('word2theme', ['theme_id' => 'id']);
}
public function formName()
{
return 's';
}
}
<file_sep>/README.md
<p align="center">
<a href="https://github.com/yiisoft" target="_blank">
<img src="https://avatars0.githubusercontent.com/u/993323" height="100px">
</a>
<h1 align="center" style="color:red">Doubletapp</h1>
<h3 align="center">Тестовое задание - RESTfull API</h3>
<br>
</p>
<strong>Демо версия</strong> [doubletapp.kadastrcard.ru](http://doubletapp.kadastrcard.ru/site/login)
```
Логин: admin
Пароль: admin
или
Логин: demo
Пароль: demo
```
<h2>Развернуть сайт</h2>
```
git clone https://github.com/SlavKoVrn/Doubletapp
```
<h3>перейти в каталог Doubletapp</h3>
```
cd Doubletapp
```
<h3>Установить библиотеки</h3>
```
conposer update
```
<h3>Настроить доступ к базе данных</h3>
```
/config/db.php
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2basic',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
```
<h3>Создание таблиц базы данных</h3>
```
yii migrate/up
```
<h3>Установить корень сайта в каталог /web</h3>
<h2>Тестирование работы</h2>
<h3>Установить константу API_SECRET</h3>
```
/config/params.php
<?php
return [
...
'API_SECRET' => '<KEY>d394ba88873c7de11a7d9d',
];
```
<h3>Реализованы следующие endpoint'ы</h3>
<h5>запрос к RESTfull API должен содержать заголовок</h5>
<h4>Secret: 95bf06e345d394ba88873c7de11a7d9d</h4>
<h5>иначе будет ответ</h5>
```
{
"name": "Forbidden",
"message": "У Вас нет доступа",
"code": 0,
"status": 403,
"type": "yii\\web\\ForbiddenHttpException"
}
```
GET http://doubletapp.kadastrcard.ru/categories
<h4>Secret: 95bf06e345d394ba88873c7de11a7d9d</h4>
```
[
{
"id": 1,
"name": "People and things",
"icon": "http://kadastrcard.ru/images/yii2.png"
},
{
"id": 2,
"name": "Appearance and character",
"icon": null
},
{
"id": 3,
"name": "Time and dates",
"icon": null
},
{
"id": 4,
"name": "Фразовые глаголы",
"icon": null
}
]
```
GET http://doubletapp.kadastrcard.ru/levels
<h4>Secret: 95bf06e345d394ba88873c7de11a7d9d</h4>
```
[
{
"id": 1,
"name": "Elementary",
"code": "A1"
},
{
"id": 2,
"name": "pre-intermediate",
"code": ""
},
{
"id": 3,
"name": "intermediate",
"code": ""
},
{
"id": 4,
"name": "upper_intermediate",
"code": ""
}
]
```
GET http://doubletapp.kadastrcard.ru/themes?s[category]=1&s[level]=1
<h4>Secret: 95bf06e345d394ba88873c7de11a7d9d</h4>
```
[
{
"id": 1,
"category": 1,
"level": 1,
"name": "Relationship",
"photo": "http://kadastrcard.ru/images/yii2.png"
}
]
```
GET http://doubletapp.kadastrcard.ru/themes/1?expand=words
<h4>Secret: 95bf06e345d394ba88873c7de11a7d9d</h4>
```
{
"id": 1,
"category": 1,
"level": 1,
"name": "Relationship",
"photo": "http://kadastrcard.ru/images/yii2.png",
"words": [
{
"id": 1,
"name": "to ask out",
"translation": "Пригласить на свидание",
"transcription": "tuː ɑːsk aʊt",
"example": "John has asked Mary out several times.",
"sound": "http://kadastrcard.ru/images/ring.wav"
}
]
}
```
GET http://doubletapp.kadastrcard.ru/words/1
<h4>Secret: 95bf06e345d394ba88873c7de11a7d9d</h4>
```
{
"id": 1,
"name": "to ask out",
"translation": "Пригласить на свидание",
"transcription": "tuː ɑːsk aʊt",
"example": "John has asked Mary out several times.",
"sound": "http://kadastrcard.ru/images/ring.wav"
}
```
<file_sep>/models/Words.php
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%words}}".
*
* @property int $id
* @property string|null $name
* @property string|null $translation
* @property string|null $transcription
* @property string|null $example
* @property string|null $sound
*/
class Words extends \yii\db\ActiveRecord
{
public $themes;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%words}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name', 'translation', 'transcription', 'example', 'sound'], 'string', 'max' => 255],
[['themes'], 'safe'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'Ид',
'name' => 'Название',
'translation' => 'Перевод',
'transcription' => 'Транскрипция',
'example' => 'Пример',
'sound' => 'Звук',
];
}
/**
* {@inheritdoc}
*/
public function afterFind()
{
parent::afterFind();
$this->themes = self::getThemesList($this->id);
}
/**
* {@inheritdoc}
*/
public function beforeSave($insert)
{
$return = parent::beforeSave($insert);
$now = self::getThemesList($this->id);
$new = (is_array($this->themes))?$this->themes:[];
$to_add = array_diff($new,$now);
$to_delete = array_diff($now,$new);
$transaction = Yii::$app->db->beginTransaction();
try {
foreach ($to_delete as $theme_id){
$wort2theme = Word2theme::findOne([
'word_id'=>$this->id,
'theme_id'=>$theme_id,
]);
$wort2theme->delete();
}
$saved = true;
foreach ($to_add as $theme_id){
$wort2theme = new Word2theme();
$wort2theme->word_id = $this->id;
$wort2theme->theme_id = $theme_id;
$saved = $wort2theme->save() && $saved;
}
} catch (\Exception $e) {
$saved = false;
}
$saved ? $transaction->commit() : $transaction->rollBack();
return $return && $saved;
}
/**
* {@inheritdoc}
*/
public static function getThemesList($id) {
return ArrayHelper::map(Word2theme::find()->where(['word_id' => $id])->all(), 'id', 'theme_id');
}
/**
* {@inheritdoc}
*/
public function formName()
{
return 's';
}
}
<file_sep>/migrations/m201125_121401_basa.php
<?php
use yii\db\Migration;
/**
* Class m201125_121401_basa
*/
class m201125_121401_basa extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%categories}}', [
'id' => $this->primaryKey(),
'name' => $this->string(),
'icon' => $this->string(),
], $tableOptions);
$this->batchInsert('{{%categories}}', ['name'], [
['People and things'],
['Appearance and character'],
['Time and dates'],
[ 'Фразовые глаголы'],
]);
$this->createTable('{{%levels}}', [
'id' => $this->primaryKey(),
'name' => $this->string(),
'code' => $this->string(),
], $tableOptions);
$this->batchInsert('{{%levels}}', ['name','code'], [
['Elementary','A1'],
['pre-intermediate',''],
['intermediate',''],
['upper_intermediate',''],
]);
$this->createTable('{{%themes}}', [
'id' => $this->primaryKey(),
'category' => $this->integer(),
'level' => $this->integer(),
'name' => $this->string(),
'photo' => $this->string(),
], $tableOptions);
$this->createIndex(
'{{%idx-themes-category}}',
'{{%themes}}',
'category'
);
$this->createIndex(
'{{%idx-themes-level}}',
'{{%themes}}',
'level'
);
$this->batchInsert('{{%themes}}', ['name','category','level'], [
['Relationship',1,1],
['Human body',2,2],
['Face',3,3],
['Things',4,4],
]);
$this->createTable('{{%words}}', [
'id' => $this->primaryKey(),
'name' => $this->string(),
'translation' => $this->string(),
'transcription' => $this->string(),
'example' => $this->string(),
'sound' => $this->string(),
], $tableOptions);
$this->batchInsert('{{%words}}', ['name','translation','transcription','example'], [
[
'to ask out',
'Пригласить на свидание',
'tuː ɑːsk aʊt',
'John has asked Mary out several times.',
]
]);
$this->createTable('{{%word2theme}}', [
'id' => $this->primaryKey(),
'word_id' => $this->integer(),
'theme_id' => $this->integer(),
], $tableOptions);
$this->createIndex(
'{{%idx-word2theme-word_id}}',
'{{%word2theme}}',
'word_id'
);
$this->createIndex(
'{{%idx-word2theme-theme_id}}',
'{{%word2theme}}',
'theme_id'
);
$this->batchInsert('{{%word2theme}}', ['word_id','theme_id'], [
[1,1],
[1,2],
[1,3],
[1,4],
]);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropTable('{{%categories}}');
$this->dropTable('{{%levels}}');
$this->dropIndex('{{%idx-themes-category}}','{{%themes}}');
$this->dropIndex('{{%idx-themes-level}}','{{%themes}}');
$this->dropTable('{{%themes}}');
$this->dropTable('{{%words}}');
$this->dropIndex('{{%idx-word2theme-word_id}}','{{%word2theme}}');
$this->dropIndex('{{%idx-word2theme-theme_id}}','{{%word2theme}}');
$this->dropTable('{{%word2theme}}');
}
}
<file_sep>/views/theme/_form.php
<?php
use app\models\Categories;
use app\models\Levels;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Themes */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="themes-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'category')->dropDownList(Categories::getCategoriesList()) ?>
<?= $form->field($model, 'level')->dropDownList(Levels::getLevelsList()) ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'photo')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
<div class="form-group">
<img id="img_look" class="img-responsive" src="<?= $model->photo ?>" />
</div>
<div class="form-group">
<?= Html::submitButton('Посмотреть ссылку', ['id'=>'look','class' => 'btn btn-success']) ?>
</div>
</div>
<?php
$js=<<<JS
$('#look').on('click',function(){
if ($('#s-photo').val()==''){
alert('Укажите ссылку на фото');
return;
}
$('#img_look').attr('src',$('#s-photo').val());
});
JS;
$this->registerJs($js);<file_sep>/controllers/CategoriesController.php
<?php
namespace app\controllers;
use app\models\Categories;
use app\models\CategoriesSearch;
use Yii;
class CategoriesController extends RestController
{
public $modelClass = Categories::class;
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$searchModel = new CategoriesSearch();
return $searchModel->search(Yii::$app->request->queryParams);
}
}
<file_sep>/controllers/LevelsController.php
<?php
namespace app\controllers;
use app\models\Levels;
use app\models\LevelsSearch;
use Yii;
class LevelsController extends RestController
{
public $modelClass = Levels::class;
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$searchModel = new LevelsSearch();
return $searchModel->search(Yii::$app->request->queryParams);
}
}
<file_sep>/models/Word2theme.php
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "{{%word2theme}}".
*
* @property int $id
* @property int|null $word_id
* @property int|null $theme_id
*/
class Word2theme extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%word2theme}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['word_id', 'theme_id'], 'integer'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'Ид',
'word_id' => 'Слово',
'theme_id' => 'Тема',
];
}
}
<file_sep>/controllers/ThemesController.php
<?php
namespace app\controllers;
use app\models\Themes;
use app\models\ThemesSearch;
use Yii;
class ThemesController extends RestController
{
public $modelClass = Themes::class;
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$searchModel = new ThemesSearch();
return $searchModel->search(Yii::$app->request->queryParams);
}
}
<file_sep>/views/theme/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel app\models\ThemesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Темы';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="themes-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Добавить тему', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'attribute'=>'category',
'content'=> function($model){
return $model->categoryModel->name;
},
'filter' => kartik\select2\Select2::widget([
'model' => $searchModel,
'attribute' =>'category',
'data' => \yii\helpers\ArrayHelper::map(\app\models\Categories::find()->orderBy("name")->all(),
'id',
'name'),
'theme' => \kartik\select2\Select2::THEME_BOOTSTRAP,
'pluginOptions' => [
'allowClear' => true,
],
'options' => [
'placeholder' => 'Поиск по категории',
],
]),
],
[
'attribute'=>'level',
'content'=> function($model){
return $model->levelModel->name;
},
'filter' => kartik\select2\Select2::widget([
'model' => $searchModel,
'attribute' =>'level',
'data' => \yii\helpers\ArrayHelper::map(\app\models\Levels::find()->orderBy("name")->all(),
'id',
'name'),
'theme' => \kartik\select2\Select2::THEME_BOOTSTRAP,
'pluginOptions' => [
'allowClear' => true,
],
'options' => [
'placeholder' => 'Поиск по уровню',
],
]),
],
'name',
[
'attribute'=>'photo',
'filter'=>false,
'format'=>'raw',
'value'=>function($model){
if (empty($model->photo)){
return '';
}
return '<img class="img-responsive" src="'.$model->photo.'" />';
}
],
[
'attribute'=>'wordsCount',
'filter'=>false,
'contentOptions' => [
'style'=>'text-align: right;'
],
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
| eaec4605d3275346fdd334ce01e3a01d01ee8f95 | [
"Markdown",
"PHP"
] | 16 | PHP | SlavKoVrn/Doubletapp | 92a97d9e343d25d75730bb7d61bb49d005297f89 | 33f46e4a5ce3f64aa479883b6eaaf23245639c84 |
refs/heads/master | <repo_name>madeindjs/acces_bat<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :products
resources :categories
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# services
get 'services/maintenance', to: 'services#maintenance'
get 'services/help', to: 'services#help'
get 'services/repair', to: 'services#repair'
get 'services/legal', to: 'services#legal'
get '/home', to: 'pages#home'
get '/contact', to: 'pages#contact'
get '/about', to: 'pages#about'
root to: 'pages#home'
end
<file_sep>/app/controllers/pages_controller.rb
class PagesController < ApplicationController
def home
end
def about
@title = 'Qui sommes-nous ?'
@breadcump = ['Accueil', @title]
end
def contact
@title = 'Contactez-nous'
@breadcump = ['Accueil', @title]
if params.has_key? 'object'
@object = 'Devis - %s' % params['object']
@content = "Bonjour,
Je vous contacte pour vous demander un devis concernant votre produit: #{params['object']}.
Pouvez-vous me recontatcer dans les plus brefs délais?
Cordialement.
"
end
end
end
<file_sep>/app/models/product.rb
class Product < ApplicationRecord
belongs_to :category
def complete_name
return "#{self.category.name} - #{self.name}"
end
end
<file_sep>/app/models/category.rb
class Category < ApplicationRecord
has_many :products
def image
name_slugged = self.name.parameterize
"categories/#{name_slugged}"
end
end
<file_sep>/db/migrate/20170901112214_add_categories_items.rb
class AddCategoriesItems < ActiveRecord::Migration[5.1]
def change
Category.create name: 'Portes Souples', description: "Nos portes souples à ouverture rapide intègrent toutes les technologies répondant à vos exigences"
Category.create name: 'Portes Sectionnelles', description: "Les Portes Sectionnelles Isolées ou Transparentes, à Refoulement ou à Empilement"
Category.create name: 'Rideaux Métalliques', description: "Fermer efficacement vos bâtiments avec notre sélection de rideaux métalliques"
Category.create name: 'Equipements de Quai', description: "Les Systèmes d’Arrimage, Les Niveleurs,
les Butoirs et les Sas d'étanchéité"
Category.create name: 'Barrières', description: "Découvrez notre barrière automatique destinée à votre activité !"
Category.create name: 'Portails', description: ""
Category.create name: 'Clôtures', description: "Les Clôtures destinées aux industries ou aux copropriétés"
Category.create name: 'Portes Piétonnes', description: "Venez découvrir nos portes automatiques coulissantes, battantes et pliantes"
Category.create name: 'Portes Transformateurs', description: "Les Portes pour Transformateurs"
end
def rollback
Category.delete_all
end
end
<file_sep>/app/controllers/services_controller.rb
class ServicesController < ApplicationController
def maintenance
@title = 'Contrats de Maintenance'
@description = "Ce sont des outils prépondérants de votre sérénité."
@breadcump = ['Nos services', @title]
end
def help
@title = 'Dépannage'
@description = "Des équipements toujours opérationnels."
@breadcump = ['Nos services', @title]
end
def repair
@title = 'Réparation et Modernisation'
@description = "La remise en service rapide d'un équipement est vitale."
@breadcump = ['Nos services', @title]
end
def legal
@title = 'Normes et Obligations Légales'
@description = "Vous aider à respecter les textes légaux."
@breadcump = ['Nos services', @title]
end
end
<file_sep>/db/migrate/20170901143358_add_products_items.rb
class AddProductsItems < ActiveRecord::Migration[5.1]
def change
basics_products = {
name: "Economie d'énergie",
description: "La porte rapide qui diminue votre facture d'énergie",
},
{
name: "Diminution maintenance",
description: "La porte souple aux coûts de maintenance réduits",
},
{
name: "Diminution maintenance",
description: "Sécurité",
}
data = [
'Portes Souples',
'Portes Sectionnelles',
'Rideaux Métalliques',
'Equipements de Quai',
'Barrières',
'Portails',
'Clôtures',
'Portes Piétonnes',
'Portes Transformateurs',
]
data.each do |category_name|
category = Category.where(name: category_name).first
basics_products.each do |product_data|
product_data['category_id'] = category.id
Product.create product_data
end
end
end
def rollback
Products.delete_all
end
end
| 797d7c29c53eee562fa5f9fc3207c7eaaea85a7a | [
"Ruby"
] | 7 | Ruby | madeindjs/acces_bat | 9887479525afa370f347679db4093ac501113bb2 | 87971f9964b58f5b3b658221e986d97cc503324d |
refs/heads/master | <repo_name>tamkmutnb/League_Of_Legends_Role_Random_For_Party<file_sep>/scramble_role-LoL.py
import time
from random import shuffle
import sys
def scramble():
x = input("Let's Go RANDOM? つ ◕_◕ つ[y/n]\n")
x = x.upper()
L=["TOP = ", "JNG = ", "MID = ", "ADC = ", "SUP = "]
M=["1", "2", "3", "4", "5"]
if x =="Y":
print("May TEEMO be With You\n")
time.sleep(1.5)
shuffle(M)
zip_lm = zip(L,M)
lst_lm = []
for L,M in zip_lm:
print(L+M)
time.sleep(1)
print('.')
time.sleep(1)
print('.')
time.sleep(1)
lst_lm.append(L+M)
for i in range(len(lst_lm)):
print(str(lst_lm[i]))
time.sleep(1)
scramble()
if x =="N":
for i in range(3,0,-1):
time.sleep(0.5)
print("Exiting in.."+str(i))
time.sleep(1)
exit()
sys.exit()
elif x != "Y":
time.sleep(0.6)
print('Your Answer Is Incorrect')
time.sleep(1)
scramble()
scramble()
| 9f164d554d5c835795be613dcfe15561fc806263 | [
"Python"
] | 1 | Python | tamkmutnb/League_Of_Legends_Role_Random_For_Party | 1e34ece039787509aa65880cfce4a3f55e773848 | aa6562405e47e05f7479cc012ec32800884516be |
refs/heads/master | <repo_name>S630/mvnfirst<file_sep>/src/main/java/com/cn/mystudy/dao/IUmsUtilDao.java
package com.cn.mystudy.dao;
import com.cn.mystudy.model.LoginInfo;
public interface IUmsUtilDao {
/**
* 用户信息
* @param loginInfo
* @return
* @throws Exception
*/
public void insert_loginInfo(LoginInfo info) throws Exception ;
}
<file_sep>/src/main/java/com/cn/mystudy/controller/UserController.java
package com.cn.mystudy.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cn.mystudy.model.User;
import com.cn.mystudy.service.IUserService;
@RequestMapping("/user")
@Controller
public class UserController {
@Autowired
private IUserService iuserService;
@RequestMapping("/showUser")
public String toIndex(HttpServletRequest request,Model model){
int userId = Integer.parseInt(request.getParameter("id"));
User user = this.iuserService.getUserById(userId);
model.addAttribute("user", user);
System.out.println(user);
return "showUser";
}
} <file_sep>/src/main/java/com/cn/mystudy/controller/loginController.java
package com.cn.mystudy.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.istack.internal.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cn.mystudy.model.User;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cn.mystudy.model.LoginInfo;
import com.cn.mystudy.service.IUserService;
import com.cn.mystudy.util.MSUtil;
@RequestMapping("/login")
@Controller
public class loginController {
@Autowired
private IUserService iuserService;
private MSUtil msUtil;
Logger logger = Logger.getLogger(loginController.class);
@RequestMapping(value="/logincheck",method=RequestMethod.POST)
public void logincheck(HttpServletRequest request,HttpServletResponse response, Model model) {
boolean loginflag = false;
String statuscode = "0";
String message = "";
String passwd = request.getParameter("passwd");
String uid = request.getParameter("id");
int userId = Integer.parseInt((String) (uid == null ? "0" : uid));
User user = this.iuserService.getUserById(userId);
if (user != null) {
System.out.println("now user:"+user.getName());
model.addAttribute("user", user);
//登录成功记录登陆者的信息
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUserid(user.getUserId());
loginInfo.setIp(msUtil.getIp2(request));
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:ms:ss");
Date date = new Date() ;
loginInfo.setTime(date);
this.iuserService.insert_loginInfo(loginInfo);
statuscode = "200";
// return "showUser";
}else{
statuscode ="100";
message = "用户["+ user +"]不存在!";
}
//return "error/Error";
// return "readme";
PrintWriter out;
try {
out = response.getWriter();
User user1 = new User();
user1.setName("aa");
User user2 = new User();
user2.setName("bb");
JSONArray array = new JSONArray();
array.add(user1);
array.add(user2);
JSONObject object = new JSONObject();
object.put("statuscode", statuscode);
object.put("msg", message);
object.put("referer", "index.html");
logger.info(object.toJSONString());
out.println(object);
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/com/cn/mystudy/model/LoginInfo.java
package com.cn.mystudy.model;
import java.util.Date;
public class LoginInfo {
//登录信息
private String userid;
private String ip;
private Date time;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
<file_sep>/src/main/java/com/cn/mystudy/model/question.java
package com.cn.mystudy.model;
import java.sql.Date;
public class question {
private String ID;
private int SERIALNUM;
private String TYPE;
private String TITLE;
private String TARGET;
private Date CREATETIME;
private String STATUS;
private String SOLUTION;
private Date SOLVETIME;
private String REMARK;
private String REMARK1;
private String REMARK2;
private String REMARK3;
private Date UPDATETIME;
private Date STAMP;
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public int getSERIALNUM() {
return SERIALNUM;
}
public void setSERIALNUM(int sERIALNUM) {
SERIALNUM = sERIALNUM;
}
public String getTYPE() {
return TYPE;
}
public void setTYPE(String tYPE) {
TYPE = tYPE;
}
public String getTITLE() {
return TITLE;
}
public void setTITLE(String tITLE) {
TITLE = tITLE;
}
public String getTARGET() {
return TARGET;
}
public void setTARGET(String tARGET) {
TARGET = tARGET;
}
public Date getCREATETIME() {
return CREATETIME;
}
public void setCREATETIME(Date cREATETIME) {
CREATETIME = cREATETIME;
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String sTATUS) {
STATUS = sTATUS;
}
public String getSOLUTION() {
return SOLUTION;
}
public void setSOLUTION(String sOLUTION) {
SOLUTION = sOLUTION;
}
public Date getSOLVETIME() {
return SOLVETIME;
}
public void setSOLVETIME(Date sOLVETIME) {
SOLVETIME = sOLVETIME;
}
public String getREMARK() {
return REMARK;
}
public void setREMARK(String rEMARK) {
REMARK = rEMARK;
}
public String getREMARK1() {
return REMARK1;
}
public void setREMARK1(String rEMARK1) {
REMARK1 = rEMARK1;
}
public String getREMARK2() {
return REMARK2;
}
public void setREMARK2(String rEMARK2) {
REMARK2 = rEMARK2;
}
public String getREMARK3() {
return REMARK3;
}
public void setREMARK3(String rEMARK3) {
REMARK3 = rEMARK3;
}
public Date getUPDATETIME() {
return UPDATETIME;
}
public void setUPDATETIME(Date uPDATETIME) {
UPDATETIME = uPDATETIME;
}
public Date getSTAMP() {
return STAMP;
}
public void setSTAMP(Date sTAMP) {
STAMP = sTAMP;
}
}
| 180464324162bf816ff74b7044e27083ee7b0e92 | [
"Java"
] | 5 | Java | S630/mvnfirst | bef400f1f25764b0c5d1da1b2a136b287280d5f9 | 37e66932250bcee22720ba035df6b01ebff59381 |
refs/heads/main | <repo_name>johncarrillo/front-curpro-ufps<file_sep>/src/app/services/usuario.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { RolAsignarUsuario } from '../models/RolAsignarUsuario';
import { Usuario } from '../models/usuario';
const cabecera = {
headers: new HttpHeaders({'Content-Type' : 'application/json'})
}
@Injectable({
providedIn: 'root'
})
export class UsuarioService {
usuarioURL = 'http://localhost:8080/usuario'
constructor(private httpClient: HttpClient) { }
public lista(): Observable <Usuario[]> {
return this.httpClient.get<Usuario[]>(this.usuarioURL, cabecera)
}
public buscar(id: number): Observable <Usuario> {
return this.httpClient.get<Usuario>(this.usuarioURL + '/' + id, cabecera)
}
public guardar(usuarioDto: Usuario): Observable<Usuario> {
return this.httpClient.post<Usuario>(this.usuarioURL, usuarioDto, cabecera);
}
public actualizar(usuarioDto: Usuario): Observable<any> {
return this.httpClient.put<Usuario>(this.usuarioURL, usuarioDto, cabecera);
}
public eliminar(id: number): Observable <Usuario> {
return this.httpClient.delete<Usuario>(this.usuarioURL + '/' + id, cabecera)
}
public asignarRol(rolAsignarUsuario: RolAsignarUsuario): Observable<Usuario> {
return this.httpClient.post<Usuario>(this.usuarioURL + '/asignarRol', rolAsignarUsuario, cabecera);
}
public listarDirectores(): Observable <Usuario[]> {
return this.httpClient.get<Usuario[]>(this.usuarioURL + '/directores', cabecera)
}
}
| eb549b382043ac4133bd45565369abb3193db940 | [
"TypeScript"
] | 1 | TypeScript | johncarrillo/front-curpro-ufps | 5384daae98867a6405f981fb0e3c9533ce322fa1 | fe951653a9c15fee5e3cebf28d525f3fde1998f6 |
refs/heads/master | <repo_name>kenestoDev/RNFilePicker<file_sep>/ios/Podfile
# Uncomment the next line to define a global platform for your project
platform :ios, '8.0'
target 'RNFilePicker' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for RNFilePicker
pod 'FPPicker', '~> 5.1.1'
target 'RNFilePicker-tvOSTests' do
inherit! :search_paths
# Pods for testing
end
target 'RNFilePickerTests' do
inherit! :search_paths
# Pods for testing
end
end
target 'RNFilePicker-tvOS' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for RNFilePicker-tvOS
end
<file_sep>/android/settings.gradle
rootProject.name = 'RNFilePicker'
include ':app'
| 66caf262baf79dfa6f6b6b86c9ac3f7bb1d0e092 | [
"Ruby",
"Gradle"
] | 2 | Ruby | kenestoDev/RNFilePicker | ae43dcc90ee77800545edcb1f8034cb6ea516709 | 4dbf61547f8db9a8446c2a510a8efc2bd99d7d1c |
refs/heads/main | <file_sep># LuaLexer
This is supposed to help in the manipulation of Lua source code. Supported lua versions Lua 5.x, MetaLua, Idle, GSL Shell and LuaU
<file_sep>--[=[
Lexical scanner for creating a sequence of tokens from Lua source code.
This is a heavily modified version of
the original Penlight Lexer module:
https://github.com/stevedonovan/Penlight
Authors:
stevedonovan <https://github.com/stevedonovan> ----------- Original Penlight lexer author
ryanjmulder <https://github.com/ryanjmulder> ------------- Penlight lexer contributer
mpeterv <https://github.com/mpeterv> --------------------- Penlight lexer contributer
Tieske <https://github.com/Tieske> ----------------------- Penlight lexer contributer
boatbomber <https://github.com/boatbomber> --------------- Roblox port, added builtin token, added patterns for incomplete syntax, bug fixes, behavior changes, token optimization
Sleitnick <https://github.com/Sleitnick> ----------------- Roblox optimizations
howmanysmall <https://github.com/howmanysmall> ----------- Lua + Roblox optimizations
boatbomber <https://github.com/boatbomber> --------------- Added lexer.navigator() for non-sequential reads
ccuser44 <https://github.com/ccuser44> ------------------- Forked from boatbomber, removed "plugin" and "self" from lua_keyword table as they are not keywords, made some changes with whitespace and made some other changes to make the use of the lexer be more applicable in uses outside of syntax highlighting
List of possible tokens:
- iden
- keyword
- string
- number
- comment
- operator
Usage:
local source = "for i = 1, n do end"
-- The 'scan' function returns a token iterator:
for token,src in lexer.scan(source) do
print(token, "'"..src.."'")
end
--> keyword 'for '
--> iden 'i '
--> operator '= '
--> number '1'
--> operator ', '
--> iden 'n '
--> keyword 'do '
--> keyword 'end'
-- The 'navigator' function returns a navigator object:
-- Navigators allow you to use nav.Peek() for non-sequential reads
local nav = lexer.navigator()
nav:SetSource(source) -- You can reuse navigators by setting a new Source
for token,src in nav.Next do
print(token, "'"..src.."'")
local peektoken, peeksrc = nav.Peek(2) -- You can peek backwards by passing a negative input
if peektoken then
print(" Peeked ahead by 2:", peektoken, "'"..peeksrc.."'")
end
end
--> keyword 'for '
--> Peeked ahead by 2: operator '= '
--> iden 'i '
--> Peeked ahead by 2: number '1'
--> operator '= '
--> Peeked ahead by 2: operator ', '
--> number '1'
--> Peeked ahead by 2: iden 'n '
--> operator ', '
--> Peeked ahead by 2: keyword 'do '
--> iden 'n '
--> Peeked ahead by 2: keyword 'end'
--> keyword 'do '
--> keyword 'end'
--]=]
local lexer = {}
local Prefix, Suffix, Cleaner = "^[ \t\n\0\a\b\v\f\r]*", "[ \t\n\0\a\b\v\f\r]*", "[ \t\n\0\a\b\v\f\r]+"
local NUMBER_A = "0[xX][%da-fA-F]+"
local NUMBER_B = "%d+%.?%d*[eE][%+%-]?%d+"
local NUMBER_C = "%d+[%.]?[%deE]*"
local VARARG = "%.%.%"
local CONCAT_OP = "%.%."
local LOREQ_OP, GOREQ_OP, NOTEQ_OP, EQ_OP = "<=", ">=", "~=", "=="
local OPERATORS = "[:;<>/%*%(%)%-=,{}%.#%^%+%%]"
local BRACKETS = "[%[%]]" -- needs to be separate pattern from other operators or it'll mess up multiline strings
local IDEN = "[%a_][%w_]*"
local STRING_EMPTY = "(['\"])%1" --Empty String
local STRING_PLAIN = "([\'\"])[^\n]-([^%\\]%1)" --TODO: Handle escaping escapes
local STRING_INCOMP_A = "(['\"]).-\n" --Incompleted String with next line
local STRING_INCOMP_B = "(['\"])[^\n]*" --Incompleted String without next line
local STRING_MULTI = "%[(=*)%[.-%]%1%]" --Multiline-String
local STRING_MULTI_INCOMP = "%[=*%[.-.*" --Incompleted Multiline-String
local COMMENT_MULTI = "%-%-%[(=*)%[.-%]%1%]" --Completed Multiline-Comment
local COMMENT_MULTI_INCOMP = "%-%-%[=*%[.-.*" --Incompleted Multiline-Comment
local COMMENT_PLAIN = "%-%-.-\n" --Completed Singleline-Comment
local COMMENT_INCOMP = "%-%-.*" --Incompleted Singleline-Comment
local TABLE_EMPTY = {}
local lua_keyword = {
["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true,
["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true,
["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["while"] = true,
["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true,
["until"] = true,
}
local implementation_spesific = {
Lua = { -- Any version of lua. Could be used for example where you want to have it for Lua in general not just a spesific version. If not specified a version the parser will default to this.
keywords = {
"continue", "goto", "<const>", "<toclose>"
},
operators = {
NOTEQ_OP, "%+=", "%-=", "%*=", "/=", "%%=", "%^=", "%.%.=", ">>", "<<", "::", "=>", "[&|~]", "//"
},
numbers = {
"0[bB][01_]+", "0[xX][_%da-fA-F]+", "%d+[%._]?[%_deE]*"
},
},
["Lua 5.2"] = {
keywords = {
"goto"
},
operators = {
"::"
}
},
["Lua 5.3"] = {
keywords = {
"goto"
},
operators = {
NOTEQ_OP, --[[Has to be added due to bitwise operators]] ">>", "<<", "::", "[&|~]", "//"
}
},
["Lua 5.4"] = {
keywords = {
"goto", "<const>", "<toclose>"
},
operators = {
NOTEQ_OP, --[[Has to be added due to bitwise operators]] ">>", "<<", "::", "[&|~]", "//"
}
},
Luau = {
keywords = {
"continue",
},
operators = {
NOTEQ_OP, "%+=", "%-=", "%*=", "/=", "%%=", "%^=", "%.%.=", "=>", "[|~]"
},
numbers = {
"0[bB][01_]+", "0[xX][_%da-fA-F]+", "%d+[%._]?[%_deE]*"
},
}
}
local function idump(tok)
--print("tok unknown:",tok)
return coroutine.yield("iden", tok)
end
local function odump(tok)
return coroutine.yield("operator", tok)
end
local function ndump(tok)
return coroutine.yield("number", tok)
end
local function sdump(tok)
return coroutine.yield("string", tok)
end
local function cdump(tok)
return coroutine.yield("comment", tok)
end
local function kdump(tok)
return coroutine.yield("keyword", tok)
end
local function lua_vdump(tok, implementation)
-- Since we merge spaces into the tok, we need to remove them
-- in order to check the actual word it contains
local cleanTok = string.gsub(tok, Cleaner, "")
if lua_keyword[cleanTok] then
return coroutine.yield("keyword", tok)
else
return coroutine.yield("iden", tok)
end
end
local lua_matches = {
-- Indentifiers
{Prefix.. IDEN ..Suffix, lua_vdump},
{Prefix.. VARARG ..Suffix, kdump},
-- Numbers
{Prefix.. NUMBER_A ..Suffix, ndump},
{Prefix.. NUMBER_B ..Suffix, ndump},
{Prefix.. NUMBER_C ..Suffix, ndump},
-- Strings
{Prefix.. STRING_EMPTY ..Suffix, sdump},
{Prefix.. STRING_PLAIN ..Suffix, sdump},
{Prefix.. STRING_INCOMP_A ..Suffix, sdump},
{Prefix.. STRING_INCOMP_B ..Suffix, sdump},
{Prefix.. STRING_MULTI ..Suffix, sdump},
{Prefix.. STRING_MULTI_INCOMP ..Suffix, sdump},
-- Comments
{Prefix.. COMMENT_MULTI ..Suffix, cdump},
{Prefix.. COMMENT_MULTI_INCOMP ..Suffix, cdump},
{Prefix.. COMMENT_PLAIN ..Suffix, cdump},
{Prefix.. COMMENT_INCOMP ..Suffix, cdump},
-- Operators
{Prefix.. CONCAT_OP ..Suffix, odump},
{Prefix.. LOREQ_OP ..Suffix, odump},
{Prefix.. GOREQ_OP ..Suffix, odump},
{Prefix.. NOTEQ_OP ..Suffix, odump},
{Prefix.. EQ_OP ..Suffix, odump},
{Prefix.. OPERATORS ..Suffix, odump},
{Prefix.. BRACKETS ..Suffix, odump},
-- Unknown
{"^.", idump}
}
local implementation_spesific_matches = {}
for version, data in pairs(implementation_spesific) do
local NewTable = {}
local keywords, operators, numbers = data.keywords, data.operators, data.numbers
if keywords then
for _, v in ipairs(keywords) do
table.insert(NewTable, {Prefix.. v ..Suffix, kdump})
end
end
if numbers then
for _, v in ipairs(numbers) do
table.insert(NewTable, {Prefix.. v ..Suffix, ndump})
end
end
if operators then
for _, v in ipairs(operators) do
table.insert(NewTable, {Prefix.. v ..Suffix, odump})
end
end
implementation_spesific_matches[version] = NewTable
end
--- Create a plain token iterator from a string.
-- @tparam string s a string.
function lexer.scan(s, include_wspace, merge_wspace, implementation)
local startTime = os.clock()
lexer.finished = false
assert((type(s) == "string" and s), "invalid argument #1 to 'scan' (string expected, got " .. type(s))
implementation = implementation and assert((type(implementation) == "string" and implementation), "bad argument #4 to 'scan' (string expected, got " .. type(implementation)) or "Lua"
local matches = {}
for _, v in ipairs(implementation_spesific_matches[implementation] or {}) do
table.insert(matches, v)
end
for _, v in ipairs(lua_matches) do
table.insert(matches, v)
end
local function lex(first_arg)
local line_nr = 0
local sz = #s
local idx = 1
-- res is the value used to resume the coroutine.
local function handle_requests(res)
while res do
local tp = type(res)
-- Insert a token list:
if tp == "table" then
res = coroutine.yield("", "")
for _, t in ipairs(res) do
res = coroutine.yield(t[1], t[2])
end
elseif tp == "string" then -- Or search up to some special pattern:
local i1, i2 = string.find(s, res, idx)
if i1 then
idx = i2 + 1
res = coroutine.yield("", string.sub(s, i1, i2))
else
res = coroutine.yield("", "")
idx = sz + 1
end
else
res = coroutine.yield(line_nr, idx)
end
end
end
handle_requests(first_arg)
line_nr = 1
while true do
if idx > sz then
while true do
handle_requests(coroutine.yield())
end
end
for _, m in ipairs(matches) do
local findres = {}
local i1, i2 = string.find(s, m[1], idx)
findres[1], findres[2] = i1, i2
if i1 then
local tok = string.sub(s, i1, i2)
idx = i2 + 1
lexer.finished = idx > sz
--if lexer.finished then
-- print(string.format("Lex took %.2f ms", (os.clock()-startTime)*1000 ))
--end
local res = m[2](tok, findres)
if string.find(tok, "\n") then
-- Update line number:
local _, newlines = string.gsub(tok, "\n", TABLE_EMPTY)
line_nr = line_nr + newlines
end
handle_requests(res)
break
end
end
end
end
return coroutine.wrap(lex)
end
function lexer.navigator()
local nav = {
Source = "";
TokenCache = table.create and table.create(50) or {};
_RealIndex = 0;
_UserIndex = 0;
_ScanThread = nil;
}
function nav:Destroy()
self.Source = nil
self._RealIndex = nil;
self._UserIndex = nil;
self.TokenCache = nil;
self._ScanThread = nil;
end
function nav:SetSource(SourceString)
self.Source = assert((type(SourceString) == "string" and SourceString), "Attempt to SetSource failed: Passed value is not a string")
self._RealIndex = 0;
self._UserIndex = 0;
if table.clear then
table.clear(self.TokenCache)
else
self.TokenCache = {}
end
self._ScanThread = coroutine.create(function()
for Token, Src in lexer.scan(self.Source) do
self._RealIndex = self._RealIndex + 1
self.TokenCache[self._RealIndex] = {Token; Src;}
coroutine.yield(Token,Src)
end
end)
end
function nav.Next()
nav._UserIndex = nav._UserIndex + 1
if nav._RealIndex >= nav._UserIndex then
-- Already scanned, return cached
return (table.unpack or unpack)(nav.TokenCache[nav._UserIndex])
else
if coroutine.status(nav._ScanThread) == "dead" then
-- Scan thread dead
return
else
local success, token, src = coroutine.resume(nav._ScanThread)
if success and token then
-- Scanned new data
return token, src
else
-- Lex completed
return
end
end
end
end
function nav.Peek(PeekAmount)
local GoalIndex = nav._UserIndex + PeekAmount
if nav._RealIndex >= GoalIndex then
-- Already scanned, return cached
if GoalIndex > 0 then
return (table.unpack or unpack)(nav.TokenCache[GoalIndex])
else
-- Invalid peek
return
end
else
if coroutine.status(nav._ScanThread) == "dead" then
-- Scan thread dead
return
else
local IterationsAway = GoalIndex - nav._RealIndex
local success, token, src = nil, nil, nil
for i = 1, IterationsAway do
success, token, src = coroutine.resume(nav._ScanThread)
if not (success or token) then
-- Lex completed
break
end
end
return token, src
end
end
end
return nav
end
return lexer
<file_sep># Security Policy
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| Lua 5.x | :white_check_mark: |
| MetaLua | :white_check_mark: |
| Idle | :white_check_mark: |
| LuaU | :white_check_mark: |
| Lua 4.x | :x: |
| Lua 3.x | :x: |
| Lua 2.x | :x: |
| Lua 1.x | :x: |
## Reporting a Vulnerability
Just make a bug report
| 36de62896bb15c48a5a15879275b1e226a4fd5dc | [
"Markdown",
"Lua"
] | 3 | Markdown | ccuser44/LuaLexer | 021ec79a17f634f0e82f86b07fb3ac36cd5005c9 | 5e71615940b40743f971c9313d3b07a651f02243 |
refs/heads/master | <repo_name>liman-cs/tally-ready<file_sep>/app/src/main/java/com/example/tally/frag_record/OutcomeFragment.java
package com.example.tally.frag_record;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.tally.R;
import com.example.tally.db.DBManager;
import com.example.tally.db.TypeBean;
import com.example.tally.utils.KeyBoardUtils;
import java.util.ArrayList;
import java.util.List;
/**
*记录页面当中的支出模块
*/
public class OutcomeFragment extends Fragment {
KeyboardView keyboardView;
EditText moneyEt;
ImageView typeIv;
TextView typeTv,beizhuTv,timeTv;
GridView typeGv;
List<TypeBean>typeList;
private TypeBaseAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_outcome, container, false);
initView(view);
//给GridView填充数据的方法
loadDataToGV();
return view;
}
/*给GridView填出数据的方法*/
private void loadDataToGV() {
typeList = new ArrayList<>();
adapter = new TypeBaseAdapter(getContext(), typeList);
typeGv.setAdapter(adapter);
//获取数据库中的数据源
List<TypeBean> outList = DBManager.getTypeList(0);
typeList.addAll(outList);
adapter.notifyDataSetChanged();
}
private void initView(View view) {
keyboardView = view.findViewById(R.id.frag_record_keyboard);
moneyEt = view.findViewById(R.id.frag_record_et_money);
typeIv = view.findViewById(R.id.frag_record_iv);
typeGv = view.findViewById(R.id.frag_record_gv);
typeTv = view.findViewById(R.id.frag_record_tv_type);
beizhuTv = view.findViewById(R.id.frag_record_tv_beizhu);
timeTv = view.findViewById(R.id.frag_record_tv_time);
//让自定义如软键盘显示出来
KeyBoardUtils boardUtils = new KeyBoardUtils(keyboardView,moneyEt);
boardUtils.showKeyboard();
//设置接口,监听确定按钮被点击了
boardUtils.setOnEnsureListener(new KeyBoardUtils.OnEnsureListener() {
@Override
public void onEnsure() {
//点击了确定按钮
//获取记录的信息,保存在数据库中
//返回上一级页面
}
});
}
}<file_sep>/README.md
# tally-ready
andriod 期末作品
简约记账程序
简简单单
| e8e4814bc761549950654b5ec2a4dad587483353 | [
"Markdown",
"Java"
] | 2 | Java | liman-cs/tally-ready | e1f52715d436dd6b0f8d43d2232944c9fd794a4d | 2162f3fc268ce657a89395951128863ff98e5e44 |
refs/heads/master | <repo_name>xenon58/-sparta-coding<file_sep>/pythonClass/Homework/4wk homework.py
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
from pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
client = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.
db = client.dbsparta
## HTML을 주는 부분
@app.route('/')
def home():
return render_template('original.html')
## API 역할을 하는 부분
@app.route('/content', methods=['POST'])
def message_post():
name_receive = request.form['name_give']
select_receive = request.form['select_give']
address_receive = request.form['address_give']
number_receive = request.form['number_give']
doc={'name': name_receive, 'select': select_receive,'address': address_receive,'number': number_receive}
db.homework.insert_one(doc)
return jsonify({'result':'success','msg': '리뷰가 성공적으로 작성되었습니다.'})
@app.route('/content', methods=['GET'])
def message_get():
send_data = list(db.homework.find({},{'_id':False}))
return jsonify({'result':'success', 'msg': send_data})
if __name__ == '__main__':
app.run('0.0.0.0',port=5000,debug=True)<file_sep>/project/app.py
from flask import Flask, render_template, jsonify, request, url_for
app = Flask(__name__)
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
client = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.
db = client.project
# 접속 화면 설
@app.route('/home')
def home():
return render_template('home.html')
# 하루 스케쥴표로 주소 부여
@app.route('/day_schedule')
def day_schedule():
return render_template('day_schedule.html')
# 스케쥴 입력창 주소 부여
@app.route('/input_schedule')
def input_schedule():
return render_template('input_schedule.html')
# API 역할을 하는 부분
@app.route('/today_data', methods=['POST'])
def taday_date():
# 클라이언트가 전달한 today_date_give 정보를 받아서 receive 변수에 넣는다.
today_date_receive = request.form['today_date_give']
# 전달받은 정보를 db의 date key값에서 같은 정보가 있는지 확인한다.
result=list(db.intervention.find({'date': today_date_receive},{'_id':False}))
# db내 date 목록에서 select로 date 가 date_receive과 일치하는 정보를 가져옵니다.
# 자료를 list로 만들어서 돌려 보냅니다.
# result=list(db.intervention.find({},{'_id':False}))
return jsonify({'result': 'success','raw_data':result})
@app.route('/pt_data', methods=['POST'])
def patient_data():
# 1. 클라이언트가 전달한 _give 정보를 _receive 변수에 넣습니다.
date_receive = request.form['date_give']
number_receive = request.form['number_give']
room_receive = request.form['room_give']
name_receive = request.form['name_give']
sex_receive = request.form['sex_give']
age_receive = request.form['age_give']
site_receive = request.form['site_give']
category_receive = request.form['category_give']
treatment_receive = request.form['treatment_give']
info_receive = request.form['info_give']
# 2. 전달 받은 정보를 db에 저장한다.
pt_data = dict(date=date_receive, number=number_receive, room=room_receive, name=name_receive, sex=sex_receive,
age=age_receive, site=site_receive, category=category_receive, treatment=treatment_receive,
info=info_receive)
db.intervention.insert_one(pt_data)
return jsonify({'result':'success', 'msg':'스케줄에 등록 되었습니다!'})
# @app.route('/api/delete', methods=['POST'])
# def star_delete():
# # 1. 클라이언트가 전달한 name_give를 name_receive 변수에 넣습니다.
# name_receive = request.form['name_give']
# # 2. mystar 목록에서 delete_one으로 name이 name_receive와 일치하는 star를 제거합니다.
# db.mystar.delete_one({'name':name_receive})
# # 3. 성공하면 success 메시지를 반환합니다.
# return jsonify({'result': 'success','msg':'삭제 완료! 안녕~'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)<file_sep>/pythonClass/3wk 2nd class.py
import requests
from bs4 import BeautifulSoup
# 타겟 URL을 읽어서 HTML를 받아오고,
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)
# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
# soup이라는 변수에 "파싱 용이해진 html"이 담긴 상태가 됨
# 이제 코딩을 통해 필요한 부분을 추출하면 된다.
soup = BeautifulSoup(data.text, 'html.parser')
# movie_title = soup.select('div.tit5')
# for movie in movie_title:
# print (movie.text)
#############################
# (입맛에 맞게 코딩)
#############################
movie_info=soup.select('table.list_ranking > tbody > tr')
# print(movie_info)
i=1
for movie in movie_info:
title = movie.select('.tit5>a')
point = movie.select('td.point')
if title:
title=title[0].text
point=point[0].text
print(i,title,point)
i=i+1
<file_sep>/pythonClass/4wk practice.py
from pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
client = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.
db = client.dbsparta
musics = list(db.music_chart.find())
target_music = db.music_chart.find_one({"title":"Black Swan"})
target_singer = target_music['singer']
titles = list(db.music_chart.find({'singer':target_singer}))
for title in titles :
print(title[target_singer))<file_sep>/pythonClass/sparta-server/app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/write')
def write():
return '질문은 이쪽으로 보내주세요~ <EMAIL>'
if __name__ == '__main__':
app.run('0.0.0.0',port=5000, debug=True)
<file_sep>/pythonClass/4wk 1st class.py
a=['사과','감','감','배','포도','포도','딸기','포도','감','수박','딸기']
def count_list (a_list):
result = {}
for fruit in a_list:
if fruit in result.keys():
result[fruit] +=1
else:
result[fruit] = 1
return result
print(count_list(a))<file_sep>/pythonClass/3wk homework - gini music rank.py
import requests
from bs4 import BeautifulSoup
# 지니 뮤직 URL을 읽어서 HTML를 받아오고,
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&rtm=N&ymd=20200309',headers=headers)
# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
soup = BeautifulSoup(data.text, 'html.parser')
# select를 이용해서, 원하는 정보 (곡 제목, 가수) 불러오기
music_list = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
# 음악들 반복문을 돌리기
rank = 0
for music in music_list :
title1 = music.select('td.info > a.title.ellipsis')
singer1 = music.select ('td.info > a.artist.ellipsis')
title2 = title1[0].text.strip()
singer2 = singer1[0].text.strip()
rank += 1
print (rank, title2, '-', singer2) | 28baac2cc8fd24f2237195b00e69bf1a913695d7 | [
"Python"
] | 7 | Python | xenon58/-sparta-coding | f7087f153f5f0228dbc10b5b3f465eba0d140af9 | 02d1ab7ac57b83023b9d394c19ab877558296667 |
refs/heads/master | <repo_name>Andriy-Lyt/lighthouse-js-fundamentals<file_sep>/codeville.js
const stations = [
['Big Bear Donair', 10, 'restaurant'],
['Bright Lights Elementary', 50, 'school'],
['Moose Mountain Community Centre', 45, 'community centre']
];
function chooseStations(stations){
let goodStations = [];
for(let array of stations ){
// console.log("outer for loop aray: "+array);
if(array[1] >= 20 && (array[2] == 'school' || array[2] == 'community centre')){
goodStations.push(array);
}
}
return goodStations;
}
console.log(chooseStations(stations));
<file_sep>/parade-position.js
const moves = ['north', 'north', 'west', 'west', 'north', 'east','north']
const finalPosition = function(moves){
let x=0; let y=0;
let finalPosition = [];
for(let element of moves){
switch(element){
case 'north':
++y; break;
case 'south':
--y; break;
case 'east':
++x; break;
case 'west':
--x; break;
}//closing switch
} // closing for loop
finalPosition.push(x);
finalPosition.push(y);
return finalPosition;
}// closing function
console.log(finalPosition(moves));
<file_sep>/judgeVegetable.js
const vegetables = [
{
submitter: '<NAME>',
redness: 10,
plumpness: 5
},
{
submitter: '<NAME>',
redness: 2,
plumpness: 8
},
{
submitter: '<NAME>',
redness: 4,
plumpness: 3
}
]
const metric = 'redness';
const judgeVegetable = function (vegetables, metric) {
let numbers = [];
for (let i = 0; i < vegetables.length; i++) {
numbers.push(vegetables[i][metric]);
}
// console.log(typeof numbers[0], numbers);
//find index of max number in array:
let maxValue = numbers[0];
let maxIndex = 0;
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxIndex = i;
maxValue = numbers[i];
}
}
// console.log("maxIndex: "+maxIndex);
return vegetables[maxIndex].submitter;
}// closing function
console.log(judgeVegetable(vegetables, metric));
<file_sep>/function-expression.js
var laugh1 = function(number){
let string = '';
let counter = 0;
while(counter < number) {
string += "ha! \n";
counter++;
}
return string;
}
var laugh2 = function(number){
let string = '';
for(let i = 0; i < number; i++){
string += "ha! \n";
}
return string;
}
// console.log(laugh1(3));
console.log(laugh2(3));
<file_sep>/tinkering.js
function mult(a,b){
return a*b;
}
const result = mult(2,4);
console.log(result);
| a40554b03c7b04d70ed607ece0a9e7c7d59f854f | [
"JavaScript"
] | 5 | JavaScript | Andriy-Lyt/lighthouse-js-fundamentals | c9b818878cbbbee2bca418ed09909b76f522f68b | a1d87416e752d535e9ac6f02dcb61540f82853f7 |
refs/heads/master | <repo_name>hananafif/ebookfrontend<file_sep>/src/pages/main/main.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HomePage } from '../home/home';
import { Materi1Page} from '../materi1/materi1'
import { Materi2Page} from '../materi2/materi2'
import { Materi3Page} from '../materi3/materi3'
/**
* Generated class for the MainPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-main',
templateUrl: 'main.html',
})
export class MainPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad MainPage');
}
home(){
this.navCtrl.push(HomePage);
}
materi1(){
this.navCtrl.push("Materi1Page");
}
materi2(){
this.navCtrl.push("Materi2Page");
}
materi3(){
this.navCtrl.push("Materi3Page");
}
}
<file_sep>/src/pages/materi3/materi3.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { Materi3Page } from './materi3';
@NgModule({
declarations: [
Materi3Page,
],
imports: [
IonicPageModule.forChild(Materi3Page),
],
})
export class Materi3PageModule {}
| 34277a2b5b332914f66d669bde7977ad44f75783 | [
"TypeScript"
] | 2 | TypeScript | hananafif/ebookfrontend | b5406df1d56884b540a009dbaac949a2c2562da9 | 0b5b5371d72fd153f52176b84e81db478800fa97 |
refs/heads/master | <repo_name>antoni-devlin/blog2<file_sep>/forms.py
from flask_wtf import FlaskForm
from flask_ckeditor import CKEditorField
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField
from wtforms.validators import DataRequired, ValidationError, Email, EqualTo
# Form for adding new posts
class AddEditPost(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
category = SelectField(u'Category', choices=[('cat1', 'Category 1'), ('cat2', 'Category 2'), ('cat3', 'Category 3'), ('cat4', 'Category 4')])
draft = BooleanField('Draft')
body = CKEditorField('Content Area')
submit = SubmitField('Save Post')
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
password2 = PasswordField('<PASSWORD>', validators=[DataRequired(), EqualTo('<PASSWORD>')])
submit = SubmitField('Register')
# def validate_username(self, username):
# user = User.query.filter_by(username=username.data).first()
# if user is not None:
# raise ValidationError('Please use a different username.')
#
# def validate_email(self, email):
# user = User.query.filter_by(email=email.data).first()
# if user is not None:
# raise ValidationError('Please use a different email address.')
<file_sep>/requirements.txt
alembic==1.0.0
altgraph==0.10.2
backports-abc==0.5
bdist-mpkg==0.5.0
bonjour-py==0.3
click==6.7
cpyrit-cuda===0.4.1-dev.-svn.r308-
Cython==0.25.2
dnet==1.12
ez-setup==0.9
Flask==1.0.2
Flask-Login==0.4.1
Flask-Migrate==2.2.1
Flask-SQLAlchemy==2.3.2
Flask-WTF==0.14.2
futures==3.2.0
itsdangerous==0.24
Jinja2==2.10
macholib==1.5.1
Mako==1.0.7
MarkupSafe==1.0
matplotlib==1.3.1
modulegraph==0.10.4
netaddr==0.7.19
nose==1.3.7
numpy==1.8.0rc1
passlib==1.7.1
py2app==0.7.3
pylibpcap==0.6.2
pyobjc-core==2.5.1
pyobjc-framework-Accounts==2.5.1
pyobjc-framework-AddressBook==2.5.1
pyobjc-framework-AppleScriptKit==2.5.1
pyobjc-framework-AppleScriptObjC==2.5.1
pyobjc-framework-Automator==2.5.1
pyobjc-framework-CFNetwork==2.5.1
pyobjc-framework-Cocoa==2.5.1
pyobjc-framework-Collaboration==2.5.1
pyobjc-framework-CoreData==2.5.1
pyobjc-framework-CoreLocation==2.5.1
pyobjc-framework-CoreText==2.5.1
pyobjc-framework-DictionaryServices==2.5.1
pyobjc-framework-EventKit==2.5.1
pyobjc-framework-ExceptionHandling==2.5.1
pyobjc-framework-FSEvents==2.5.1
pyobjc-framework-InputMethodKit==2.5.1
pyobjc-framework-InstallerPlugins==2.5.1
pyobjc-framework-InstantMessage==2.5.1
pyobjc-framework-LatentSemanticMapping==2.5.1
pyobjc-framework-LaunchServices==2.5.1
pyobjc-framework-Message==2.5.1
pyobjc-framework-OpenDirectory==2.5.1
pyobjc-framework-PreferencePanes==2.5.1
pyobjc-framework-PubSub==2.5.1
pyobjc-framework-QTKit==2.5.1
pyobjc-framework-Quartz==2.5.1
pyobjc-framework-ScreenSaver==2.5.1
pyobjc-framework-ScriptingBridge==2.5.1
pyobjc-framework-SearchKit==2.5.1
pyobjc-framework-ServiceManagement==2.5.1
pyobjc-framework-Social==2.5.1
pyobjc-framework-SyncServices==2.5.1
pyobjc-framework-SystemConfiguration==2.5.1
pyobjc-framework-WebKit==2.5.1
pyOpenSSL==0.13.1
pyparsing==2.0.1
pyrit===0.4.1-dev.-svn.r308-
pystan==2.16.0.0
python-dateutil==1.5
python-dotenv==0.9.1
python-editor==1.0.3
python-slugify==1.2.5
pytz==2013.7
requests-transition==1.0.4.0
scapy==2.1.0
scipy==0.13.0b1
singledispatch==3.4.0.3
six==1.4.1
speedtest-cli==1.0.7
SQLAlchemy==1.2.10
tornado==5.1
Unidecode==1.0.22
vboxapi==1.0
Werkzeug==0.14.1
WTForms==2.1
xattr==0.6.4
zope.interface==4.1.1
<file_sep>/app.py
from flask import Flask, url_for, render_template, request, flash, redirect
from slugify import slugify
from flask_sqlalchemy import *
from flask_migrate import Migrate
from flask_login import LoginManager, UserMixin, logout_user, login_user, current_user, login_required, login_manager
from datetime import datetime
from forms import AddEditPost, LoginForm, RegistrationForm
from flask_ckeditor import CKEditor
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.urls import url_parse
import os
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "blogdatabase.db"))
app = Flask(__name__)
app.config['SECRET_KEY'] = '<KEY>'
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
ckeditor = CKEditor(app)
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer(), primary_key=True)
date_posted = db.Column(db.DateTime(), index = True, default = datetime.utcnow)
title = db.Column(db.String(80), unique=True, nullable=False)
slug = db.Column(db.String(80), unique=True, default = id, nullable=False)
category = db.Column(db.String(80))
draft = db.Column(db.Boolean(), default = True)
body = db.Column(db.Text())
def __repr__(self):
return '<Post {}>'.format(self.body)
# Automatic Slug generation (using slugify)
@staticmethod
def generate_slug(target, value, oldvalue, initiator):
if not target.slug:
target.slug = slugify(value)
event.listen(Post.title, 'set', Post.generate_slug, retval=False)
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True, nullable=False)
email = db.Column(db.String(120), index=True, unique=True, nullable=False)
password_hash = db.Column(db.String(128))
def __repr__(self):
return '<User {}>'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
@login.user_loader
def load_user(id):
return User.query.get(int(id))
#Home Page Route
@app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Post': Post}
@app.route('/')
@app.route('/index')
def index():
title = '<NAME> | Blog'
posts = Post.query.all()
return render_template('index.html', posts=posts, title=title)
#Add New Post Route
@app.route('/add', methods=['GET', 'POST'])
@login_required
def add_post():
form = AddEditPost()
if form.validate_on_submit():
post = Post(title = form.title.data, category = form.category.data, draft = form.draft.data, body = form.body.data)
db.session.add(post)
db.session.commit()
return redirect(url_for('index'))
return render_template('add.html', form=form)
# Edit Existing Post
@app.route('/edit/<string:slug>', methods=['GET', 'POST'])
@login_required
def edit_post(slug):
post = Post.query.filter_by(slug=slug).first_or_404()
form = AddEditPost(obj=post)
if form.validate_on_submit():
post.title = form.title.data
post.category = form.category.data
post.draft = form.draft.data
post.body = form.body.data
db.session.commit()
return redirect(url_for('index'))
return render_template('add.html', form=form, title='Edit Post')
@app.route('/delete/<string:slug>')
@login_required
def delete_post(slug):
Post.query.filter_by(slug=slug).delete()
db.session.commit()
return redirect(url_for('index'))
# Navigate to post by slug
@app.route('/post/<string:slug>')
def byslug(slug):
post = Post.query.filter_by(slug=slug).first_or_404()
return render_template("post.html", post=post, slug=slug)
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you are now a registered user!')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return redirect(url_for('index'))
return render_template('login.html', title='Sign In', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/contact')
def contact():
title = 'Contact'
return render_template('contact.html', title=title)
@app.route('/about')
def about():
title = 'About'
return render_template('about.html', title=title)
# Error handling
@app.errorhandler(404)
def page_not_found(e):
title = 'Not Found'
return render_template('404.html', title=title), 404
| 3824d96cf1b868aa2e5154267cbc62d1e95dfa54 | [
"Python",
"Text"
] | 3 | Python | antoni-devlin/blog2 | 9f34ffa9ef5429184bcede6c674bbfaaeac35e03 | b6173429ff64fc009c0c9456669764e874f2c6b2 |
refs/heads/master | <repo_name>ruthico/Project01_5404_8555_dotNet5780<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/Converters.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows;
using BE;
using BL;
namespace PLWPF
{
#region GuestRequest
public class ConvertersFullName : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
GuestRequest guestRequest = (GuestRequest)value;
return guestRequest.PrivateName + " " + guestRequest.FamilyName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersMeal : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
GuestRequest guestRequest = (GuestRequest)value;
string meal = "";
if (guestRequest.Breakfast == true)
meal += "B ";
else
meal += " ";
if (guestRequest.Lunch == true)
meal += "L ";
else
meal += " ";
if (guestRequest.Dinner == true)
meal += "D";
return meal;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersPool : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
GuestRequest guestRequest = (GuestRequest)value;
return guestRequest.Pool == ChoosingAttraction.אפשרי || guestRequest.Pool == ChoosingAttraction.הכרחי ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersJacuzzi : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
GuestRequest guestRequest = (GuestRequest)value;
return guestRequest.Jacuzzi == ChoosingAttraction.אפשרי || guestRequest.Jacuzzi == ChoosingAttraction.הכרחי ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersPChildrensAttractions : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
GuestRequest guestRequest = (GuestRequest)value;
return guestRequest.ChildrensAttractions == ChoosingAttraction.אפשרי || guestRequest.ChildrensAttractions == ChoosingAttraction.הכרחי ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersGarden : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
GuestRequest guestRequest = (GuestRequest)value;
return guestRequest.Garden == ChoosingAttraction.אפשרי || guestRequest.Garden == ChoosingAttraction.הכרחי ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
#endregion
//public class ConverterHuName : IValueConverter
//{
// BL.IBL bl;
// public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
// {
// bl = BL.FactoryBL.GetBL();
// Order order = (Order)value;
// string nameH = bl.KeyToNameHu(order.HostingUnitKey);
// return nameH;
// }
// public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
// {
// throw new NotImplementedException();
// }
//}
#region HostingUnit
public class ConverterHostName : IValueConverter
{
BL.IBL bl;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bl = BL.FactoryBL.GetBL();
HostingUnit hostingUnit = (HostingUnit)value;
return hostingUnit.Owner.PrivateName + " " + hostingUnit.Owner.FamilyName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersPoolHU : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
HostingUnit hostingUnit = (HostingUnit)value;
return hostingUnit.Pool ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersGardenHU : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
HostingUnit hostingUnit = (HostingUnit)value;
return hostingUnit.Garden ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersjakuziHU : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
HostingUnit hostingUnit = (HostingUnit)value;
return hostingUnit.Jacuzzi ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersAtractionHU : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
HostingUnit hostingUnit = (HostingUnit)value;
return hostingUnit.ChildrensAttractions ? "V" : "X";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class ConvertersMealHU : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
HostingUnit hostingUnit = (HostingUnit)value;
string meal = "";
if (hostingUnit.Breakfast == true)
meal += "B ";
else
meal += " ";
if (hostingUnit.Lunch == true)
meal += "L ";
else
meal += " ";
if (hostingUnit.Dinner == true)
meal += "D";
return meal;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
#endregion
//public class ConverterGRName : IValueConverter
//{
// BL.IBL bl;
// public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
// {
// bl = BL.FactoryBL.GetBL();
// Order order = (Order)value;
// string nameH = bl.KeyToNameGR(order.GuestRequestKey);
// return nameH;
// }
// public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
// {
// throw new NotImplementedException();
// }
//}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/LinqHost.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for LinqHost.xaml
/// </summary>
public partial class LinqHost : Window
{
BL.IBL bl;
public LinqHost()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
bl = BL.FactoryBL.GetBL();
}
private void Host_Click(object sender, RoutedEventArgs e)
{
ListView_Host.ItemsSource = bl.Get_Host();
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BE/SiteOwner1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public class SiteOwner1 : IClonable
{
private static int passwords;
public static int Passwords { get => passwords; set => passwords = value; }
private static int commission;
public static int Commission { get => commission; set => commission = value;}
private static int accumulation;
public static int Accumulation { get => accumulation; set => accumulation = value; }
public override string ToString()
{
string siteOwner = " ";
return siteOwner += string.Format("SiteOwner Passwords : {0}\n" + "SiteOwner Commission : {1}\n"+ "SiteOwner Accumulation : {2}\n", passwords, commission, accumulation);
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/AddOrder.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for AddOrder.xaml
/// </summary>
///
public partial class AddOrder : Window
{
BL.IBL bl;
GuestRequest g;
Host host;
HostingUnit hostingUnit = new HostingUnit();
IEnumerable<GuestRequest> guestRequest;
public AddOrder(Host H)
{
bl = BL.FactoryBL.GetBL();
guestRequest = new ObservableCollection<GuestRequest>();
g = new GuestRequest();
host = H;
this.DataContext = host;
InitializeComponent();
NavigationService.NavigationStack.Push(this);
this.AreaCB.ItemsSource = Enum.GetValues(typeof(BE.AreasInTheCountry));
this.TypeHostingUnitCB.ItemsSource = Enum.GetValues(typeof(BE.TypesOfVacation));
IEnumerable<string> nameHu = bl.NameOfUnit(host);
this.NameHu.ItemsSource = nameHu;
}
private void Button_Click_All(object sender, RoutedEventArgs e)
{
ListView_GR.ItemsSource = bl.Get_GuestRequestListB();
}
private void Button_Click_HU(object sender, RoutedEventArgs e)
{
NameHu.Visibility = Visibility.Visible;
}
private void Choise_Click(object sender, RoutedEventArgs e)
{
BGR1.Visibility = Visibility.Visible;
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void NameHuCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
guestRequest = bl.Get_GuestRequestListB();
hostingUnit = bl.Host_ToHostingUnit(host, NameHu.SelectedItem.ToString());
GuestRequest G = new GuestRequest();
if (hostingUnit.Pool == false)
guestRequest = bl.Condition_Guest_Request1(bl.PoolF, guestRequest);
if (hostingUnit.Garden == false)
guestRequest = bl.Condition_Guest_Request1(bl.GardenF, guestRequest);
if (hostingUnit.Jacuzzi == false)
guestRequest = bl.Condition_Guest_Request1(bl.GardenF, guestRequest);
if (hostingUnit.ChildrensAttractions == false)
guestRequest = bl.Condition_Guest_Request1(bl.AttractionF, guestRequest);
if (hostingUnit.Breakfast == false)
guestRequest = bl.Condition_Guest_Request1(bl.Breakfast, guestRequest);
if (hostingUnit.Lunch == false)
guestRequest = bl.Condition_Guest_Request1(bl.Lunch, guestRequest);
if (hostingUnit.Dinner == false)
guestRequest = bl.Condition_Guest_Request1(bl.Dinner, guestRequest);
if (hostingUnit.Children > 0)
{
guestRequest = bl.Condition_Guest_Request2(g => g.Children <= hostingUnit.Children, guestRequest);
}
if (hostingUnit.Adults > 0)
{
guestRequest = bl.Condition_Guest_Request2(g => g.Adults <= hostingUnit.Children, guestRequest);
}
if (hostingUnit.Room > 0)
{
guestRequest = bl.Condition_Guest_Request2(g => g.Room <= hostingUnit.Children, guestRequest);
}
guestRequest = bl.Condition_Guest_Request2(g => g.Type == hostingUnit.Type, guestRequest);
guestRequest = bl.Condition_Guest_Request2(g => g.SubArea == hostingUnit.SubArea, guestRequest);
ListView_GR.ItemsSource = guestRequest;
}
private void AreaCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SubAreaCB.Visibility = Visibility.Visible;
switch (AreaCB.SelectedValue.ToString())
{
case ("הכל"):
SubAreaCB.SelectedItem = "{Binding Path=All,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.All));
break;
case ("ירושלים"):
SubAreaCB.SelectedItem = "{Binding Path=Jerusalem,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.Jerusalem));
break;
case ("צפון"):
SubAreaCB.SelectedItem = "{Binding Path=North,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.North));
break;
case ("דרום"):
SubAreaCB.SelectedItem = "{Binding Path=South,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.South));
break;
case ("מרכז"):
SubAreaCB.SelectedItem = "{Binding Path=Center,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.Center));
break;
}
}
private void SubAreaCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void ListView_GR_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void MouseDoubleClick_ListView_GR(object sender, RoutedEventArgs e)
{
if (((ListView)sender).SelectedItem!=null)
{
GuestRequest g = new GuestRequest();
g = ((ListView)sender).SelectedItem as GuestRequest;
GetHuName WIN = new GetHuName(host,g);
WIN.Show();
}
}
private void Execut_Click(object sender, RoutedEventArgs e)
{
GuestRequest G = new GuestRequest();
g.Area = (AreasInTheCountry)Enum.Parse(typeof(AreasInTheCountry), AreaCB.SelectedItem.ToString(), true);
g.SubArea = (All)Enum.Parse(typeof(All), SubAreaCB.SelectedItem.ToString(), true);
g.Type = (TypesOfVacation)Enum.Parse(typeof(TypesOfVacation), TypeHostingUnitCB.SelectedItem.ToString(), true);
if (int.Parse(SumAdults.Text) > 0)
{
guestRequest = bl.Condition_Guest_Request2(g =>g.Adults >= int.Parse(SumAdults.Text), guestRequest);
}
if (int.Parse(SumAdults.Text) > 0)
{
guestRequest = bl.Condition_Guest_Request2(g => g.Children >= int.Parse(Sumchilds.Text), guestRequest);
}
if (int.Parse(SumAdults.Text) > 0)
{
guestRequest = bl.Condition_Guest_Request2(g => g.Adults >= int.Parse(SumRoom.Text), guestRequest);
}
if (poolcb.IsChecked == true) guestRequest = bl.Condition_Guest_Request1(bl.PoolT, bl.Get_GuestRequestListB());
else guestRequest = bl.Condition_Guest_Request1(bl.PoolF, bl.Get_GuestRequestListB());
if (GardenCB.IsChecked == true) guestRequest = bl.Condition_Guest_Request1(bl.GardenT, guestRequest);
else guestRequest = bl.Condition_Guest_Request1(bl.GardenF, guestRequest);
if (jakuziCB.IsChecked == true) guestRequest = bl.Condition_Guest_Request1(bl.jakuzziT, guestRequest);
else guestRequest = bl.Condition_Guest_Request1(bl.jakuzziF, guestRequest);
if (AttractionCB.IsChecked == true) guestRequest = bl.Condition_Guest_Request1(bl.AttractionT, guestRequest);
else guestRequest = bl.Condition_Guest_Request1(bl.AttractionF, guestRequest);
if (BreakFastCB.IsChecked == true)
{
guestRequest = bl.Condition_Guest_Request1(bl.Breakfast, guestRequest);
}
if (LunchCB.IsChecked == true)
{
guestRequest = bl.Condition_Guest_Request1(bl.Lunch, guestRequest);
}
if (DinnerCB.IsChecked == true)
{
guestRequest = bl.Condition_Guest_Request1(bl.Dinner, guestRequest);
}
ListView_GR.ItemsSource = guestRequest;
}
private void ComboBox_SelectionChanged_4(object sender, SelectionChangedEventArgs e)
{
}
// if (hostingUnit.Pool == true)
// guestRequest = bl.Condition_Guest_Request1(bl.PoolT, guestRequest);
//else
// guestRequest = bl.Condition_Guest_Request1(bl.PoolF, guestRequest);
//if (hostingUnit.Garden == true)
// guestRequest = bl.Condition_Guest_Request1(bl.GardenT, guestRequest);
//else
//guestRequest = bl.Condition_Guest_Request1(bl.GardenF, guestRequest);
//if (hostingUnit.Jacuzzi == true)
// guestRequest = bl.Condition_Guest_Request1(bl.GardenT, guestRequest);
//else
//guestRequest = bl.Condition_Guest_Request1(bl.GardenF, guestRequest);
//if (hostingUnit.ChildrensAttractions == true)
//guestRequest = bl.Condition_Guest_Request1(bl.AttractionT, guestRequest);
//else
//guestRequest = bl.Condition_Guest_Request1(bl.AttractionF, guestRequest);
// if (hostingUnit.Breakfast == false)
//guestRequest = bl.Condition_Guest_Request1(bl.Breakfast, guestRequest);
//if (hostingUnit.Lunch == false)
// guestRequest = bl.Condition_Guest_Request1(bl.Lunch, guestRequest);
//if (hostingUnit.Dinner == false)
//guestRequest = bl.Condition_Guest_Request1(bl.Dinner, guestRequest);
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BE/GuestRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace BE
{
public class GuestRequest :IClonable
{
private int guestRequestKey;
public int GuestRequestKey { get => guestRequestKey; set => guestRequestKey = value; }
private String privateName;
public String PrivateName { get => privateName; set => privateName = value; }
private String familyName;
public String FamilyName { get => familyName; set => familyName = value; }
private String mailAddress;
public String MailAddress { get => mailAddress; set => mailAddress = value; }
private int id;
public int ID { get => id; set => id = value; }
private OrderStatus status;
public OrderStatus Status { get => status; set => status = value; }
private DateTime registrationDate;
public DateTime RegistrationDate { get => registrationDate; set => registrationDate = value; }
private DateTime entryDate;
public DateTime EntryDate { get => entryDate; set => entryDate = value; }
private DateTime releaseDate;
public DateTime ReleaseDate { get => releaseDate; set => releaseDate = value; }
private AreasInTheCountry area;
public AreasInTheCountry Area { get => area; set => area = value; }
private All subArea;
public All SubArea { get => subArea; set => subArea = value; }
private TypesOfVacation type;
public TypesOfVacation Type { get => type; set => type = value; }
private int adults;
public int Adults { get => adults; set => adults = value; }
private int children;
public int Children { get => children; set => children = value; }
private ChoosingAttraction childrensAttractions;
public ChoosingAttraction ChildrensAttractions { get => childrensAttractions; set => childrensAttractions = value; }
private int room;
public int Room { get => room; set => room = value; }
private ChoosingAttraction pool;
public ChoosingAttraction Pool { get => pool; set => pool = value; }
private ChoosingAttraction jacuzzi;
public ChoosingAttraction Jacuzzi { get => jacuzzi; set => jacuzzi = value; }
private ChoosingAttraction garden;
public ChoosingAttraction Garden { get => garden; set => garden = value; }
private bool breakfast;
public bool Breakfast { get => breakfast; set => breakfast = value; }
private bool lunch;
public bool Lunch { get => lunch; set => lunch = value; }
private bool dinner;
public bool Dinner { get => dinner; set => dinner = value; }
public override string ToString()
{
string GuestRequest = " ";
return GuestRequest += string.Format("Guest Request Key: {0}\n"+ "Name: {1} {2}\n"+ "Mail:{3}\n" + "ID:{4}\n" + "status: {5}\n"
+ "Registration Date:{6}\n"+ "Entry Date: {7}\n" + "Release Date:{8}\n" + "Area:{9}\n" + "Sub Area:{10}\n"+
"Type:{11}\n" + "Adults:{12}\n" + "Children: {13}\n" + "Room: {14}\n" + "Pool:{15}\n" + "Jacuzzi: {16}\n" + "Garden{17}\n" + "Childrens Attractions: {18}\n"+ "Breakfast:{19}\n" + " Lunch:{20}\n" + " Dinner:{21}\n", guestRequestKey,PrivateName,FamilyName, MailAddress,ID,Status,
RegistrationDate, EntryDate, ReleaseDate, Area, SubArea , Type, Adults,Children,Room,Pool,Jacuzzi,Garden, ChildrensAttractions , Breakfast, Lunch,Dinner);
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/Project01_5404_8555_dotNet5780/BL/IBL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
namespace BL
{
public interface IBL
{
void CheckSumDay(GuestRequest guest);
void Signed_bank_debit_authoization(GuestRequest x);
bool AvailableDate(HostingUnit T, GuestRequest F);
void BusyDate(Order O);
void CheckStatus(Order O);
int StatusDone(Order O);
void StatusChange(Order o);
void SendMail(Order O);
bool AvailableUnit(DateTime Entry, int sumDay);
int CalculateDate(DateTime firstDate, DateTime secondDate);
IEnumerable<IGrouping<AreasInTheCountry, GuestRequest>> VacationArea();
IEnumerable<IGrouping<int, GuestRequest>> SumOfVacationers();
IEnumerable<IGrouping<int, Host>> SumOfHostingunit();
IEnumerable<IGrouping<AreasInTheCountry, HostingUnit>> RegionOfUnit();
Host CheckId(int id);
List<HostingUnit> FindHostingUnit(int id);
IEnumerable< string> NameOfUnit(Host HO);
//IDAL
void AddGuestRequestB(GuestRequest T);
void AddOrderB(Order T);
void AddHostingUnitB(HostingUnit T);
void RemoveHostingUnitB(HostingUnit H);
void UpdateGuestRequestB(GuestRequest T);
void UpdateHostingUnitB(HostingUnit T);
void OrderChangedB(Order T);
IEnumerable<HostingUnit> Get_HostingUnitsListB();
IEnumerable<GuestRequest> Get_GuestRequestListB();
IEnumerable<Order> Get_OrdersB();
IEnumerable<BankBranch> Brunch_bankB();
// HostingUnit
HostingUnit Host_ToHostingUnit(Host h, string name);
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BE/Host.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public class Host : IClonable
{
private int hostKey;
public int HostKey { get => hostKey; set => hostKey = value; }
private string privateName;
public string PrivateName { get => privateName; set => privateName = value; }
private string familyName;
public string FamilyName { get => familyName; set => familyName = value; }
private int phoneNumber;
public int PhoneNumber { get => phoneNumber; set => phoneNumber = value; }
private string mailAddress;
public string MailAddress { get => mailAddress; set => mailAddress = value; }
private BankBranch bankAccount;
public BankBranch BankAccount { get => bankAccount; set => bankAccount = value; }
private bool collectionClearance;
public bool CollectionClearance { get => collectionClearance; set => collectionClearance = value; }
public override string ToString()
{
string Host = " ";
return Host += string.Format("Host Key: {0}\n" + "Name: {1} {2}\n" + "Fhone Number: {3}\n" + "Mail: {4}\n" +" -Bank Account:\n" + "{5}\n" + "Collection Clearance:{6}",
HostKey, PrivateName, FamilyName, PhoneNumber, MailAddress, BankAccount, CollectionClearance);
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/NavigationService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace PLWPF
{
public class NavigationService
{
public NavigationService()
{
// NavigationStack.Push(Application.Current.MainWindow);
}
public static Stack<Window> NavigationStack = new Stack<Window>();
public static void NavigateBack()
{
NavigationStack.Pop().Close();
NavigationStack.Peek().Show();
}
public static bool CanNavigateBack()
{
return NavigationStack.Count > 1;
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/GetStatusOrder.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for GetStatusOrder.xaml
/// </summary>
public partial class GetStatusOrder : Window
{
BL.IBL bl;
Order order;
Host host;
public GetStatusOrder(Host H,Order o)
{
host = H;
order = o;
bl = BL.FactoryBL.GetBL();
InitializeComponent();
NavigationService.NavigationStack.Push(this);
this.ChangeStatus.ItemsSource = Enum.GetValues(typeof(BE.OrderStatus));
}
private void ChangeStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void Update_btn_Click(object sender, RoutedEventArgs e)
{
order.Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), ChangeStatus.SelectedItem.ToString(), true);
try
{
bl.OrderChangedB(host,order);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message.ToString());
}
this.Close();
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BE/Enum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public enum TypesOfVacation { צימר, מלון, קמפינג, דירת_אירוח }
public enum AreasInTheCountry { הכל, צפון, דרום, מרכז, ירושלים }
public enum Jerusalem { הכל, העיר_העתיקה, ממילה, גילו, תלפיות, מרכז_העיר, בית_וגן }
public enum Center { הכל, תל_אביב, רמת_גן, קיריית_אונו, נתניה, פתח_תקווה, אור_יהודה, גיבעתיים, ראשון_לציון }
public enum South { הכל, אילת, באר_שבע, אשדוד, אשקלון, אופקים, ערד, קריית_גת, נתיבות }
public enum North { הכל, נהריה, בית_שאן, עפולה, צפת, כרמיאל, גליל_עליון, קיריית_שמונה }
public enum All
{
הכל, נהריה, בית_שאן, עפולה, צפת, כרמיאל, גליל_עליון, קיריית_שמונה ,אילת, באר_שבע,
אשדוד, אשקלון, אופקים, ערד, קריית_גת, נתיבות , תל_אביב, רמת_גן, קיריית_אונו,
ירושלים,מרכז,צפון,דרום ,נתניה ,העיר_העתיקה, ממילה, גילו, תלפיות, מרכז_העיר, בית_וגן, פתח_תקווה, אור_יהודה, גיבעתיים, ראשון_לציון
}
//public enum Meal {Breakfast,Dinner,Lunch}
//public enum CustomersRequirement { Open, Closed_when_expired, The_deal_was_closed }
public enum ChoosingAttraction{ הכרחי,אפשרי,לא_מעוניין}
public enum OrderStatus { לא_טופל,נשלח_מייל, נסגר_מחוסר_הענות, נסגרה_עסקה }
public enum Bank_Name {Mizrahi,Discont,Marcentil,BenLeoumi,Igood}
public class Program
{
}
}
<file_sep>/Project01_5404_8555_dotNet5780/Project01_5404_8555_dotNet5780/DAL/IDAL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
namespace DAL
{
public interface IDAL
{
void AddGuestRequest(GuestRequest T);
void AddOrder(Order T);
void AddHostingUnit(HostingUnit T);
void DeleteHostingUnit(HostingUnit T);
void UpdateGuestRequest(GuestRequest T);
void UpdateHostingUnit(HostingUnit T);
void OrderChanged(Order T);
IEnumerable<HostingUnit> Get_HostingUnitsList();
IEnumerable<GuestRequest> Get_GuestRequestList();
IEnumerable<Order> Get_Orders();
IEnumerable<BankBranch> GetBrunch_bank();
IEnumerable<Host> Get_HostList();
}
}
<file_sep>/Project01_5404_8555_dotNet5780/DAL/IDAL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
namespace DAL
{
public interface IDAL
{
void AddGuestRequest(GuestRequest T);
void AddOrder(Order T);
void AddHostingUnit(HostingUnit T);
void DeleteHostingUnit(HostingUnit T);
void UpdateGuestRequest(GuestRequest T);
void UpdateHostingUnit(HostingUnit T);
void OrderChanged(Order T);
void AddHost(Host Ho);
IEnumerable<HostingUnit> Get_HostingUnitsList();
IEnumerable<GuestRequest> Get_GuestRequestList();
IEnumerable<Order> Get_Orders();
IEnumerable<Host> Get_HostList();
void updateaccumulation(int co);
int updatepasswords(int co);
int Get_commission();
int Get_passwords();
int Get_accumulation();
IEnumerable<BankBranch> GetBrunch_bank();
IEnumerable<BankBranch> GetAllbanks(Func<BankBranch, bool> condition = null);
// GuestRequest FindGR(int ID);///?????
//T ReadXml<T>(string filename);
//List<BankBranch> GetListBankAccount();
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/AddHost.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for AddHost.xaml
/// </summary>
public partial class AddHost : Window
{
Host host;
BL.IBL bl;
public AddHost()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
bl = BL.FactoryBL.GetBL();
host = new Host();
}
private void Button_Click_Add(object sender, RoutedEventArgs e)
{
try
{
if ((id.Text).Length != 9)
{
id.BorderBrush = Brushes.Red;
IDlabel.Content = "הכנס ת.ז בעלת 9 תווים";
IDlabel.BorderBrush = Brushes.Red;
return;
}
else { IDlabel.BorderBrush =Brushes.Transparent; }
if (PN.Text == "")
{
PN.BorderBrush = Brushes.Red;
PnLabel.Content = "הכנס שם פרטי";
PnLabel.BorderBrush = Brushes.Red;
return;
}
if (FN.Text == "")
{
FN.BorderBrush = Brushes.Red;
FnLabel.Content = "הכנס שם משפחה";
FnLabel.BorderBrush = Brushes.Red;
return;
}
host.FamilyName = FN.Text;
host.PrivateName = PN.Text;
host.MailAddress = Mail.Text;
host.HostKey = int.Parse(id.Text);
host.PhoneNumber = int.Parse(Phone.Text);
//host.BankAccount = GetBank();
bl.AddHostB(host);
vi.Visibility = Visibility.Visible;
addlable.Visibility = Visibility.Visible;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Host", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
//private BankBranch GetBank()
//{
// BankBranch b= bl.Brunch_bankB().FirstOrDefault(x => x.BankNumber == int.Parse(BankNum.Text));
// b.BankAccountNumber = int.Parse(AccontNum.Text);
// return b;
//}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void id_TextChanged(object sender, TextChangedEventArgs e)
{
//if (id.Text.Length == 9)
// host.HostKey = int.Parse(id.Text);
//else throw new KeyNotFoundException("הכנס ת.ז בעלת 9 ספרות");
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/UpdateHostingUnit.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for UpdateHostingUnit.xaml
/// </summary>
public partial class UpdateHostingUnit : Window
{
BL.IBL bl;
Host host = new Host();
HostingUnit hostingUnit = new HostingUnit();
public UpdateHostingUnit(Host H)
{
bl = BL.FactoryBL.GetBL();
host = H;
this.DataContext = host;
InitializeComponent();
NavigationService.NavigationStack.Push(this);
this.AreaCB.ItemsSource = Enum.GetValues(typeof(BE.AreasInTheCountry));
this.TypeHostingUnitCB.ItemsSource = Enum.GetValues(typeof(BE.TypesOfVacation));
IEnumerable<string> nameHu = bl.NameOfUnit(host);
this.NameHu.ItemsSource = nameHu;
}
private bool button1WasClicked = false;
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
hostingUnit = bl.Host_ToHostingUnit(host, NameHu.SelectedItem.ToString());
if (hostingUnit.Pool)
poolCB.IsChecked = true;
if (hostingUnit.Garden)
GardenCB.IsChecked = true;
if (hostingUnit.Jacuzzi)
jakouziCB.IsChecked = true;
if (hostingUnit.ChildrensAttractions)
AttractionCB.IsChecked = true;
if (hostingUnit.Breakfast)
BreakfastCB.IsChecked = true;
if (hostingUnit.Lunch)
LunchCB.IsChecked = true;
if (hostingUnit.Dinner)
DinnerCB.IsChecked = true;
TypeHostingUnitCB.SelectedItem = hostingUnit.Type;
AreaBtn.Content = hostingUnit.SubArea;
RoomTxt.Text = hostingUnit.Room.ToString();
}
private int _numValue1 = 0;
public int NumValue1
{
get { return _numValue1; }
set
{
_numValue1 = value;
txtNumRoom.Text = value.ToString();
RoomTxt.Text = value.ToString();
}
}
private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
if (txtNumRoom == null)
{
return;
}
if (!int.TryParse(txtNumRoom.Text, out _numValue1))
{
txtNumRoom.Text = _numValue1.ToString();
}
}
private void Area_Click(object sender, RoutedEventArgs e)
{
gr3.Visibility = Visibility.Visible;
}
private void Minus_Click1(object sender, RoutedEventArgs e)
{
if (NumValue1 > 0)
{ NumValue1--; }
else NumValue1 = 0;
}
private void Plus_Click1(object sender, RoutedEventArgs e)
{
NumValue1++;
}
private void UpdateHU_Click(object sender, RoutedEventArgs e)
{
if (poolCB.IsChecked == true)
hostingUnit.Pool = true;
else { hostingUnit.Pool = false; }
if (jakouziCB.IsChecked == true)
hostingUnit.Jacuzzi = true;
else { hostingUnit.Jacuzzi = false; }
if (GardenCB.IsChecked == true)
hostingUnit.Garden = true;
else { hostingUnit.Garden = false; }
if (AttractionCB.IsChecked == true)
hostingUnit.ChildrensAttractions = true;
else { hostingUnit.ChildrensAttractions = false; }
if (BreakfastCB.IsChecked == true)
hostingUnit.Breakfast = true;
else { hostingUnit.Breakfast = false; }
if (LunchCB.IsChecked == true)
hostingUnit.Lunch = true;
else { hostingUnit.Lunch = false; }
if (DinnerCB.IsChecked == true)
hostingUnit.Dinner = true;
else { hostingUnit.Dinner = false; }
hostingUnit.Type = (TypesOfVacation)Enum.Parse(typeof(TypesOfVacation), TypeHostingUnitCB.SelectedItem.ToString(), true);
if (button1WasClicked == true)
{
hostingUnit.SubArea = (All)Enum.Parse(typeof(All), SubAreaCB.SelectedItem.ToString(), true);
hostingUnit.Area = (AreasInTheCountry)Enum.Parse(typeof(AreasInTheCountry), AreaCB.SelectedItem.ToString(), true);
}
upd.Visibility = Visibility.Visible;
vi.Visibility = Visibility.Visible;
try
{
hostingUnit.Room = int.Parse(RoomTxt.Text);
bl.UpdateHostingUnitB(hostingUnit);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void RoomTxt_TextChanged(object sender, TextChangedEventArgs e)
{
if (RoomTxt == null)
{
return;
}
if (!int.TryParse(RoomTxt.Text, out _numValue1))
{
RoomTxt.Text = _numValue1.ToString();
}
}
private void AreaCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SubAreaCB.Visibility = Visibility.Visible;
switch (AreaCB.SelectedValue.ToString())
{
case ("הכל"):
SubAreaCB.SelectedItem = "{Binding Path=All,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.All));
break;
case ("ירושלים"):
SubAreaCB.SelectedItem = "{Binding Path=Jerusalem,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.Jerusalem));
break;
case ("צפון"):
SubAreaCB.SelectedItem = "{Binding Path=North,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.North));
break;
case ("דרום"):
SubAreaCB.SelectedItem = "{Binding Path=South,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.South));
break;
case ("מרכז"):
SubAreaCB.SelectedItem = "{Binding Path=Center,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.Center));
break;
}
}
private void SubAreaCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
button1WasClicked = true;
AreaBtn.Content = SubAreaCB.SelectedItem.ToString();
if (SubAreaCB.SelectedItem != null) { gr3.Visibility = Visibility.Collapsed; }
}
private void Room_Button_Click(object sender, RoutedEventArgs e)
{
gr4.Visibility = Visibility.Visible;
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
}
}<file_sep>/Project01_5404_8555_dotNet5780/PL/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
using BL;
namespace PL
{
class Program
{
static void Main(string[] args)
{
// HostingUnit h1 = new HostingUnit()
// {
// Owner = new Host()
// {
// PrivateName = "yael",
// FamilyName = "levi",
// PhoneNumber = 020000001,
// MailAddress = "<EMAIL>",
// BankAccount = new BankBranch() { BankNumber = 111, BankName = Bank_Name.Discont, BranchNumber = 1111, BranchAddress = "beit hadfous 65", BranchCity = "Jerusalem", BankAccountNumber = 123111 },
// CollectionClearance = false
// },
// HostingUnitName = "yael hotel",
// Area = AreasInTheCountry.ירושלים
// };
// HostingUnit h2 = new HostingUnit()
// {
// Owner = new Host()
// {
// PrivateName = "ruthi",
// FamilyName = "cohen",
// PhoneNumber = 02 - 0000055,
// MailAddress = "<EMAIL>",
// BankAccount = new BankBranch() { BankNumber = 222, BankName = Bank_Name.Igood, BranchNumber = 2222, BranchAddress = "kanfey nesharim 3", BranchCity = "Jerusalem", BankAccountNumber = 123222 },
// CollectionClearance = false
// },
// HostingUnitName = "ruthi houses",
// Area = AreasInTheCountry.מרכז
// };
// HostingUnit h3 = new HostingUnit()
// {
// HostingUnitKey = 10000003,
// Owner = new Host()
// {
// HostKey = 200000003,
// PrivateName = "odelia",
// FamilyName = "melloul",
// PhoneNumber = 02 - 0000003,
// MailAddress = "<EMAIL>",
// BankAccount = new BankBranch() { BankNumber = 333, BankName = Bank_Name.Igood, BranchNumber = 3333, BranchAddress = "smilanski 14", BranchCity = "Netanya", BankAccountNumber = 123333 },
// CollectionClearance = true
// },
// HostingUnitName = "odelia's tsimer",
// Area = AreasInTheCountry.ירושלים,
// Adults = 3,
// Pool = true,
// Jacuzzi = false,
// Garden = true
// };
// Order o1 = new Order()
// { HostingUnitKey = 10000001,
// GuestRequestKey = 10000001,
// OrderKey = Configuration.orderKey++,
// Status = OrderStatus.לא_טופל,
// CreateDate = new DateTime(2019, 12,01),
// OrderDate = new DateTime(2019, 12, 12) };
// Order o2 = new Order()
// {
// HostingUnitKey = 10000007,
// GuestRequestKey = 22222223,
// OrderKey = Configuration.orderKey++,
// Status = OrderStatus.נשלח_מייל,
// CreateDate = new DateTime(2019, 08, 02),
// OrderDate = new DateTime(2019, 09, 02)
// };
// GuestRequest g1 = new GuestRequest()
// {
// GuestRequestKey = Configuration.guestRequestKey++,
// PrivateName = "yaniv",
// FamilyName = "ashkenazi",
// MailAddress = "<EMAIL>",
// Status = OrderStatus.נשלח_מייל,
// RegistrationDate = new DateTime(2019, 06, 11),
// EntryDate = new DateTime(2019, 10, 11),
// ReleaseDate = new DateTime(2019, 10, 26),
// Area = AreasInTheCountry.ירושלים,
// SubArea = All.אשקלון,
// Type = TypesOfVacation.מלון,
// Adults = 2,
// Children = 1,
// Pool = ChoosingAttraction.הכרחי,
// Jacuzzi = ChoosingAttraction.אפשרי,
// Garden = ChoosingAttraction.הכרחי,
// ChildrensAttractions = ChoosingAttraction.לא_מעוניין,
// Its_Signed = true,
// Breakfast = true,
// Dinner = false,
// Lunch = true
// };
// BL.IBL bl = BL.FactoryBL.GetBL();
// bl.AddHostingUnitB(h2);
// try
// {
// bl.UpdateHostingUnitB(h3);
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// }
// bl.RemoveHostingUnitB(h3);
// foreach (var item in bl.Get_HostingUnitsListB())
// Console.WriteLine(item.ToString());
// bl.AddGuestRequestB(g1);
// try
// {
// bl.AddOrderB(o1);
// }
// catch (Exception e )
// {
// Console.WriteLine(e.Message);
// }
// try
// {
// bl.OrderChangedB(o2);
// }
// catch (Exception e)
// {
// Console.WriteLine(e.Message);
// }
// foreach (var item in bl.Get_OrdersB())
// Console.WriteLine(item.ToString());
// Console.ReadKey();
}
}
//public static List<GuestRequest> guestRequestsList = new List<GuestRequest>(){new GuestRequest(){GuestRequestKey= Configuration.guestRequestKey,PrivateName="yaniv",FamilyName="ashkenazi",MailAddress="<EMAIL>",Status=OrderStatus.mail_has_been_sent, RegistrationDate= new DateTime(11,06,2019),
// EntryDate= new DateTime(10/11/2019),ReleaseDate= new DateTime (03/26/2019),Area= AreasInTheCountry.Jerusalem,SubArea= "yafo",
// Type= TypesOfVacation.Zimmer,Adults= 2,Children=1,Pool= ChoosingAttraction.necessary,Jacuzzi= ChoosingAttraction.not_interested,
// Garden= ChoosingAttraction.necessary,ChildrensAttractions= ChoosingAttraction.possible, Its_Signed= true,IsApproved= true},
// new GuestRequest() {GuestRequestKey = Configuration.GuestRequestKey,PrivateName = "Sara",FamilyName = "cohen",MailAddress = "<EMAIL>",Status = OrderStatus.Not_treated, RegistrationDate = new DateTime(10, 30, 2019),
// EntryDate = new DateTime(11 / 06 / 2019),ReleaseDate = new DateTime(03 / 26 / 2019),Area = AreasInTheCountry.North,SubArea = "givat shaul",
// Type = TypesOfVacation.Zimmer,Adults = 2,Children = 1,Pool = ChoosingAttraction.necessary,Jacuzzi = ChoosingAttraction.not_interested,
// Garden = ChoosingAttraction.necessary,ChildrensAttractions = ChoosingAttraction.possible,Its_Signed= true,IsApproved = true },
// new GuestRequest() {GuestRequestKey = Configuration.GuestRequestKey,PrivateName = "Haya",FamilyName = "aharonov",MailAddress = "<EMAIL>",Status = OrderStatus.mail_has_been_sent, RegistrationDate = new DateTime(06,11,2019),
// EntryDate = new DateTime(03/22/2019),ReleaseDate =new DateTime (03/26/2019),Area = AreasInTheCountry.North,SubArea = "Tveria",
// Type = TypesOfVacation.Camping,Adults = 2,Children = 2,Pool =ChoosingAttraction.not_interested,Jacuzzi = ChoosingAttraction.not_interested,
// Garden = ChoosingAttraction.necessary,ChildrensAttractions = ChoosingAttraction.possible,Its_Signed= false,IsApproved = true }
//};
}
//כאשר נשלח לעדכון יחידה שאינה קיימת נזרקה שגיאה
//Unhandled Exception: System.Collections.Generic.KeyNotFoundException: יחידת האירוח שאותה אנו רוצים לעדכן אינה קיימת
// at DAL.Dal_imp.UpdateHostingUnit(HostingUnit T) in Z:\שנה ג'\c#\Project\BE\DAL\Dal_imp.cs:line 21
// at BL.BL_imp.UpdateHostingUnitB(HostingUnit T) in Z:\שנה ג'\c#\Project\BE\BL\BL_imp.cs:line 339
// at PL.Program.Main(String[] args) in Z:\שנה ג'\c#\Project\BE\PL\Program.cs:line 63
// הרצה של הוספה ועדכון של host unit
//Hosting Unit Key:10000001
//Owner: Host Key: 200000001
//Name: <NAME>
//Fhone Number: 20000001
//Mail: <EMAIL>
// Bank Account: Bank Number: 111
//Bank Name: Discont
//Branch Number: 1111
//Branch Address: beit hadfous 65
// Branch City: Jerusalem
//Bank Account Number:123111
//Collection Clearance:False
//Hosting Unit Name:yael hotel
//Hosting Unit Area:Jerusalem/nHosting Unit Adults:2
//Hosting Unit Children:1
//Hosting Unit Pool:necessary
//Hosting Unit Jacuzzi:possible
//Hosting UnitGarden:possible
//Hosting Unit Area:necessary
// Hosting Unit Key:10000002
//Owner: Host Key: 200000002
//Name: <NAME>
//Fhone Number: 0
//Mail: <EMAIL>
// Bank Account: Bank Number: 222
//Bank Name: Igood
//Branch Number: 2222
//Branch Address: kanfey nesharim 3
// Branch City: Jerusalem
//Bank Account Number:123222
//Collection Clearance:True
//Hosting Unit Name:ruthi houses
//Hosting Unit Area:Jerusalem/nHosting Unit Adults:4
//Hosting Unit Children:3
//Hosting Unit Pool:not_interested
//Hosting Unit Jacuzzi:possible
//Hosting UnitGarden:possible
//Hosting Unit Area:not_interested
// Hosting Unit Key:10000003
//Owner: Host Key: 200000003
//Name: <NAME>
//Fhone Number: -1
//Mail: <EMAIL>
// Bank Account: Bank Number: 333
//Bank Name: Igood
//Branch Number: 3333
//Branch Address: smilanski 14
// Branch City: Netanya
//Bank Account Number:123333
//Collection Clearance:False
//Hosting Unit Name:odelia's tsimer
//Hosting Unit Area:Center/nHosting Unit Adults:3
//Hosting Unit Children:0
//Hosting Unit Pool:necessary
//Hosting Unit Jacuzzi:possible
//Hosting UnitGarden:possible
//Hosting Unit Area:necessary
// Hosting Unit Key:10000004
//Owner: Host Key: 0
//Name: <NAME>
//Fhone Number: -53
//Mail: <EMAIL>
// Bank Account: Bank Number: 222
//Bank Name: Igood
//Branch Number: 2222
//Branch Address: kanfey nesharim 3
// Branch City: Jerusalem
//Bank Account Number:123222
//Collection Clearance:False
//Hosting Unit Name:ruthi houses
//Hosting Unit Area:Jerusalem/nHosting Unit Adults:0
//Hosting Unit Children:0
//Hosting Unit Pool:necessary
//Hosting Unit Jacuzzi:necessary
//Hosting UnitGarden:necessary
//Hosting Unit Area:necessary
//Unhandled Exception: System.Exception: לא ניתן למחוק יחידת אירוח כל עוד יש הצעה הקשורה אליה במצב פתוח
// at BL.BL_imp.RemoveHostingUnitB(HostingUnit H) in Z:\שנה ג'\c#\Project\BE\BL\BL_imp.cs:line 130
// at PL.Program.Main(String[] args) in Z:\שנה ג'\c#\Project\BE\PL\Program.cs:line 71
//Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
// at BL.BL_imp.AvailableDate(HostingUnit T, GuestRequest F) in Z:\שנה ג'\c#\Project\BE\BL\BL_imp.cs:line 51
// at BL.BL_imp.AddOrderB(Order O) in Z:\שנה ג'\c#\Project\BE\BL\BL_imp.cs:line 323
// at PL.Program.Main(String[] args) in Z:\שנה ג'\c#\Project\BE\PL\Program.cs:line 90<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/UpdateOrder.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BL;
using BE;
namespace PLWPF
{
/// <summary>
/// Interaction logic for UpdateOrder.xaml
/// </summary>
public partial class UpdateOrder : Window
{
BL.IBL bl;
Host host;
HostingUnit hostingUnit;
IEnumerable<Order> orders;
public UpdateOrder(Host h)
{
host = h;
InitializeComponent();
NavigationService.NavigationStack.Push(this);
bl = BL.FactoryBL.GetBL();
IEnumerable<string> nameHu = bl.NameOfUnit(host);
this.NameHu.ItemsSource = nameHu;
}
private void NameHuCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
hostingUnit = bl.Host_ToHostingUnit(host, NameHu.SelectedItem.ToString());
orders = bl.UnitToOrder(hostingUnit);
ListView_GR.ItemsSource = orders;
}
private void MouseDoubleClick_ListView_GR(object sender, RoutedEventArgs e)
{
if (((ListView)sender).SelectedItem != null)
{
Order o = new Order();
o = ((ListView)sender).SelectedItem as Order;
GetStatusOrder WIN = new GetStatusOrder(host,o);
WIN.Show();
}
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void ListView_GR_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/GetHuName.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for GetHuName.xaml
/// </summary>
///
public partial class GetHuName : Window
{
BL.IBL bl;
Host host = new Host();
GuestRequest guestRequest = new GuestRequest();
HostingUnit hostingUnit = new HostingUnit();
Order order;
public GetHuName(Host H,GuestRequest g)
{
bl = BL.FactoryBL.GetBL();
host = H;
guestRequest = g;
order = new Order();
InitializeComponent();
NavigationService.NavigationStack.Push(this);
IEnumerable<string> nameHu = bl.NameOfUnit(host);
this.NameHu.ItemsSource = nameHu;
}
private void NameHuCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void Add_btn_Click(object sender, RoutedEventArgs e)
{
hostingUnit = bl.Host_ToHostingUnit(host, NameHu.SelectedItem.ToString());
order.HostingUnitKey = hostingUnit.HostingUnitKey;
order.GuestRequestKey = guestRequest.GuestRequestKey;
order.CreateDate = DateTime.Now;
order.Status = OrderStatus.לא_טופל;
try
{
bl.sumAdult(guestRequest, hostingUnit);
bl.sumAdult(guestRequest, hostingUnit);
if (guestRequest.SubArea != All.הכל)
if (hostingUnit.SubArea != guestRequest.SubArea)
throw new KeyNotFoundException("האזור של היחידת האירוח אינו תואם לאיזור דרישת הלקוח");
bl.AddOrderB(host, order);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
this.Close();
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/Project01_5404_8555_dotNet5780/BE/HostingUnit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public class HostingUnit : IClonable
{
private int hostingUnitKey;
public int HostingUnitKey { get => hostingUnitKey; set => hostingUnitKey = value; }
private Host owner;
public Host Owner { get => owner; set => owner = value; }
private string hostingUnitName;
public string HostingUnitName { get => hostingUnitName; set => hostingUnitName = value; }
private All subArea;
public All SubArea { get => subArea; set => subArea = value; }
private AreasInTheCountry area;
public AreasInTheCountry Area { get => area; set => area = value; }
private bool[,] diary = new bool[32, 13];
public bool[,] Diary { get => diary;set => diary= value; }
private int adults;
public int Adults { get => adults; set => adults = value; }
private int children;
public int Children { get => children; set => children = value; }
private bool pool;
public bool Pool { get => pool; set => pool = value; }
private bool jacuzzi;
public bool Jacuzzi { get => jacuzzi; set => jacuzzi = value; }
private bool garden;
public bool Garden { get => garden; set => garden = value; }
private bool childrensAttractions;
public bool ChildrensAttractions { get => childrensAttractions; set => childrensAttractions = value; }
private int room;
public int Room { get => room; set => room = value; }
private TypesOfVacation type;
public TypesOfVacation Type { get => type; set => type = value; }
private bool breakfast;
public bool Breakfast { get => breakfast; set => breakfast = value; }
private bool lunch;
public bool Lunch { get => lunch; set => lunch = value; }
private bool dinner;
public bool Dinner { get => dinner; set => dinner = value; }
public override string ToString()
{
string HostingUnit=" ";
return HostingUnit += string.Format("Hosting Unit Key:{0}\n" + " -Owner:\n"+"{1}\n" + "Hosting Unit Name:{2}\n" + "Hosting Unit Area:{3}\n" + "Hosting Unit Adults:{4}\n" + "Hosting Unit Children:{5}\n" + "Hosting Unit Pool:{6}\n" +
"Hosting Unit Jacuzzi:{7}\n" + "Hosting UnitGarden:{8}\n" + "Hosting Unit Area:{9}\n", HostingUnitKey, Owner, HostingUnitName, Area, Adults,children,pool,jacuzzi,Garden,ChildrensAttractions);
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BL/IBL.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
namespace BL
{
public interface IBL
{
void CheckSumDay(GuestRequest guest);
// void Signed_bank_debit_authoization(GuestRequest x);
bool AvailableDate(HostingUnit T, GuestRequest F);
void BusyDate(Order O);
void CheckStatus(Order O);
int StatusDone(Order O);
void StatusChange(Order o);
void SendMail(Host H,GuestRequest guest);
bool AvailableUnit(DateTime Entry, int sumDay);
int CalculateDate(DateTime firstDate, DateTime secondDate);
IEnumerable<IGrouping<AreasInTheCountry, GuestRequest>> VacationArea();
IEnumerable<IGrouping<int, GuestRequest>> SumOfVacationers();
IEnumerable<IGrouping<int, Host>> SumOfHostingunit();
IEnumerable<IGrouping<AreasInTheCountry, HostingUnit>> RegionOfUnit();
Host CheckId(int id);
List<HostingUnit> FindHostingUnit(int id);
IEnumerable< string> NameOfUnit(Host HO);
IEnumerable<GuestRequest> Condition_Guest_Request1(Predicate<GuestRequest> conditions, IEnumerable<GuestRequest> g);
IEnumerable<GuestRequest> Condition_Guest_Request2(Func< GuestRequest, bool> conditions, IEnumerable<GuestRequest> g);
bool PoolT(GuestRequest g);
bool PoolF(GuestRequest g);
bool GardenT(GuestRequest g);
bool GardenF(GuestRequest g);
bool jakuzziT(GuestRequest g);
bool jakuzziF(GuestRequest g);
bool AttractionT(GuestRequest g);
bool AttractionF(GuestRequest g);
bool Breakfast(GuestRequest g);
bool Lunch(GuestRequest g);
bool Dinner(GuestRequest g);
bool Type(GuestRequest g, TypesOfVacation a);
bool SubArea(GuestRequest g, All a);
//IDAL
void AddGuestRequestB(GuestRequest T);
void AddOrderB(Host H, Order T);
void AddHostingUnitB(HostingUnit T);
void AddHostB(Host T);
void RemoveHostingUnitB(HostingUnit H);
void UpdateGuestRequestB(GuestRequest T);
void UpdateHostingUnitB(HostingUnit T);
void OrderChangedB(Host H,Order T);
IEnumerable<HostingUnit> Get_HostingUnitsListB();
IEnumerable<GuestRequest> Get_GuestRequestListB();
IEnumerable<Order> Get_OrdersB();
IEnumerable<BankBranch> Brunch_bankB();
// HostingUnit
HostingUnit Host_ToHostingUnit(Host h, string name);
IEnumerable<Order> UnitToOrder(HostingUnit H);
string KeyToNameHu(int key);
string KeyToNameGR(int key);
void sumAdult(GuestRequest g, HostingUnit H);
void sumChilds(GuestRequest g, HostingUnit H);
//SiteOwner
IEnumerable<GuestRequest> CloseGR();
IEnumerable<GuestRequest> NoTreat();
IEnumerable<GuestRequest> MailwasSent();
IEnumerable<HostingUnit> AvailableUnitList(DateTime Entry, int sumDay);
IEnumerable<HostingUnit> BusyUnitList(DateTime Entry, int sumDay);
IEnumerable<Host> Get_Host();
IEnumerable<Order> pagTokef();
void Accumulation(int t);
int Accumulation();
int updatepasswords();
IEnumerable<BankBranch> ListOfBanks(string searchString);
}
}
<file_sep>/Project01_5404_8555_dotNet5780/Project01_5404_8555_dotNet5780/BE/Configuration.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public class Configuration
{
public static int guestRequestKey=10000000;
public static int hostingUnitKey = 10000000;
public static int orderKey = 20000000;
public static int orderValidity = 5;
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/DeleteHostingUnit.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for DeleteHostingUnit.xaml
/// GuestRequest guestRequest;
/// </summary>
public partial class DeleteHostingUnit : Window
{
//GuestRequest ;
BL.IBL bl;
Host host = new Host();
public DeleteHostingUnit(Host H)
{
bl = BL.FactoryBL.GetBL();
host = H;
this.DataContext = host;
InitializeComponent();
NavigationService.NavigationStack.Push(this);
IEnumerable<string> nameHu = bl.NameOfUnit(host);
this.NameHu.ItemsSource = nameHu;
InitializeComponent();
}
private void DeleteBtn_Click(object sender, RoutedEventArgs e)
{
try
{
bl.RemoveHostingUnitB(bl.Host_ToHostingUnit(host, NameHu.SelectedItem.ToString()));
MessageBox.Show($" היחידת אירוח נמחקה בהצלחה ", " מחיקת יחידת אירוח", MessageBoxButton.OK, MessageBoxImage.None);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/AddGR.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
using System.Windows.Interop;
namespace PLWPF
{
/// <summary>
/// Interaction logic for AddGR.xaml
/// </summary>
public partial class AddGR : Window
{
GuestRequest guestRequest;
BL.IBL bl;
public AddGR()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
bl = BL.FactoryBL.GetBL();
guestRequest = new GuestRequest();
this.poolCB.ItemsSource = Enum.GetValues(typeof(BE.ChoosingAttraction));
this.jakouziCB.ItemsSource = Enum.GetValues(typeof(BE.ChoosingAttraction));
this.GardenCB.ItemsSource = Enum.GetValues(typeof(BE.ChoosingAttraction));
this.attractionCB.ItemsSource = Enum.GetValues(typeof(BE.ChoosingAttraction));
this.TypeHostingUnitCB.ItemsSource = Enum.GetValues(typeof(BE.TypesOfVacation));
this.AreaCB.ItemsSource = Enum.GetValues(typeof(BE.AreasInTheCountry));
}
public void Button_Click_Add(object sender, RoutedEventArgs e)
{
if (poolCB.SelectedItem == null || jakouziCB.SelectedItem == null || GardenCB.SelectedItem == null ||
attractionCB.SelectedItem == null || TypeHostingUnitCB == null)
{
MessageBox.Show($" עליך לבחור את כל האפשרויות ", "Guest Request", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
try
{
if ((id.Text).Length != 9)
{
id.BorderBrush = Brushes.Red;
IDlabel.Content = "הכנס ת.ז בעלת 9 תווים";
IDlabel.BorderBrush = Brushes.Red;
return;
}
if (PN.Text == "")
{
PN.BorderBrush = Brushes.Red;
PnLabel.Content = "הכנס שם פרטי";
PnLabel.BorderBrush = Brushes.Red;
return;
}
if (FN.Text == "")
{
FN.BorderBrush = Brushes.Red;
FnLabel.Content = "הכנס שם משפחה";
FnLabel.BorderBrush = Brushes.Red;
return;
}
if (int.Parse(txtNumAdult.Text) < 1)
{
FamilyTxt.BorderBrush = Brushes.Red;
return;
}
if (int.Parse(txtNumRoom.Text) < 1)
{
RoomTxt.BorderBrush = Brushes.Red;
return;
}
if (BreakfastCB.IsChecked == true)
guestRequest.Breakfast = true;
else
{ guestRequest.Breakfast = false; }
if (LunchCB.IsChecked == true)
guestRequest.Lunch = true;
else
{ guestRequest.Lunch = false; }
if (DinnerCB.IsChecked == true)
guestRequest.Dinner = true;
else
{ guestRequest.Dinner = false; }
guestRequest.Status = OrderStatus.לא_טופל;
guestRequest.RegistrationDate = DateTime.Now;
guestRequest.Pool = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), poolCB.SelectedItem.ToString(), true);
guestRequest.Jacuzzi = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), jakouziCB.SelectedItem.ToString(), true);
guestRequest.Garden = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), GardenCB.SelectedItem.ToString(), true);
guestRequest.ChildrensAttractions = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), attractionCB.SelectedItem.ToString(), true);
guestRequest.Type = (TypesOfVacation)Enum.Parse(typeof(TypesOfVacation), TypeHostingUnitCB.SelectedItem.ToString(), true);
guestRequest.SubArea = Subarea();
guestRequest.Area = (AreasInTheCountry)Enum.Parse(typeof(AreasInTheCountry), AreaCB.SelectedItem.ToString(), true);
guestRequest.FamilyName = FN.Text;
guestRequest.PrivateName = PN.Text;
guestRequest.MailAddress = Email.Text;
guestRequest.EntryDate = EntryDateDP.SelectedDate.Value.Date;
guestRequest.ReleaseDate = RealeseDateDP.SelectedDate.Value.Date;
guestRequest.ID = int.Parse(id.Text);
guestRequest.Adults = int.Parse(txtNumAdult.Text);
guestRequest.Children = int.Parse(txtNumChild.Text);
guestRequest.Room = int.Parse(RoomTxt.Text);
bl.AddGuestRequestB(guestRequest);
vi.Visibility = Visibility.Visible;
addlable.Visibility = Visibility.Visible;
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
#region
private int _numValue1 = 0;
public int NumValue1
{
get { return _numValue1; }
set
{
_numValue1 = value;
txtNumRoom.Text = value.ToString();
RoomTxt.Text = value.ToString();
}
}
private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
if (txtNumRoom == null)
{
return;
}
if (!int.TryParse(txtNumRoom.Text, out _numValue1))
{
txtNumRoom.Text = _numValue1.ToString();
}
}
private void RoomTxt_TextChanged(object sender, TextChangedEventArgs e)
{
if (RoomTxt == null)
{
return;
}
if (!int.TryParse(RoomTxt.Text, out _numValue1))
{
RoomTxt.Text = _numValue1.ToString();
}
}
private void Minus_Click1(object sender, RoutedEventArgs e)
{
if (NumValue1 > 0)
{ NumValue1--; }
else NumValue1 = 0;
}
private void Plus_Click1(object sender, RoutedEventArgs e)
{
NumValue1++;
}
#endregion
#region
private int _numValue2 = 0;
public int NumValue2
{
get { return _numValue2; }
set
{
_numValue2 = value;
txtNumAdult.Text = _numValue2.ToString();
int x = value + _numValue3;
FamilyTxt.Text = x.ToString();
}
}
private void TextBox_TextChanged_2(object sender, TextChangedEventArgs e)
{
if (txtNumAdult == null)
{
return;
}
if (!int.TryParse(txtNumAdult.Text, out _numValue2))
txtNumAdult.Text = _numValue2.ToString();
}
private void Minus_Click2(object sender, RoutedEventArgs e)
{
if (NumValue2 > 0)
{ NumValue2--; }
else NumValue2 = 0;
}
private void Plus_Click2(object sender, RoutedEventArgs e)
{
NumValue2++;
}
#endregion
#region
private int _numValue3 = 0;
public int NumValue3
{
get { return _numValue3; }
set
{
_numValue3 = value;
txtNumChild.Text = _numValue3.ToString();
int x = value + _numValue2;
FamilyTxt.Text = x.ToString();
}
}
private void TextBox_TextChanged_3(object sender, TextChangedEventArgs e)
{
if (txtNumChild == null)
{
return;
}
if (!int.TryParse(txtNumChild.Text, out _numValue3))
txtNumChild.Text = _numValue3.ToString();
}
private void Minus_Click3(object sender, RoutedEventArgs e)
{
if (NumValue3 > 0)
{ NumValue3--; }
else NumValue3 = 0;
}
private void Plus_Click3(object sender, RoutedEventArgs e)
{
NumValue3++;
}
#endregion
private void SubAreaCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AreaBtn.Content= SubAreaCB.SelectedItem.ToString();
if (SubAreaCB.SelectedItem != null) { gr3.Visibility = Visibility.Collapsed; }
}
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
}
private void ComboBox_SelectionChanged_2(object sender, SelectionChangedEventArgs e)
{
}
private void ComboBox_SelectionChanged_3(object sender, SelectionChangedEventArgs e)
{
}
private void ComboBox_SelectionChanged_4(object sender, SelectionChangedEventArgs e)
{
}
private void Got_Focus_PN(object sender, RoutedEventArgs e)
{
PnLabel.Content = "";
PN.BorderBrush = Brushes.Black;
}
private void Got_Focus_FN(object sender, RoutedEventArgs e)
{
FnLabel.Content = "";
FN.BorderBrush = Brushes.Black;
}
private void Got_Focus_Mail(object sender, RoutedEventArgs e)
{
MailLabel.Content = "";
Email.BorderBrush = Brushes.Black;
}
private void Id_GotFocus(object sender, RoutedEventArgs e)
{
IDlabel.Content = "";
id.BorderBrush = Brushes.Black;
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void PN_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void AreaCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SubAreaCB.Visibility = Visibility.Visible;
switch (AreaCB.SelectedValue.ToString()) {
case ("הכל"):
SubAreaCB.SelectedItem = "{Binding Path=All,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.All));
break;
case ("ירושלים"):
SubAreaCB.SelectedItem = "{Binding Path=Jerusalem,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.Jerusalem));
break;
case ("צפון"):
SubAreaCB.SelectedItem = "{Binding Path=North,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.North));
break;
case ("דרום"):
SubAreaCB.SelectedItem = "{Binding Path=South,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.South));
break;
case ("מרכז"):
SubAreaCB.SelectedItem = "{Binding Path=Center,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.Center));
break;
}
}
private All Subarea()
{
switch (AreaCB.SelectedValue.ToString())
{
case ("הכל"):
SubAreaCB.SelectedItem = "{Binding Path=All,Mode=TwoWay}";
this.SubAreaCB.ItemsSource = Enum.GetValues(typeof(BE.All));
break;
case ("ירושלים"):
if (SubAreaCB.SelectedValue.ToString() == "בית_וגן")
return All.בית_וגן;
if (SubAreaCB.SelectedValue.ToString() == "מרכז_העיר")
return All.מרכז_העיר;
if (SubAreaCB.SelectedValue.ToString() == "תלפיות")
return All.תלפיות;
if (SubAreaCB.SelectedValue.ToString() == "גילו")
return All.גילו;
if (SubAreaCB.SelectedValue.ToString() == "העיר_העתיקה")
return All.העיר_העתיקה;
if (SubAreaCB.SelectedValue.ToString() == "מרכז_העיר")
return All.מרכז_העיר;
if (SubAreaCB.SelectedValue.ToString() == "הכל")
return All.ירושלים;
break;
case ("צפון"):
if (SubAreaCB.SelectedValue.ToString() == "קיריית_שמונה")
return All.קיריית_שמונה;
if (SubAreaCB.SelectedValue.ToString() == "גליל_עליון")
return All.גליל_עליון;
if (SubAreaCB.SelectedValue.ToString() == "כרמיאל")
return All.כרמיאל;
if (SubAreaCB.SelectedValue.ToString() == "צפת")
return All.צפת;
if (SubAreaCB.SelectedValue.ToString() == "עפולה")
return All.עפולה;
if (SubAreaCB.SelectedValue.ToString() == "בית_שאן")
return All.בית_שאן;
if (SubAreaCB.SelectedValue.ToString() == "נהריה")
return All.נהריה;
if (SubAreaCB.SelectedValue.ToString() == "הכל")
return All.צפון;
break;
case ("דרום"):
if (SubAreaCB.SelectedValue.ToString() == "נתיבות")
return All.נתיבות;
if (SubAreaCB.SelectedValue.ToString() == "קריית_גת")
return All.קריית_גת;
if (SubAreaCB.SelectedValue.ToString() == "ערד")
return All.ערד;
if (SubAreaCB.SelectedValue.ToString() == "אופקים")
return All.אופקים;
if (SubAreaCB.SelectedValue.ToString() == "אשקלון")
return All.אשקלון;
if (SubAreaCB.SelectedValue.ToString() == "אשדוד")
return All.אשדוד;
if (SubAreaCB.SelectedValue.ToString() == "באר_שבע")
return All.באר_שבע;
if (SubAreaCB.SelectedValue.ToString() == "אילת")
return All.אילת;
if (SubAreaCB.SelectedValue.ToString() == "הכל")
return All.דרום;
break;
case ("מרכז"):
if (SubAreaCB.SelectedValue.ToString() == "ראשון_לציון")
return All.ראשון_לציון;
if (SubAreaCB.SelectedValue.ToString() == "גיבעתיים")
return All.גיבעתיים;
if (SubAreaCB.SelectedValue.ToString() == "אור_יהודה")
return All.אור_יהודה;
if (SubAreaCB.SelectedValue.ToString() == "פתח_תקווה")
return All.פתח_תקווה;
if (SubAreaCB.SelectedValue.ToString() == "נתניה")
return All.נתניה;
if (SubAreaCB.SelectedValue.ToString() == "אשדוד")
return All.אשדוד;
if (SubAreaCB.SelectedValue.ToString() == "קיריית_אונו")
return All.קיריית_אונו;
if (SubAreaCB.SelectedValue.ToString() == "רמת_גן")
return All.רמת_גן;
if (SubAreaCB.SelectedValue.ToString() == "תל_אביב")
return All.תל_אביב;
if (SubAreaCB.SelectedValue.ToString() == "הכל")
return All.מרכז;
break;
}
return All.הכל;
}
private void FamilyBtn_Click(object sender, RoutedEventArgs e)
{
gr2.Visibility = Visibility.Visible;
}
private void Date_Click(object sender, RoutedEventArgs e)
{
gr5.Visibility = Visibility.Visible;
}
private void Area_Click(object sender, RoutedEventArgs e)
{
gr3.Visibility = Visibility.Visible;
}
private void Room_Button_Click(object sender, RoutedEventArgs e)
{
gr4.Visibility = Visibility.Visible;
}
private void RealeseDateChanged(object sender, RoutedEventArgs e)
{
TxtDateOut.Text = RealeseDateDP.SelectedDate.Value.Date.ToString();
TimeSpan x = RealeseDateDP.SelectedDate.Value.Date - EntryDateDP.SelectedDate.Value.Date;
calendarTxt.Text = x.Days.ToString();
if (RealeseDateDP.SelectedDate != null && EntryDateDP.SelectedDate != null)
gr5.Visibility = Visibility.Collapsed;
}
private void EntryDateChanged(object sender, RoutedEventArgs e)
{
TxtDateIn.Text = EntryDateDP.SelectedDate.Value.Date.ToString();
if (RealeseDateDP.SelectedDate != null && EntryDateDP.SelectedDate != null)
gr5.Visibility = Visibility.Collapsed;
}
private void gr4_MouseLeave(object sender, RoutedEventArgs e)
{
gr4.Visibility = Visibility.Collapsed;
}
private void gr2_MouseLeave(object sender, RoutedEventArgs e)
{
gr2.Visibility = Visibility.Collapsed;
}
private void id_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/SiteOwner.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;
using System.Net.Mail;
using BE;
using BL;
using System.Timers;
using System.Threading;
namespace PLWPF
{
/// <summary>
/// Interaction logic for SiteOwner.xaml
/// </summary>
public partial class SiteOwner : Window
{
BL.IBL bl;
public SiteOwner()
{
InitializeComponent();
//Thread T = new Thread(updetListOrders);
//T.Start();
bl = BL.FactoryBL.GetBL();
NavigationService.NavigationStack.Push(this);
SiteOwner1.Passwords = Configuration.passwords;
}
private void Button_Click_Enter(object sender, RoutedEventArgs e)
{
if(PSW.Password== Site<PASSWORD>s.ToString())
GrSO.Visibility = Visibility.Visible;
else
MessageBox.Show($"הסיסמא שהוקשה אינה תקינה אנה נסה שנית ", "בעל האתר", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
private void Btn_GR_Click(object sender, RoutedEventArgs e)
{
LinqGR win = new LinqGR();
win.Show();
this.Visibility = Visibility.Collapsed;
}
private void BtnHU_Button_Click(object sender, RoutedEventArgs e)
{
LinqHu win = new LinqHu();
win.Show();
this.Visibility = Visibility.Collapsed;
}
private void BtnHost_Button_Click(object sender, RoutedEventArgs e)
{
LinqHost win = new LinqHost();
win.Show();
this.Visibility = Visibility.Collapsed;
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void ForgetPsw_Click(object sender, RoutedEventArgs e)
{
Random rnd = new Random();
Configuration.passwords = rnd.Next(100000001, 1000000000);
SiteOwner1.Passwords = Configuration.passwords;
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.To.Add("<EMAIL>");
mail.From = new MailAddress("<EMAIL>");
mail.Subject = "סיסמא חדשה לאתר";
mail.IsBodyHtml = false;
mail.Body = SiteOwner1.Passwords.ToString();
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.Credentials = new System.Net.NetworkCredential("<EMAIL>", "308508rc");
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
MessageBox.Show($"סיסמתך החדשה נישלחה אליך למייל בהצלחה", "Site Owner", MessageBoxButton.OK, MessageBoxImage.None);
bl.updatepasswords();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/////
//private void updetListOrders()
//{
// while (true)
// {
// OrderDailyMethod();
// ReqDailyMethod();
// Thread.Sleep(86400000);//24 שעות
// }
//}
//private void ReqDailyMethod()
//{
// IEnumerable<GuestRequest> listOfreq = bl.DaysPassedOnReq(31);
// List<GuestRequest> g = new List<GuestRequest>();
// foreach (GuestRequest o in listOfreq)
// {
// g.Add(o);
// }
// g.ForEach(element => element.Status = Status.Closed);
// g.ForEach(element => bl.Updategr(element));
//}
//private void OrderDailyMethod()
//{
// IEnumerable<Order> listOfOrder = bl.DaysPassedOnOrders(31);
// List<Order> ord = new List<Order>();
// foreach (Order o in listOfOrder)
// {
// ord.Add(o);
// }
// ord.ForEach(element => element.Status = OrderStatus.נסגרה_עסקה);
// ord.ForEach(element =>bl.UpdateOrder(element));
//}
private void commision_Button_Click(object sender, RoutedEventArgs e)
{
btn_commition.Content =bl.Accumulation();
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/LinqGR.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for LinqGR.xaml
/// </summary>
public partial class LinqGR : Window
{
BL.IBL bl;
public LinqGR()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
bl = BL.FactoryBL.GetBL();
}
private void Close_Button_Click(object sender, RoutedEventArgs e)
{
ListView_GR.ItemsSource = bl.CloseGR();
}
private void NotTreated_Button_Click(object sender, RoutedEventArgs e)
{
ListView_GR.ItemsSource = bl.NoTreat();
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void MailHasSent_Click(object sender, RoutedEventArgs e)
{
ListView_GR.ItemsSource = bl.MailwasSent();
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/Feedback.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace PLWPF
{
/// <summary>
/// Interaction logic for feedback.xaml
/// </summary>
public partial class Feedback : Window
{
public Feedback()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.To.Add("<EMAIL>");
mail.From = new MailAddress("<EMAIL>");
mail.Subject = "סיסמא חדשה לאתר";
mail.IsBodyHtml = false;
mail.Body = txt.Text.ToString() + "הערות לאתר";
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.Credentials = new System.Net.NetworkCredential("<EMAIL>", "308508rc");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
vi.Visibility = Visibility.Visible;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BE/Order.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public class Order : IClonable
{
private int hostingUnitKey;
public int HostingUnitKey { get => hostingUnitKey; set => hostingUnitKey = value; }
private int guestRequestKey;
public int GuestRequestKey { get => guestRequestKey; set => guestRequestKey = value; }
private int orderKey;
public int OrderKey { get => orderKey; set => orderKey = Configuration.orderKey++; }
private OrderStatus status;
public OrderStatus Status { get => status; set => status = value; }
private DateTime createDate;
public DateTime CreateDate { get => createDate; set => createDate = value; }
private DateTime orderDate;
public DateTime OrderDate { get => orderDate; set => orderDate = value; }
public override string ToString()
{
string order = " ";
return order += string.Format("KeHosting Unit Key: {0}\n" + "KeHosting Unit Key: {1}\n" + "Order Key: {2}\n" + "Status: {3}\n" + "Create Date: {4}\n" + "Order Date:{5}\n",
HostingUnitKey, GuestRequestKey, OrderKey, Status, CreateDate, OrderDate);
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/DAL/Dal_imp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using BE;
using DS;
namespace DAL
{
//public class Dal_imp : IDAL
//{
// public void AddHostingUnit(HostingUnit T)
// {
// T.HostingUnitKey = Configuration.hostingUnitKey++;
// var v = from item in Get_HostingUnitsList()
// where item.HostingUnitName == T.HostingUnitName && item.Owner.HostKey == T.Owner.HostKey
// select item;
// foreach (var item in v)
// if (v != null)
// throw new KeyNotFoundException("שם יחידת האירוח כבר קיימת במערכת בחר שם אחר");
// //T.DiaryDto = new bool[32, 13];
// //for (int j = 0; j < 13; j++)
// //{
// // for (int i = 0; i < 32; i++)
// // T.Diary[i, j] =false;
// //}
// DataSource.hostingUnitList.Add(T);
// }
// public void UpdateHostingUnit(HostingUnit T)
// {
// var v = DataSource.hostingUnitList.FirstOrDefault(X => X.HostingUnitKey == T.HostingUnitKey);
// if (v == null)
// throw new KeyNotFoundException(" יחידת האירוח שאותה אנו רוצים לעדכן אינה קיימת");
// DataSource.hostingUnitList.Remove(v);
// DataSource.hostingUnitList.Add(T);
// }
// public void DeleteHostingUnit(HostingUnit T)
// {
// var v = from item in DataSource.hostingUnitList
// where item.HostingUnitKey == T.HostingUnitKey
// select item.Clone();
// if (v != null)
// DataSource.hostingUnitList.Remove(T);
// else throw new KeyNotFoundException("יחידת האירוח למחיקה אינה קיימת");
// }
// public void AddOrder(Order T)
// {
// T.OrderKey = Configuration.orderKey++;
// DataSource.ordersList.Add(T);
// }
// public void OrderChanged(Order T)
// {
// var v = DataSource.ordersList.FirstOrDefault(X => X.OrderKey == T.OrderKey);
// if (v == null)
// throw new KeyNotFoundException(" הזמנה שאותה אנו רוצים לעדכן אינה קיימת");
// DataSource.ordersList.Remove(v);
// DataSource.ordersList.Add(T);
// }
// public void AddGuestRequest(GuestRequest T)
// {
// T.GuestRequestKey = Configuration.guestRequestKey++;
// DataSource.guestRequestsList.Add(T);
// }
// public void UpdateGuestRequest(GuestRequest T)
// {
// var v = DataSource.guestRequestsList.FirstOrDefault(X => X.GuestRequestKey == T.GuestRequestKey);
// if (v == null)
// throw new KeyNotFoundException(" יחידת האירוח שאותה אנו רוצים לעדכן אינה קיימת");
// DataSource.guestRequestsList.Remove(v);
// DataSource.guestRequestsList.Add(T);
// }
// public IEnumerable<HostingUnit> Get_HostingUnitsList()
// {
// return from item in DataSource.hostingUnitList
// select item.Clone();
// }
// public IEnumerable<GuestRequest> Get_GuestRequestList()
// {
// return from item in DataSource.guestRequestsList
// select item.Clone();
// }
// public IEnumerable<Order> Get_Orders()
// {
// return from item in DataSource.ordersList
// select item.Clone();
// }
// public IEnumerable<BankBranch> GetBrunch_bank()
// {
// return from item in DataSource.hostingUnitList
// select item.Owner.BankAccount;
// }
// public IEnumerable<Host> Get_HostList()
// {
// return from item in DataSource.hostList
// select item.Clone();
// }
// public GuestRequest FindGR(int ID)
// {
// var v = from item in DataSource.guestRequestsList
// where item.GuestRequestKey == ID
// select item;
// return v.FirstOrDefault();
// }
// public void AddHost(Host Ho) { }
// public void updateaccumulation(int co)
// {
// }
// public void updatepasswords(int co)
// {
// }
// public int Get_commission()
// {
// return 0;
// }
// public int Get_passwords()
// {
// return 0;
// }
// public int Get_accumulation()
// {
// return 0;
// }
//}
}
<file_sep>/Project01_5404_8555_dotNet5780/BE/HostingUnit.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace BE
{
public class HostingUnit : IClonable
{
private int hostingUnitKey;
public int HostingUnitKey { get => hostingUnitKey; set => hostingUnitKey = value; }
private Host owner;
public Host Owner { get => owner; set => owner = value; }
private string hostingUnitName;
public string HostingUnitName { get => hostingUnitName; set => hostingUnitName = value; }
private All subArea;
public All SubArea { get => subArea; set => subArea = value; }
private AreasInTheCountry area;
public AreasInTheCountry Area { get => area; set => area = value; }
// tell the XmlSerializer to ignore this Property.
[XmlIgnore]
public bool[,] Diary = new bool[12, 31];
//optional. tell the XmlSerializer to name the Array Element as'Board'
// instead of 'BoaredDto'
[XmlArray("Diary")]
public bool[] DiaryDto
{
get { return Diary.Flatten(); }
set { Diary = value.Expand(12); } //5 is the number of roes in the matrix
}
// private bool[,] diary = new bool[32, 13];
// public bool[,] Diary { get => diary;set => diary= value; }
private int adults;
public int Adults { get => adults; set => adults = value; }
private int children;
public int Children { get => children; set => children = value; }
private bool pool;
public bool Pool { get => pool; set => pool = value; }
private bool jacuzzi;
public bool Jacuzzi { get => jacuzzi; set => jacuzzi = value; }
private bool garden;
public bool Garden { get => garden; set => garden = value; }
private bool childrensAttractions;
public bool ChildrensAttractions { get => childrensAttractions; set => childrensAttractions = value; }
private int room;
public int Room { get => room; set => room = value; }
private TypesOfVacation type;
public TypesOfVacation Type { get => type; set => type = value; }
private bool breakfast;
public bool Breakfast { get => breakfast; set => breakfast = value; }
private bool lunch;
public bool Lunch { get => lunch; set => lunch = value; }
private bool dinner;
public bool Dinner { get => dinner; set => dinner = value; }
public override string ToString()
{
string HostingUnit = " ";
return HostingUnit += string.Format("Hosting Unit Key:{0}\n" + " -Owner:\n" + "{1}\n" + "Hosting Unit Name:{2}\n" + "Hosting Unit Area:{3}\n" + "Hosting Unit Adults:{4}\n" + "Hosting Unit Children:{5}\n" + "Hosting Unit Pool:{6}\n" +
"Hosting Unit Jacuzzi:{7}\n" + "Hosting UnitGarden:{8}\n" + "Hosting Unit Area:{9}\n", HostingUnitKey, Owner, HostingUnitName, Area, Adults, children, pool, jacuzzi, Garden, ChildrensAttractions);
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/Project01_5404_8555_dotNet5780/BL/BL_imp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using BE;
using DAL;
using System.Windows;
using System.Net.Mail;
namespace BL
{
public class BL_imp : IBL
{
public void CheckSumDay(GuestRequest guest)//בודק את מספר הימים של ההזמנה ותקינותם
{
try
{
if ((guest.ReleaseDate - guest.EntryDate).Days < 1 && (guest.EntryDate - DateTime.Now).Days > 0)
throw new KeyNotFoundException("תאריכי הנופש שהזנת אינם תקינים");
}
catch (KeyNotFoundException a)
{
throw a;
}
}
public void Signed_bank_debit_authoization(GuestRequest x)// הסטטוס של הזזמנת הלקוח תהיה לפי אם הוא חתם על הרשאת גישה עבור חשבון בנק
{
try
{
if (x.Its_Signed == true)
x.Status = OrderStatus.mail_has_been_sent;
else
{
throw new OverflowException("לא חתמתה על השראת גישה לחיוב חשבון הבנק");//איזה סוג של זריקת חריגה צריך פה???
}
}
catch (OverflowException a)
{
throw a;
}
}
public bool AvailableDate(HostingUnit T, GuestRequest F)//ימים פנויים
{
DateTime Date = F.EntryDate;
while (Date < F.ReleaseDate)
{
int day = Date.Day;
int month = Date.Month;
if (T.Diary[day, month] == true)
return false;
Date= Date.AddDays(1);
}
return true;
}
public void CheckStatus(Order O)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> order = dal.Get_Orders();
var v = order.FirstOrDefault(o => O.OrderKey == o.OrderKey);
try
{
if (v.Status == OrderStatus.Closes_out_of_customer_disrespect || v.Status == OrderStatus.Closes_with_customer_response)
throw new Exception("אינך יכול לשנות את סטטוס הזמנתך");// צריך למצוא זריקת חריגה נכונה
}
catch (Exception)
{
throw;
}
}
public int StatusDone(Order O)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
GuestRequest v = dal.Get_GuestRequestList().FirstOrDefault(g => O.GuestRequestKey == g.GuestRequestKey);
if (O.Status == OrderStatus.Closes_with_customer_response)
if (v != null)
return ((v.ReleaseDate - v.EntryDate).Days * SiteOwner.Commission);
return 0;
}
public void BusyDate(Order O)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
GuestRequest guestRequest = dal.Get_GuestRequestList().FirstOrDefault(g => O.GuestRequestKey == g.GuestRequestKey);
HostingUnit hostingUnit = dal.Get_HostingUnitsList().FirstOrDefault(g => O.HostingUnitKey == g.HostingUnitKey);
DateTime Date = guestRequest.EntryDate;
while (Date < guestRequest.ReleaseDate)
{
int day = Date.Day;
int month = Date.Month;
hostingUnit.Diary[day, month] = true;
Date.AddDays(1);
}
}
public void StatusChange(Order O)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<GuestRequest> guestRequest = dal.Get_GuestRequestList();
var gu = guestRequest.FirstOrDefault(g => O.GuestRequestKey == g.GuestRequestKey);
gu.Status = OrderStatus.Closes_with_customer_response;//סטטוס ההזמנה נסגרה עסקה
try
{
dal.UpdateGuestRequest(gu);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
IEnumerable<Order> order = dal.Get_Orders();
foreach (var item in order)
{
if (gu.GuestRequestKey == item.GuestRequestKey)// צריך לבדוק שהלולואה לא אנסופית
{
item.Status = OrderStatus.Closes_with_customer_response;
try
{
dal.OrderChanged(item);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
}
}
}
public List<HostingUnit> FindHostingUnit(int id)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnits = dal.Get_HostingUnitsList();
var v = from item in hostingUnits
where id == item.Owner.HostKey
select item;
return v.ToList();
}
public void RemoveHostingUnitB(HostingUnit H)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> order = dal.Get_Orders();
var v = from item in order
where item.HostingUnitKey == H.HostingUnitKey && (item.Status == OrderStatus.mail_has_been_sent || item.Status == OrderStatus.Not_treated && item.HostingUnitKey == H.HostingUnitKey)
select item;
try
{
if (v == null)
throw new OverflowException("לא ניתן למחוק יחידת אירוח כל עוד יש הצעה הקשורה אליה במצב פתוח");
else dal.DeleteHostingUnit(H);
}
catch (OverflowException ex)
{
throw ex;
}
catch (KeyNotFoundException ex)
{
throw ex;
}
}
public void SendMail(Order O)
{
MailMessage mail = new MailMessage();
// כתובת הנמען)ניתן להוסיף יותר מאחד(
mail.To.Add("toEmailAddress");
// הכתובת ממנה נשלח המייל
mail.From = new MailAddress("fromEmailAddress");
// נושא ההודע ה
mail.Subject = "mailSubject";
//( HTML תוכן ההודעה )נניח שתוכן ההודעה בפורמט
mail.Body = "mailBody";
// HTML הגדרה שתוכן ההודעה בפורמט
mail.IsBodyHtml = true;
// Smtp יצירת עצם מסוג
SmtpClient smtp = new SmtpClient();
// gmail הגדרת השרת של
smtp.Host = "smtp.gmail.com";
// gmail הגדרת פרטי הכניסה )שם משתמש וסיסמה( לחשבון ה
smtp.Credentials = new System.Net.NetworkCredential("<EMAIL>", "<PASSWORD>");
// SSL ע"פ דרישת השר, חובה לאפשר במקרה זה
smtp.EnableSsl = true;
//try
//{
// שליחת ההודע ה
// smtp.Send(mail);
//}
//catch (KeyNotFoundException ex)
//{
// טיפול בשגיאות ותפיסת חריגות
// txtMessage.Text = ex.ToString();
//}
}
public bool AvailableUnit(DateTime Entry, int sumDay)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnits = dal.Get_HostingUnitsList();
DateTime Release = Entry.AddDays(sumDay);
var v = from item in hostingUnits
where AvailableDate(item, new GuestRequest { EntryDate = Entry, ReleaseDate = Release })
select item;
foreach (var item in v)
if (v == null)
throw new OverflowException("כל יחידות האירוח תפוסות בתאריכים אילו");
return true;
}
public int CalculateDate(DateTime firstDate, DateTime secondDate = default(DateTime))
{
if (secondDate == default(DateTime))
return (DateTime.Now - firstDate).Days;
return (secondDate - firstDate).Days;
}
public IEnumerable<Order> DateOfcreateOrder(int sumDay)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> order = dal.Get_Orders();
var v = from item in order
where (DateTime.Now - item.OrderDate).Days >= sumDay
select item.Clone();// מתי צריך לעשות clone
return v;
}
public IEnumerable<GuestRequest> Condition_Guest_Request(Predicate<GuestRequest> conditions)//צריך לכתוב את הפונקציה טוב יותר
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<GuestRequest> match_condition = dal.Get_GuestRequestList();
var applicable = from item in match_condition
where conditions(item)
select item;
return applicable;
}
public int NumOfOrder(GuestRequest gu)//מספר ההזמנות שנשלחו ללקוח לפי דרישת לקוח
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> order = dal.Get_Orders();
var countOfOrder = (from item in order
where gu.GuestRequestKey == item.GuestRequestKey
select new { OKey = item.OrderKey }).Count();
return countOfOrder;
}
public int NumOfOrderClosed(HostingUnit hu)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> order = dal.Get_Orders();
var countOfClosed = (from item in order
let closed = item.Status == OrderStatus.Closes_with_customer_response
where hu.HostingUnitKey == item.HostingUnitKey && closed == true
select item).Count();
return countOfClosed;
}
//grouping
//-------------------------------------------------------------------------
public IEnumerable<IGrouping<AreasInTheCountry, GuestRequest>> VacationArea()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<GuestRequest> guestRequest = dal.Get_GuestRequestList();
var Request_With_Same_Area = from item in guestRequest
group item by item.Area into groupByArea
select groupByArea;
return Request_With_Same_Area;
}
public IEnumerable<IGrouping<int, GuestRequest>> SumOfVacationers()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<GuestRequest> guestRequest = dal.Get_GuestRequestList();
var sum_of_Vacationers = from item in guestRequest
group item by (item.Adults + item.Children) into count_person
select count_person;
return sum_of_Vacationers;
}
public IEnumerable<IGrouping<int, Host>> SumOfHostingunit()//צריך לשנות את הפונקציה
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var numUnit = from item in hostingUnit
group item by item.Owner into unit
group unit.Key by unit.Count() into count_unit
select count_unit;
return numUnit;
}
public IEnumerable<IGrouping<AreasInTheCountry, HostingUnit>> RegionOfUnit()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var unit_area = from item in hostingUnit
group item by item.Area into Ua
select Ua;
return unit_area;
}
public IEnumerable<string> NameOfUnit(Host HO)//מקבץ לי שמות יחדות אירוח לפי מספר זהות של המארח
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var unit_Name = from item in hostingUnit
where item.Owner.HostKey == HO.HostKey
select item.HostingUnitName;
foreach (var item in unit_Name)
if (unit_Name.ToList() == null)
throw new KeyNotFoundException("אין יחידות אירוח למארח זה במערכת ");
return unit_Name.ToList();
}
public void CheackMail(string adress)
{
if ((adress.IndexOf("@") < 2) || (adress.IndexOf('.') < adress.IndexOf("@") + 3) || adress.IndexOf(" ") > 0)
throw new KeyNotFoundException("המייל שהכנסת שגוי או שלא הכנסת מייל, נסה שוב!");
}
void CheackNumOfPeople(int sum)
{
try
{
if (sum < 1)
throw new FormatException("לא הזנת מספר תקין של אנשים");
}
catch (FormatException a)
{
throw a;
}
}
//IDAL
//-------------------------------------------------------------------------
public void AddGuestRequestB(GuestRequest T)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
try
{
CheckSumDay(T);
CheackMail(T.MailAddress);
CheackNumOfPeople(T.Adults + T.Children);
AvailableUnit(T.EntryDate, (T.ReleaseDate - T.EntryDate).Days);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
catch (FormatException a)
{
throw a;
}
catch (OverflowException e)
{
throw e;
}
dal.AddGuestRequest(T);
}
public void AddOrderB(Order O)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var H = hostingUnit.FirstOrDefault(X => O.HostingUnitKey == X.HostingUnitKey);
IEnumerable<GuestRequest> guestReques = dal.Get_GuestRequestList();
var G = guestReques.First(Y => O.GuestRequestKey == Y.GuestRequestKey);
if (H == null)
throw new OverflowException("?????? לא תקינה");
if (G == null)
throw new OverflowException("דרישת האירוח לא תקינה");
dal.AddOrder(O);
if (!AvailableDate(H, G))
throw new OverflowException("שלח בקשת אירוח");
}
public void AddHostingUnitB(HostingUnit T)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
dal.AddHostingUnit(T);
}
public void UpdateHostingUnitB(HostingUnit T)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
try
{
dal.UpdateHostingUnit(T);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
}
public void OrderChangedB(Order O)
{
try
{
CheckStatus(O);
}
catch (Exception)
{
throw;
}
if (O.Status == OrderStatus.Closes_with_customer_response)
{
try
{
StatusChange(O);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
catch (Exception)
{
throw;
}
StatusDone(O);
BusyDate(O);
}
if (O.Status == OrderStatus.mail_has_been_sent)
try
{
SendMail(O);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
}
public IEnumerable<HostingUnit> Get_HostingUnitsListB()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.Get_HostingUnitsList();
}
public IEnumerable<GuestRequest> Get_GuestRequestListB()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.Get_GuestRequestList();
}
public IEnumerable<Order> Get_OrdersB()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.Get_Orders();
}
public IEnumerable<BankBranch> Brunch_bankB()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.GetBrunch_bank();
}
//HostingUnit
public Host CheckId(int id)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Host> hostList = dal.Get_HostList();
var H = hostList.FirstOrDefault(X => X.HostKey == id);
if (H != null)
return H;
throw new KeyNotFoundException("הת.ז לא קיימת במערכת ");
}
public HostingUnit Host_ToHostingUnit(Host h,string name)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> HU = dal.Get_HostingUnitsList();
var V = HU.FirstOrDefault(X=> X.HostingUnitName == name && X.Owner.HostKey == h.HostKey);
return V;
}
//GuestRequest
public void UpdateGuestRequestB(GuestRequest T)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
try
{
dal.UpdateGuestRequest(T);
}
catch (KeyNotFoundException)
{
throw;
}
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BL/BL_imp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using BE;
using DAL;
using System.Windows;
using System.Net.Mail;
namespace BL
{
public class BL_imp : IBL
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
#region bank
public IEnumerable<BankBranch> Brunch_bankB()
{
return dal.GetBrunch_bank();
}
public IEnumerable<BankBranch> ListOfBanks(string searchString)
{
return dal.GetAllbanks(t => ((t.BankName.Contains(searchString) || t.BranchAddress.Contains(searchString) || t.BranchCity.Contains(searchString))));
}
//public void Signed_bank_debit_authoization(GuestRequest x)// הסטטוס של הזזמנת הלקוח תהיה לפי אם הוא חתם על הרשאת גישה עבור חשבון בנק
//{
// try
// {
// if (x.Its_Signed == true)
// x.Status = OrderStatus.נשלח_מייל;
// else
// {
// throw new OverflowException("לא חתמתה על השראת גישה לחיוב חשבון הבנק");//איזה סוג של זריקת חריגה צריך פה???
// }
// }
// catch (OverflowException a)
// {
// throw a;
// }
//}
#endregion
#region GuestRequest
public bool AvailableUnit(DateTime Entry, int sumDay)//בודק אם יש תאריכים פונים לדרישת לקוח
{
IEnumerable<HostingUnit> hostingUnits = dal.Get_HostingUnitsList();
DateTime Release = Entry.AddDays(sumDay);
var v = from item in hostingUnits
where AvailableDate(item, new GuestRequest { EntryDate = Entry, ReleaseDate = Release})
select item;
foreach (var item in v)
if (v.ToList() == null)
throw new OverflowException("כל יחידות האירוח תפוסות בתאריכים אילו");
return true;
}
public int CalculateDate(DateTime firstDate, DateTime secondDate = default(DateTime))//הפונקציה מחזירה את מספר הימים שעברו
{
if (secondDate == default(DateTime))
return (DateTime.Now - firstDate).Days;
return (secondDate - firstDate).Days;
}
public int NumOfOrder(GuestRequest gu)//מספר ההזמנות שנשלחו ללקוח לפי דרישת לקוח
{
IEnumerable<Order> order = dal.Get_Orders();
var countOfOrder = (from item in order
where gu.GuestRequestKey == item.GuestRequestKey
select new { OKey = item.OrderKey }).Count();
return countOfOrder;
}
public IEnumerable<IGrouping<AreasInTheCountry, GuestRequest>> VacationArea()//קיבוץ לקוחות לפי תת אדור
{
IEnumerable<GuestRequest> guestRequest = dal.Get_GuestRequestList();
var Request_With_Same_Area = from item in guestRequest
group item by item.Area into groupByArea
select groupByArea;
return Request_With_Same_Area;
}
public IEnumerable<IGrouping<int, GuestRequest>> SumOfVacationers()//קיבוף לקוחות לפי מסר נופשים
{
IEnumerable<GuestRequest> guestRequest = dal.Get_GuestRequestList();
var sum_of_Vacationers = from item in guestRequest
group item by (item.Adults + item.Children) into count_person
select count_person;
return sum_of_Vacationers;
}
public void CheackMail(string adress)//בדקת את כתובת המייל
{
if ((adress.IndexOf("@") < 2) || (adress.IndexOf('.') < adress.IndexOf("@") + 3) || adress.IndexOf(" ") > 0)
throw new KeyNotFoundException("המייל שהכנסת שגוי או שלא הכנסת מייל, נסה שוב!");
}
void CheackNumOfPeople(int sum)//בדק שמספר הלקוחות גדול מ1
{
if (sum < 1)
throw new FormatException("לא הזנת מספר תקין של אנשים");
}
public IEnumerable<GuestRequest> Get_GuestRequestListB()//מחזיר רשימת כל הלקוחות
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.Get_GuestRequestList();
}
public void UpdateGuestRequestB(GuestRequest T)//מעדכן מארח
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
dal.UpdateGuestRequest(T);
throw new Exception("");
}
public void AddGuestRequestB(GuestRequest T)//הוספת יחידת לקוח
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
try
{
CheckSumDay(T);
CheackMail(T.MailAddress);
CheackNumOfPeople(T.Adults + T.Children);
AvailableUnit(T.EntryDate, (T.ReleaseDate - T.EntryDate).Days);
dal.AddGuestRequest(T);
}
catch (Exception b)
{
throw b;
}
}
public string KeyToNameGR(int key)//מקבלת מפתח של דרישת לקוח ומחזירה את השם הלקוח
{
IEnumerable<GuestRequest> gr = dal.Get_GuestRequestList();
var v = gr.FirstOrDefault(X => key == X.GuestRequestKey);
return v.PrivateName += v.FamilyName;
}
#endregion
#region Host
public Host CheckId(int id)//מקבל ת"ז ומחזיר את המארח שלו
{
IEnumerable<Host> hostList = dal.Get_HostList();
var H = hostList.FirstOrDefault(X => X.HostKey == id);
if (H != null)
return H;
throw new KeyNotFoundException("הת.ז לא קיימת במערכת ");
}
public void AddHostB(Host T)//הוספת מארח
{
try
{
dal.AddHost(T);
}
catch (Exception e)
{
throw e;
}
}
public IEnumerable<Host> Get_Host()//מחזיר רשימת המארחים
{
IEnumerable<Host> host = dal.Get_HostList();
var v = from item in host
select item;
return v.ToList();
}
#endregion
#region Order;
public void BusyDate(Order O)//כאשר סטטוס ההזמנה משתנה בגלל סגירת עסקה – יש לסמן במטריצה את התאריכים
{
GuestRequest guestRequest = dal.Get_GuestRequestList().FirstOrDefault(g => O.GuestRequestKey == g.GuestRequestKey);
HostingUnit hostingUnit = dal.Get_HostingUnitsList().FirstOrDefault(g => O.HostingUnitKey == g.HostingUnitKey);
DateTime Date = guestRequest.EntryDate;
while (Date < guestRequest.ReleaseDate)
{
int day = Date.Day;
int month = Date.Month;
hostingUnit.Diary[month, day] = true;
Date = Date.AddDays(1);
}
}
public int StatusDone(Order O)//כאשר סטטוס ההזמנה משתנה בגלל סגירת עסקה – יש לבצע חישוב עמלה
{
GuestRequest v = dal.Get_GuestRequestList().FirstOrDefault(g => O.GuestRequestKey == g.GuestRequestKey);
if (O.Status == OrderStatus.נסגרה_עסקה)
if (v != null)
return ((v.ReleaseDate - v.EntryDate).Days *dal.Get_commission());
return 0;
}
public void CheckStatus(Order O)//לאחר שסטטוס ההזמנה השתנה לסגירת עיסקה – לא ניתן לשנות יותר את הסטטוס שלה.
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> order = dal.Get_Orders();
var v = order.FirstOrDefault(o => O.OrderKey == o.OrderKey);
if (v.Status == OrderStatus.נסגר_מחוסר_הענות || v.Status == OrderStatus.נסגרה_עסקה)
throw new KeyNotFoundException("אינך יכול לשנות את סטטוס הזמנתך");// צריך למצוא זריקת חריגה נכונה
}
public IEnumerable<Order> DateOfcreateOrder(int sumDay)//בודקת אם פג התוקף של ההזמנה
{
IEnumerable<Order> order = dal.Get_Orders();
var v = from item in order
where (DateTime.Now - item.OrderDate).Days >= sumDay
select item.Clone();
return v.ToList();
}
public int NumOfOrderClosed(HostingUnit hu)//מספר ההזמנות שניסגרו
{
IEnumerable<Order> order = dal.Get_Orders();
var countOfClosed = (from item in order
let closed = item.Status == OrderStatus.נסגרה_עסקה
where hu.HostingUnitKey == item.HostingUnitKey && closed == true
select item).Count();
return countOfClosed;
}
public IEnumerable<Order> Get_OrdersB()//מחזיר את רשימת כל ההזמנות
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.Get_Orders();
}
public bool AvailableDate(HostingUnit T, GuestRequest F)//ימים פנויים
{
DateTime Date = F.EntryDate;
while (Date < F.ReleaseDate)
{
int day = Date.Day - 1;
int month = Date.Month - 1;
if (T.Diary[month, day] == true)
return false;
Date = Date.AddDays(1);
}
return true;
}
public void CheckSumDay(GuestRequest guest)//בודק את מספר הימים של ההזמנה ותקינותם
{
try
{
if ((guest.ReleaseDate - guest.EntryDate).Days < 1 || guest.EntryDate < DateTime.Now || guest.ReleaseDate < DateTime.Now
)
throw new KeyNotFoundException("תאריכי הנופש שהזנת אינם תקינים");
}
catch (KeyNotFoundException a)
{
throw a;
}
}
public void SendMail(Host H,GuestRequest g)//שליחת מייל
{
MailMessage mail = new MailMessage();
mail.To.Add(g.MailAddress);
mail.From = new MailAddress("<EMAIL>");
mail.Subject = "הצעה לחופשה ";
mail.Body = H.PhoneNumber + " " + "או ליצור איתנו קשר במספר הטלפון " + " " + H.MailAddress + " " + " שלום וברכה,ראינו שהתענינת/ה בחופשה ,אנחנו מצאנו חופשה שתואמת לדרישות שלך עדכן אותנו אם הינך מעוניין במייל המצורף";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Port = 25;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential(" <EMAIL>", "308508rc");
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
throw new Exception("ההזמנה התבצעה בהצלחה ");
}
catch (Exception ex)
{
ex.ToString();
}
}
public void AddOrderB(Host Ho,Order O)//הוספת הזמנה
{
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var H = hostingUnit.FirstOrDefault(X => O.HostingUnitKey == X.HostingUnitKey);
IEnumerable<GuestRequest> guestReques = dal.Get_GuestRequestList();
var G = guestReques.First(Y => O.GuestRequestKey == Y.GuestRequestKey);
if (H == null)
throw new OverflowException("דרישת הלקוח לא תקינה");
if (G == null)
throw new OverflowException("דרישת האירוח לא תקינה");
try
{
AvailableDate(H, G);
//ConditionHU(guestReques,H);
SendMail(Ho.Clone(),G.Clone());
O.Status = OrderStatus.נשלח_מייל;
O.OrderDate = DateTime.Now;
dal.AddOrder(O.Clone());
}
catch (Exception exp)
{
throw exp;
}
throw new OverflowException("ההזמנה נשלחה בהצלחה");
}
public IEnumerable<GuestRequest> Condition_Guest_Request1(Predicate<GuestRequest> conditions, IEnumerable<GuestRequest> g)//מקבלת תנאי ובדקת את הלקוחות לפי התנאי
{
var applicable = from item in g
where conditions(item)
select item;
foreach (var item in applicable)
if (applicable.ToList() == null)
throw new KeyNotFoundException("לא קיימת דרישת לקוח מתאימה ליחידה זו ");
return applicable.ToList();
}
public IEnumerable<GuestRequest> Condition_Guest_Request2(Func< GuestRequest, bool> conditions, IEnumerable<GuestRequest> g)//מקבלת תנאי ובדקת את הלקוחות לפי התנאי
{
var applicable = from item in g
where conditions(item)
select item;
foreach (var item in applicable)
if (applicable.ToList() == null)
throw new KeyNotFoundException("לא קיימת דרישת לקוח מתאימה ליחידה זו ");
return applicable.ToList();
}
public bool PoolT(GuestRequest g)
{
return g.Pool == ChoosingAttraction.אפשרי || g.Pool == ChoosingAttraction.הכרחי ? true : false;
}
public bool PoolF(GuestRequest g)
{
return g.Pool == ChoosingAttraction.אפשרי || g.Pool == ChoosingAttraction.לא_מעוניין ? false : true;
}
public bool GardenT(GuestRequest g)
{
return g.Garden == ChoosingAttraction.אפשרי || g.Garden == ChoosingAttraction.הכרחי ? true : false;
}
public bool GardenF(GuestRequest g)
{
return g.Garden == ChoosingAttraction.אפשרי || g.Garden == ChoosingAttraction.לא_מעוניין ? false : true;
}
public bool jakuzziT(GuestRequest g)
{
return g.Jacuzzi == ChoosingAttraction.אפשרי || g.Jacuzzi == ChoosingAttraction.הכרחי ? true : false;
}
public bool jakuzziF(GuestRequest g)
{
return g.Jacuzzi == ChoosingAttraction.אפשרי || g.Jacuzzi == ChoosingAttraction.לא_מעוניין ? false : true;
}
public bool AttractionT(GuestRequest g)
{
return g.ChildrensAttractions == ChoosingAttraction.אפשרי || g.ChildrensAttractions == ChoosingAttraction.הכרחי ? true : false;
}
public bool AttractionF(GuestRequest g)
{
return g.ChildrensAttractions == ChoosingAttraction.אפשרי || g.ChildrensAttractions == ChoosingAttraction.לא_מעוניין ? false : true;
}
public bool Breakfast(GuestRequest g)
{
return g.Breakfast ? false : true;
}
public bool Lunch(GuestRequest g)
{
return g.Lunch ? false : true;
}
public bool Dinner(GuestRequest g)
{
return g.Dinner ? false : true;
}
public bool Type(GuestRequest g, TypesOfVacation a)
{
return g.Type == a ? true : false;
}
public bool SubArea(GuestRequest g, All a)
{
return g.SubArea == a ? true : false;
}
public void StatusChange(Order O)//שינוי סטטוס
{
IEnumerable<GuestRequest> guestRequest = dal.Get_GuestRequestList();
var gu = guestRequest.FirstOrDefault(g => O.GuestRequestKey == g.GuestRequestKey);
gu.Status = OrderStatus.נסגרה_עסקה;//סטטוס ההזמנה נסגרה עסקה
try
{
dal.UpdateGuestRequest(gu);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
IEnumerable<Order> order = dal.Get_Orders();
foreach (var item in order)
{
if (gu.GuestRequestKey == item.GuestRequestKey)// צריך לבדוק שהלולואה לא אנסופית
{
item.Status = OrderStatus.נסגרה_עסקה;
try
{
dal.OrderChanged(item.Clone());
}
catch (KeyNotFoundException ex)
{
throw ex;
}
}
}
}
public void OrderChangedB(Host H,Order O)//עדכון הזמנה
{
try
{
CheckStatus(O);
if (O.Status == OrderStatus.נסגרה_עסקה)
StatusChange(O);
}
catch (Exception)
{
throw;
}
Accumulation(StatusDone(O));
BusyDate(O);
IEnumerable<GuestRequest> guestReques = dal.Get_GuestRequestList();
var G = guestReques.First(Y => O.GuestRequestKey == Y.GuestRequestKey);
if (O.Status == OrderStatus.נשלח_מייל)
try
{
SendMail(H.Clone(),G.Clone());
}
catch (KeyNotFoundException ex)
{
throw ex;
}
O.OrderDate = DateTime.Now;
}
#endregion
#region siteOwner
public IEnumerable<GuestRequest> CloseGR ()//שאילתת רשימת לקוחות שנסגרה עסקה
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<GuestRequest> guestReques = dal.Get_GuestRequestList();
var V = from item in guestReques
where item.Status == OrderStatus.נסגרה_עסקה
select item;
return V.ToList();
}
public IEnumerable<GuestRequest> NoTreat()//שאילתת רשימת לקוחות שלא טופלו
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<GuestRequest> guestReques = dal.Get_GuestRequestList();
var V = from item in guestReques
where item.Status == OrderStatus.לא_טופל
select item;
return V.ToList();
}
public IEnumerable<GuestRequest> MailwasSent()//שאילתת רשימת לקוחות שטופלו
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<GuestRequest> guestReques = dal.Get_GuestRequestList();
var V = from item in guestReques
where item.Status == OrderStatus.נשלח_מייל
select item;
return V.ToList();
}
public IEnumerable<HostingUnit> AvailableUnitList(DateTime Entry, int sumDay)//מחזירה את כל רשימת יחידות אירוח פנויות
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnits = dal.Get_HostingUnitsList();
DateTime Release = Entry.AddDays(sumDay);
var v = from item in hostingUnits
where AvailableDate(item, new GuestRequest { EntryDate = Entry, ReleaseDate = Release })
select item;
return v.ToList();
}
public IEnumerable<HostingUnit> BusyUnitList(DateTime Entry, int sumDay)//בודק את הימים התפוסים
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hostingUnits = dal.Get_HostingUnitsList();
DateTime Release = Entry.AddDays(sumDay);
var v = from item in hostingUnits
where (!AvailableDate(item, new GuestRequest { EntryDate = Entry, ReleaseDate = Release }))
select item;
return v.ToList();
}
public IEnumerable<Order> pagTokef()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> orders = dal.Get_Orders();//gets the list of orders
var createResult = from item in orders //creates a list of all orders that need to be closed
where item.OrderDate.AddDays(Configuration.orderValidity) < DateTime.Now && item.Status == OrderStatus.נשלח_מייל
select item;
return createResult;
}
public void Accumulation(int t)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
int acu = dal.Get_accumulation() + t;
dal.updateaccumulation(acu);
}
public int Accumulation()
{
return dal.Get_accumulation();
}
public int updatepasswords()
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.updatepasswords(SiteOwner1.Passwords);
}
#endregion
#region HostingUnit
public List<HostingUnit> FindHostingUnit(int id)//מוצא מארח לפי תז
{
IEnumerable<HostingUnit> hostingUnits = dal.Get_HostingUnitsList();
var v = from item in hostingUnits
where id == item.Owner.HostKey
select item;
return v.ToList();
}
public void RemoveHostingUnitB(HostingUnit H)//לפני מחיקת יחידת אירוח בודק אם אין הזמנות במצב פתוח
{
IEnumerable<Order> order = dal.Get_Orders();
var v = from item in order
where item.HostingUnitKey == H.HostingUnitKey && (item.Status == OrderStatus.נשלח_מייל || item.Status == OrderStatus.לא_טופל && item.HostingUnitKey == H.HostingUnitKey)
select item;
if (v.ToList() == null)
throw new OverflowException("לא ניתן למחוק יחידת אירוח כל עוד יש הצעה הקשורה אליה במצב פתוח");
else
{
try
{
dal.DeleteHostingUnit(H);
}
catch (Exception)
{
throw;
}
}
}
public IEnumerable<IGrouping<int, Host>> SumOfHostingunit()//רשימת מארחים מקובצת ע"פ מספר יחידות האירוח שהם מחזיקים
{
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var numUnit = from item in hostingUnit
group item by item.Owner into unit
group unit.Key by unit.Count() into count_unit
select count_unit;
return numUnit.ToList();
}
public IEnumerable<IGrouping<AreasInTheCountry, HostingUnit>> RegionOfUnit()//מקבף יחדות אירוח לפי תת אזור
{
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var unit_area = from item in hostingUnit
group item by item.Area into Ua
select Ua;
return unit_area.ToList();
}
public IEnumerable<string> NameOfUnit(Host HO)//מקבץ לי שמות יחדות אירוח לפי מספר זהות של המארח
{
IEnumerable<HostingUnit> hostingUnit = dal.Get_HostingUnitsList();
var unit_Name = from item in hostingUnit
where item.Owner.HostKey == HO.HostKey
select item.HostingUnitName;
foreach (var item in unit_Name)
if (item.ToList() == null)
throw new KeyNotFoundException("אין יחידות אירוח למארח זה במערכת ");
return unit_Name.ToList();
}
public void AddHostingUnitB(HostingUnit T)
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
try
{
dal.AddHostingUnit(T);
}
catch (Exception)
{
throw;
}
}
public void UpdateHostingUnitB(HostingUnit T)//מעדכן יחידת אירוח
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
try
{
dal.UpdateHostingUnit(T);
}
catch (KeyNotFoundException ex)
{
throw ex;
}
}
public IEnumerable<HostingUnit> Get_HostingUnitsListB()//מחזיר רשימת של יחידות אירוח
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
return dal.Get_HostingUnitsList();
}
public HostingUnit Host_ToHostingUnit(Host h, string name)//מקבל מארח ומחדיר את כל יחידות ארוח שלו
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> HU = dal.Get_HostingUnitsList();
var V = HU.FirstOrDefault(X => X.HostingUnitName == name && X.Owner.HostKey == h.HostKey);
return V;
}
public IEnumerable<Order> UnitToOrder(HostingUnit H)//מקבלת את היחדת אירוח ומחזירה את ההזמנות ששיכות ליחדה זו
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<Order> orders = dal.Get_Orders();
var v = from item in orders
where item.HostingUnitKey == H.HostingUnitKey
select item;
return v.ToList();
}
public string KeyToNameHu(int key)//מקבלת מפתח של יחידת אירוח ומחזירה את השם של היחידה
{
DAL.IDAL dal = DAL.FactoryDal.GetDal();
IEnumerable<HostingUnit> hu = dal.Get_HostingUnitsList();
var v = hu.FirstOrDefault(X => key == X.HostingUnitKey);
return v.HostingUnitName;
}
public void sumAdult(GuestRequest g,HostingUnit H)
{
if (H.Adults < g.Adults)
throw new KeyNotFoundException("יחידת האירוח אינה תואמת לדרישת הלקוח");
}
public void sumChilds(GuestRequest g, HostingUnit H)
{
if (H.Children < g.Children)
throw new KeyNotFoundException("יחידת האירוח אינה תואמת לדרישת הלקוח");
}
#endregion
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace PLWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
//SunTimes.CalculateSunRiseSetTimes(35.224,);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
grGR.Visibility = Visibility.Visible;
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
grHu.Visibility = Visibility.Visible;
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
}
private void Button_Click_PrivateHost(object sender, RoutedEventArgs e)
{
PrivateHost w1 = new PrivateHost();
w1.Show();
this.Visibility = Visibility.Collapsed;
}
private void enter(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
b.Content = b.Content;
}
}
private void live(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
b.Content = b.Content;
}
}
private void Button_Click_Delete(object sender, RoutedEventArgs e)
{
}
private void Button_Click_AddGr(object sender, RoutedEventArgs e)
{
AddGR win = new AddGR();
win.Show();
this.Visibility = Visibility.Collapsed;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Question win = new Question();
win.Show();
this.Visibility = Visibility.Collapsed;
}
private void Button_Click_feed(object sender, RoutedEventArgs e)
{
Feedback win = new Feedback();
win.Show();
this.Visibility = Visibility.Collapsed;
}
private void Button_Click_(object sender, RoutedEventArgs e)
{
Feedback win = new Feedback();
win.Show();
this.Close();
}
private void grHu_MouseLeave(object sender, RoutedEventArgs e)
{
grHu.Visibility = Visibility.Collapsed;
}
private void grGR_MouseLeave(object sender, RoutedEventArgs e)
{
grGR.Visibility = Visibility.Collapsed;
}
private void Button_Click_SiteOwner(object sender, RoutedEventArgs e)
{
SiteOwner SO = new SiteOwner();
SO.Show();
this.Visibility = Visibility.Collapsed;
}
public System.Collections.Specialized.NameValueCollection ServerVariables;
private void Language_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Button_Click_AddHost(object sender, RoutedEventArgs e)
{
AddHost Ah = new AddHost();
Ah.Show();
this.Visibility = Visibility.Collapsed;
}
private void Button_Click_hu(object sender, RoutedEventArgs e)
{
HotelRecommended Hr = new HotelRecommended();
Hr.Show();
this.Visibility = Visibility.Collapsed;
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/DAL/Dal_XML_imp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Xml.Linq;
using System.Xml.Serialization;
using BE;
using System.IO;
using System.Reflection;
using System.Net;
using System.ComponentModel;
using System.Xml;
namespace DAL
{
public class Dal_XML_imp : IDAL
{
XElement GuestRequestRoot;
string guestRequestPath = @"\GuestRequestXml.xml";
XElement HostingUnitRoot;
string hostingUnitPath = @"\HostingUnitXml.xml";
XElement OrderRoot;
string orderPath = @"\OrderXml.xml";
XElement HostRoot;
string hostPath = @"\HostXml.xml";
XElement ConfigRoot;
string configPath = @"\ConfigXml.xml";
//XElement BankRoot;
public static volatile bool bankDownloaded = false;//flag if bank was downloaded
BackgroundWorker worker;
XElement SiteOwner1Root;
string siteOwner1Path = @"\SiteOwner1Xml.xml";
public Dal_XML_imp()
{
if (!File.Exists(guestRequestPath))
{
List<GuestRequest> guestRequestList = new List<GuestRequest>();//empty list for start
SaveToXML<List<GuestRequest>>(guestRequestList, guestRequestPath);
//GuestRequestRoot = new XElement("GuestRequest");
//GuestRequestRoot.Save(guestRequestPath);
}
else
LoadGuestRequests();
if (!File.Exists(hostingUnitPath))
{
List<HostingUnit> HostingUnitList = new List<HostingUnit>();//empty list for start
SaveToXML<List<HostingUnit>>(HostingUnitList, hostingUnitPath);
// HostingUnitRoot = new XElement("HostingUnit");
//HostingUnitRoot.Save(hostingUnitPath);
}
else
LoadHostingUnit();
if (!File.Exists(orderPath))
{
List<Order> OrdertList = new List<Order>();//empty list for start
SaveToXML<List<Order>>(OrdertList, orderPath);
//OrderRoot = new XElement("Order");
// OrderRoot.Save(orderPath);
}
else
LoadOrder();
if (!File.Exists(hostPath))
{
List<Host> HostList = new List<Host>();//empty list for start
SaveToXML<List<Host>>(HostList, hostPath);
}
else
LoadHost();
if (!File.Exists(configPath))
{
CreateConfigFile();
}
else
Loadconfig();
if (!File.Exists(siteOwner1Path))
{
CreateSiteOwner1();
}
else
LoadSiteOwner();
try
{
worker = new BackgroundWorker();
worker.DoWork += Worker_DoWork;
worker.RunWorkerAsync();
}
catch(FileLoadException a)
{
throw a;
}
}
public static void SaveToXML<T>(T source, string path)//save objects like elements from program to file
{
FileStream file = new FileStream(path, FileMode.Create);
XmlSerializer xmlSerializer = new XmlSerializer(source.GetType());
xmlSerializer.Serialize(file, source);
file.Close();
}
public static T LoadFromXML<T>(string path)//save elements like objects from file to program
{
FileStream file = new FileStream(path, FileMode.Open);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
T result = (T)xmlSerializer.Deserialize(file);
file.Close();
return result;
}
public void LoadGuestRequests()
{
try
{
GuestRequestRoot = XElement.Load(guestRequestPath);
}
catch
{
throw new Exception("File upload problem");
}
}
public void LoadHostingUnit()
{
try
{
HostingUnitRoot = XElement.Load(hostingUnitPath);
}
catch
{
throw new Exception("File upload problem");
}
}
public void LoadOrder()
{
try
{
OrderRoot = XElement.Load(orderPath);
}
catch
{
throw new Exception("File upload problem");
}
}
public void LoadHost()
{
try
{
HostRoot = XElement.Load(hostPath);
}
catch
{
throw new Exception("File upload problem");
}
}
public void Loadconfig()
{
try
{
ConfigRoot = XElement.Load(configPath);
}
catch
{
throw new Exception("File upload problem");
}
}
public void LoadSiteOwner()
{
try
{
SiteOwner1Root = XElement.Load(siteOwner1Path);
}
catch
{
throw new Exception("File upload problem");
}
}
#region GuestRequest
public void AddGuestRequest(GuestRequest g)
{
// if (CheckGR(g.GuestRequestKey)==null)//בודק אם המפתח כבר קיים
// throw new Exception("היחידת אירוח קיימת במערכת");
int tmp = int.Parse(ConfigRoot.Element("guestRequestKey").Value) + 1;
g.GuestRequestKey = tmp;
ConfigRoot.Element("guestRequestKey").Value = tmp.ToString();
List<GuestRequest> guestRequestList = LoadFromXML<List<GuestRequest>>(guestRequestPath);
guestRequestList.Add(g);
ConfigRoot.Save(configPath);
SaveToXML<List<GuestRequest>>(guestRequestList, guestRequestPath);//שומר בקובץ
}
public void UpdateGuestRequest(GuestRequest g)//פונקציה שמעדכנת את יחידות האירוח
{
List<GuestRequest> guestRequestList = LoadFromXML<List<GuestRequest>>(guestRequestPath);
int index = guestRequestList.FindIndex(p => p.GuestRequestKey == g.GuestRequestKey);
if (index == -1)//didnt find
throw new Exception("לקוח לא נמצא במערכת");
guestRequestList[index] = g;//update mother in her place
SaveToXML<List<GuestRequest>>(guestRequestList, guestRequestPath);//save in file
}
public IEnumerable<GuestRequest> Get_GuestRequestList()
{
return LoadFromXML<List<GuestRequest>>(guestRequestPath).AsEnumerable();
}
public GuestRequest CheckGR(int checkId)//An auxiliary function that brings and passes the Testers list
{
return LoadFromXML<List<GuestRequest>>(guestRequestPath).FirstOrDefault(p => p.GuestRequestKey == checkId);
}
#endregion
#region HostingUnit
public void AddHostingUnit(HostingUnit h)
{
if (Checkhu(h.HostingUnitKey) != null)//בודק אם המפתח כבר קיים
throw new Exception("היחידת אירוח קיימת במערכת");
for (int j = 0; j < 12; j++)
{
{
for (int i = 0; i < 31; i++)
h.Diary[j, i] = false;
}
}
int tmp = int.Parse(ConfigRoot.Element("hostingUnitKey").Value) + 1;
h.HostingUnitKey = tmp;
ConfigRoot.Element("hostingUnitKey").Value = tmp.ToString();
List<HostingUnit> hostingUnittList = LoadFromXML<List<HostingUnit>>(hostingUnitPath);
hostingUnittList.Add(h);
ConfigRoot.Save(configPath);
SaveToXML<List<HostingUnit>>(hostingUnittList, hostingUnitPath);//שומר בקובץ
}
public void UpdateHostingUnit(HostingUnit h)//פונקציה שמעדכנת את יחידות האירוח
{
List<HostingUnit> hostingUnitList = LoadFromXML<List<HostingUnit>>(hostingUnitPath);
int index = hostingUnitList.FindIndex(p => p.HostingUnitKey == h.HostingUnitKey);
if (index == -1)//didnt find
throw new Exception("יחידת האירוח לא נמצאת במערכת");
hostingUnitList[index] = h;//update mother in her place
DeleteHostingUnit(h);
SaveToXML<List<HostingUnit>>(hostingUnitList, hostingUnitPath);//save in file
}
public IEnumerable<HostingUnit> Get_HostingUnitsList()
{
return LoadFromXML<List<HostingUnit>>(hostingUnitPath).AsEnumerable();
}
public HostingUnit Checkhu(int checkId)
{
return LoadFromXML<List<HostingUnit>>(hostingUnitPath).FirstOrDefault(p => p.HostingUnitKey == checkId);
}
public void DeleteHostingUnit(HostingUnit T)
{
XElement hostingUnitElement;
try
{
hostingUnitElement = (from item in HostingUnitRoot.Elements()
where int.Parse(item.Element("HostingUnitKey").Value) == T.HostingUnitKey
select item).FirstOrDefault();
hostingUnitElement.Remove();
HostingUnitRoot.Save(hostingUnitPath);
}
catch
{
throw new KeyNotFoundException("היחידת אירוח אינה קיימת במערכת");
}
}
#endregion
#region Host
public void AddHost(Host Ho)
{
if (CheckHost(Ho.HostKey))//בודק אם המפתח כבר קיים
throw new Exception("המארח כבר קיים במערכת");
List<Host> hostList = LoadFromXML<List<Host>>(hostPath);
var v = hostList.FirstOrDefault(X => X.HostKey == Ho.HostKey);
hostList.Add(Ho);
SaveToXML<List<Host>>(hostList, hostPath);//שומר בקובץ
}
public bool CheckHost(int checkId)//An auxiliary function that brings and passes the host list
{
return LoadFromXML<List<Host>>(hostPath).FirstOrDefault(p => p.HostKey == checkId) == null ? false : true;
}
#endregion
#region Order
public void AddOrder(Order O)
{
if (CheckO(O.OrderKey) != null)//בודק אם המפתח כבר קיים
throw new Exception("ההזמנה קיימת במערכת");
int tmp = int.Parse(ConfigRoot.Element("orderKey").Value) + 1;
O.OrderKey = tmp;
ConfigRoot.Element("orderKey").Value = tmp.ToString();
List<Order> orderList = LoadFromXML<List<Order>>(orderPath);
orderList.Add(O);
ConfigRoot.Save(configPath);
SaveToXML<List<Order>>(orderList, orderPath);//שומר בקובץ
}
public void OrderChanged(Order o)//פונקציה שמעדכנת את ההזמנות
{
List<Order> orderList = LoadFromXML<List<Order>>(orderPath);
int index = orderList.FindIndex(p => p.OrderKey == o.OrderKey);
if (index == -1)//didnt find
throw new Exception("ההזמנה לא נמצאת במערכת");
orderList[index] = o;//update mother in her place
DeleteOrder(o);
SaveToXML<List<Order>>(orderList, orderPath);//save in file
}
public IEnumerable<Order> Get_Orders()
{
return LoadFromXML<List<Order>>(orderPath).AsEnumerable();
}
public Order CheckO(int checkId)//An auxiliary function that brings and passes the order list
{
return LoadFromXML<List<Order>>(orderPath).FirstOrDefault(p => p.OrderKey == checkId);
}
public IEnumerable<Host> Get_HostList()
{
return LoadFromXML<List<Host>>(hostPath).AsEnumerable();
}
public void DeleteOrder(Order T)
{
XElement orderElrment;
try
{
orderElrment = (from item in OrderRoot.Elements()
where int.Parse(item.Element("orderKey").Value) == T.OrderKey
select item).FirstOrDefault();
orderElrment.Remove();
OrderRoot.Save(orderPath);
}
catch
{
throw new KeyNotFoundException("היחידת אירוח אינה קיימת במערכת");
}
}
#endregion
#region config
void CreateConfigFile()
{
try
{
ConfigRoot = new XElement("Configuration");
//XElement passwords = new XElement("passwords", 100000000);
XElement hostingUnitKey = new XElement("hostingUnitKey", 100000000);
XElement guestRequestKey = new XElement("guestRequestKey", 100000000);
XElement orderKey = new XElement("orderKey", 100000000);
ConfigRoot.Add(hostingUnitKey, guestRequestKey, orderKey);
ConfigRoot.Save(configPath);
}
catch
{
throw new FileLoadException("Cannot start the project check your Config Xml files");
}
}
#endregion
#region SiteOwner1
void CreateSiteOwner1()
{
try
{
SiteOwner1Root = new XElement("SiteOwner1");
XElement passwords = new XElement("passwords", 100000000);
XElement commission = new XElement("commission", 10);
XElement accumulation = new XElement("accumulation", 0);
SiteOwner1Root.Add(passwords, commission, accumulation);
SiteOwner1Root.Save(siteOwner1Path);
}
catch
{
throw new FileLoadException("Cannot start the project check your Config Xml files");
}
}
public void updateaccumulation(int co)
{
SiteOwner1Root.Element("accumulation").Value = co.ToString();
SiteOwner1Root.Save(siteOwner1Path);
}
public int updatepasswords(int co)
{
SiteOwner1Root.Element("passwords").Value = co.ToString();
SiteOwner1Root.Save(siteOwner1Path);
return int.Parse(SiteOwner1Root.Element("passwords").Value);
}
public int Get_commission()
{
return int.Parse(SiteOwner1Root.Element("commission").Value);
}
public int Get_passwords()
{
return int.Parse(SiteOwner1Root.Element("passwords").Value);
}
public int Get_accumulation()
{
return int.Parse(SiteOwner1Root.Element("accumulation").Value);
}
#endregion
public IEnumerable<BankBranch> GetAllbanks(Func<BankBranch, bool> condition = null)
{
try
{
List<BankBranch> banks = GetBrunch_bank().ToList();
List<BankBranch> tmp = (from bank in banks
where condition(bank)
select bank).ToList();
return tmp;
}
catch (FileLoadException a)
{
throw a;
}
}
public IEnumerable<BankBranch> GetBrunch_bank()
{
List<BankBranch> banks = new List<BankBranch>();
XmlDocument doc = new XmlDocument();
doc.Load(@"atm.xml");
XmlNode rootNode = doc.DocumentElement;
XmlNodeList children = rootNode.ChildNodes;
foreach (XmlNode child in children)
{
BankBranch b = GetBranchByXmlNode(child);
if (b != null)
{
banks.Add(b);
}
}
return banks;
}
private static BankBranch GetBranchByXmlNode(XmlNode node)
{
if (node.Name != "BRANCH") return null;
BankBranch branch = new BankBranch();
XmlNodeList children = node.ChildNodes;
foreach (XmlNode child in children)
{
switch (child.Name)
{
case "Bank_Code":
branch.BankNumber = int.Parse(child.InnerText);
break;
case "Bank_Name":
branch.BankName = child.InnerText;
break;
case "Branch_Code":
branch.BranchNumber = int.Parse(child.InnerText);
break;
case "Address":
branch.BranchAddress = child.InnerText;
break;
case "City":
branch.BranchCity = child.InnerText;
break;
}
}
if (branch.BranchNumber > 0)
return branch;
return null;
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
object ob = e.Argument;
while (bankDownloaded == false)//continues until it downloads
{
try
{
DownloadBank();
Thread.Sleep(2000);//sleeps before trying
}
catch
{
}
}
GetBrunch_bank();//saves branches to ds
}
void DownloadBank()
{
string xmlLocalPath = @"atm.xml";
WebClient wc = new WebClient();
try
{
string xmlServerPath =
@"https://www.boi.org.il/en/BankingSupervision/BanksAndBranchLocations/Lists/BoiBankBranchesDocs/snifim_en.xml";
wc.DownloadFile(xmlServerPath, xmlLocalPath);
bankDownloaded = true;
}
catch
{
string xmlServerPath = @"http://www.jct.ac.il/~coshri/atm.xml";
wc.DownloadFile(xmlServerPath, xmlLocalPath);
bankDownloaded = true;
}
finally
{
wc.Dispose();
}
}
//#region GuestRequest
// //ADD
// public void AddGuestRequest(GuestRequest g)
// {
// List<GuestRequest> GuestRequestList = new List<GuestRequest>();
// if (!CheckGR(g.GuestRequestKey))
// {
// g.GuestRequestKey = Configuration.guestRequestKey++;
// SavaGRToXElement(g);
// }
// }
// public void SavaGRToXElement( GuestRequest p)
// {
// XElement GuestRequestKey = new XElement("GuestRequestKey", p.GuestRequestKey);
// XElement PrivateName = new XElement("PrivateName", p.PrivateName);
// XElement FamilyName = new XElement("FamilyName", p.FamilyName);
// XElement MailAddress = new XElement("MailAddress", p.MailAddress);
// XElement ID = new XElement("ID", p.ID);
// XElement Status = new XElement("Status", p.Status.ToString());
// XElement RegistrationDate = new XElement("RegistrationDate", p.RegistrationDate.ToString());
// XElement EntryDate = new XElement("EntryDate", p.EntryDate.ToString());
// XElement ReleaseDate = new XElement("ReleaseDate", p.ReleaseDate.ToString());
// XElement Area = new XElement("Area", p.Area.ToString());
// XElement SubArea = new XElement("SubArea", p.SubArea.ToString());
// XElement Type = new XElement("Type", p.Type.ToString());
// XElement Adults = new XElement("Adults", p.Adults);
// XElement Children = new XElement("Children", p.Children);
// XElement ChildrensAttractions = new XElement("ChildrensAttractions", p.ChildrensAttractions.ToString());
// XElement Room = new XElement("Room", p.Room);
// XElement Pool = new XElement("Pool", p.Pool.ToString());
// XElement Jacuzzi = new XElement("Jacuzzi", p.Jacuzzi.ToString());
// XElement Garden = new XElement("Garden", p.Garden.ToString());
// XElement Breakfast = new XElement("Breakfast", p.Breakfast);
// XElement Lunch = new XElement("Lunch", p.Lunch);
// XElement Dinner = new XElement("Dinner", p.Dinner);
// XElement Its_Signed = new XElement("Its_Signed", p.Its_Signed);
// XElement guestRequest = new XElement("guestRequest", GuestRequestKey, PrivateName, FamilyName, MailAddress, ID,
// Status, RegistrationDate, EntryDate, Area, SubArea, Type, Adults, Children, ChildrensAttractions,
// Room, Pool, Jacuzzi, Garden, Breakfast, Lunch, Dinner, Its_Signed);
// GuestRequestRoot.Add(guestRequest);
// GuestRequestRoot.Save(guestRequestPath);
// }
// public void LoadGuestRequests()
// {
// try {
// GuestRequestRoot = XElement.Load(guestRequestPath);
// }
// catch
// {
// throw new Exception("File upload problem");
// }
// }
// //Update
// public GuestRequest GetGRFromXElementT(int id)
// {
// LoadGuestRequests();
// GuestRequest guestRequest;
// try
// {
// guestRequest = (from item in GuestRequestRoot.Elements()
// where int.Parse(item.Element("GuestRequestKey").Value) == id
// select new GuestRequest()
// {
// GuestRequestKey = Convert.ToInt32(item.Element("GuestRequestKey").Value),
// PrivateName = item.Element("Name").Element("PrivateName").Value,
// FamilyName = item.Element("Name").Element("FamilyName").Value,
// MailAddress = item.Element("MailAddress").Value,
// Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), item.Element("Status").Value),
// RegistrationDate = new DateTime(int.Parse(item.Element("RegistrationDate").Element("YearReg").Value),
// int.Parse(item.Element("RegistrationDate").Element("MonthReg").Value),
// int.Parse(item.Element("RegistrationDate").Element("DayReg").Value)),
// EntryDate = new DateTime(int.Parse(item.Element("EntryDate").Element("YearEntry").Value),
// int.Parse(item.Element("EntryDate").Element("MonthEntry").Value),
// int.Parse(item.Element("EntryDate").Element("DayEntry").Value)),
// ReleaseDate = new DateTime(int.Parse(item.Element("ReleaseDate").Element("YearRelease").Value),
// int.Parse(item.Element("ReleaseDate").Element("MonthRelease").Value),
// int.Parse(item.Element("ReleaseDate").Element("DayRelease").Value)),
// Area = (AreasInTheCountry)Enum.Parse(typeof(AreasInTheCountry), item.Element("Area").Value),
// Type = (TypesOfVacation)Enum.Parse(typeof(TypesOfVacation), item.Element("Type").Value),
// Adults = Convert.ToInt32(item.Element("Adults").Value),
// Children = Convert.ToInt32(item.Element("Children").Value),
// Pool = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Pool").Value),
// Jacuzzi = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Jacuzzi").Value),
// Garden = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Garden").Value),
// ChildrensAttractions = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("ChildrensAttractions").Value),
// SubArea = (All)Enum.Parse(typeof(All), item.Element("Area").Value),
// Room = Convert.ToInt32(item.Element("Room").Value),
// ID = Convert.ToInt32(item.Element("ID").Value),
// Breakfast = item.Element("Breakfast").Value == "true",
// Lunch = item.Element("Lunch").Value == "true",
// Dinner = item.Element("Dinner").Value == "true",
// Its_Signed = item.Element("Its_Signed").Value == "true"
// }).FirstOrDefault();
// }
// catch
// {
// guestRequest = null;
// }
// return guestRequest;
// }
// public void UpdateGuestRequest(GuestRequest G)
// {
// LoadGuestRequests();
// try {
// if (CheckGR(G.GuestRequestKey))
// {
// (from item in GuestRequestRoot.Elements()
// where item.Element("GuestRequestKey").Value == G.GuestRequestKey.ToString()
// select item
// ).FirstOrDefault().Remove();
// SavaGRToXElement(G);
// }
// else
// throw new KeyNotFoundException("GuestRequest to update doesn't exist");
// }
// catch (Exception a)
// {
// throw a;
// }
// }
////get
//public IEnumerable<GuestRequest> Get_GuestRequestList()
// {
// LoadGuestRequests();
// List<GuestRequest> guestRequest;
// try
// {
// guestRequest = (from item in GuestRequestRoot.Elements()
// select new GuestRequest()
// {
// GuestRequestKey = Convert.ToInt32(item.Element("GuestRequestKey").Value),
// PrivateName = item.Element("Name").Element("PrivateName").Value,
// FamilyName = item.Element("Name").Element("FamilyName").Value,
// MailAddress = item.Element("MailAddress").Value,
// Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), item.Element("Status").Value),
// RegistrationDate = new DateTime(int.Parse(item.Element("RegistrationDate").Element("YearReg").Value),
// int.Parse(item.Element("RegistrationDate").Element("MonthReg").Value),
// int.Parse(item.Element("RegistrationDate").Element("DayReg").Value)),
// EntryDate = new DateTime(int.Parse(item.Element("EntryDate").Element("YearEntry").Value),
// int.Parse(item.Element("EntryDate").Element("MonthEntry").Value),
// int.Parse(item.Element("EntryDate").Element("DayEntry").Value)),
// ReleaseDate = new DateTime(int.Parse(item.Element("ReleaseDate").Element("YearRelease").Value),
// int.Parse(item.Element("ReleaseDate").Element("MonthRelease").Value),
// int.Parse(item.Element("ReleaseDate").Element("DayRelease").Value)),
// Area = (AreasInTheCountry)Enum.Parse(typeof(AreasInTheCountry), item.Element("Area").Value),
// Type = (TypesOfVacation)Enum.Parse(typeof(TypesOfVacation), item.Element("Type").Value),
// Adults = Convert.ToInt32(item.Element("Adults").Value),
// Children = Convert.ToInt32(item.Element("Children").Value),
// Pool = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Pool").Value),
// Jacuzzi = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Jacuzzi").Value),
// Garden = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Garden").Value),
// ChildrensAttractions = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("ChildrensAttractions").Value),
// SubArea = (All)Enum.Parse(typeof(All), item.Element("Area").Value),
// Room = Convert.ToInt32(item.Element("Room").Value),
// ID = Convert.ToInt32(item.Element("ID").Value),
// Breakfast = item.Element("Breakfast").Value == "true",
// Lunch = item.Element("Lunch").Value == "true",
// Dinner = item.Element("Dinner").Value == "true",
// Its_Signed = item.Element("Its_Signed").Value == "true"
// }).ToList();
// }
// catch (Exception)
// {
// guestRequest = null;
// }
// return guestRequest;
// }
////ADD
//public void AddHostingUnit(HostingUnit h)
//{
// List<HostingUnit> GuestRequestList = new List<HostingUnit>();
// if (!CheckHU(h.HostingUnitKey))
// {
// h.HostingUnitKey = Configuration.hostingUnitKey++;
// SavaHUToXElement(h);
// }
//}
//public bool CheckHU(int key)
//{
// try
// {
// LoadHostingUnit();
// var tmp = from item in HostingUnitRoot.Elements()
// where item.Element("HostingUnitKey").Value == key.ToString()
// select item;
// if (tmp.ToList() == null)
// return false;
// else
// return true;
// }
// catch (FileLoadException a)
// {
// throw a;
// }
//}
//public void SavaHUToXElement(HostingUnit p)
//{
// XElement HostingUnitKey = new XElement("GuestRequestKey", p.HostingUnitKey);
// XElement HostingUnitName = new XElement("HostingUnitName", p.HostingUnitName);
// XElement Diary = new XElement("Diary");
// for (int i = 0; i < 12; i++)
// {
// for (int j = 0; j < 31; j++)
// {
// Diary.Add(p.Diary[i, j].ToString() + " ");
// }
// }
// XElement BankNumber = new XElement("BankNumber", p.Owner.BankAccount.BankNumber);
// XElement BankName = new XElement("BankName", p.Owner.BankAccount.BankName);
// XElement BranchNumber = new XElement("BranchNumber", p.Owner.BankAccount.BranchNumber);
// XElement BranchAddress = new XElement("BranchAddress", p.Owner.BankAccount.BranchAddress);
// XElement BranchCity = new XElement("BranchCity", p.Owner.BankAccount.BranchCity);
// XElement BankAccountNumber = new XElement("BranchCity", p.Owner.BankAccount.BankAccountNumber);
// XElement BankAccount = new XElement("BankBranchDetails", BankNumber, BankName, BranchNumber,
// BranchAddress, BranchCity, BankAccountNumber);
// XElement HostKey = new XElement("HostKey", p.Owner.HostKey);
// XElement PrivateName = new XElement("PrivateName", p.Owner.PrivateName);
// XElement FamilyName = new XElement("FamilyName", p.Owner.FamilyName);
// XElement PhoneNumber = new XElement("PhoneNumber", p.Owner.PhoneNumber);
// XElement MailAddress = new XElement("MailAddress", p.Owner.MailAddress);
// XElement CollectionClearance = new XElement("CollectionClearance", p.Owner.CollectionClearance);
// XElement Name = new XElement("Name", PrivateName, FamilyName);
// XElement Owner = new XElement("Owner", HostKey, Name, PhoneNumber, MailAddress, CollectionClearance,
// BankAccount, BankAccountNumber);
// XElement Area = new XElement("Area", p.Area.ToString());
// XElement SubArea = new XElement("SubArea", p.SubArea.ToString());
// XElement Type = new XElement("Type", p.Type.ToString());
// XElement Adults = new XElement("Adults", p.Adults);
// XElement Children = new XElement("Children", p.Children);
// XElement ChildrensAttractions = new XElement("ChildrensAttractions", p.ChildrensAttractions.ToString());
// XElement Room = new XElement("Room", p.Room);
// XElement Pool = new XElement("Pool", p.Pool.ToString());
// XElement Jacuzzi = new XElement("Jacuzzi", p.Jacuzzi.ToString());
// XElement Garden = new XElement("Garden", p.Garden.ToString());
// XElement Breakfast = new XElement("Breakfast", p.Breakfast);
// XElement Lunch = new XElement("Lunch", p.Lunch);
// XElement Dinner = new XElement("Dinner", p.Dinner);
// XElement hostingUnit = new XElement("HostingUnit", HostingUnitKey, HostingUnitName, Diary, Owner, Area, Type, SubArea, Type
// , Adults, Children, ChildrensAttractions, Room, Pool, Jacuzzi, Garden, Breakfast, Lunch, Dinner);
// HostingUnitRoot.Add(hostingUnit);
// HostingUnitRoot.Save(hostingUnitPath);
//}
//public void LoadHostingUnit()
//{
// try
// {
// HostingUnitRoot = XElement.Load(hostingUnitPath);
// }
// catch
// {
// throw new Exception("File upload problem");
// }
//}
////Update
//public HostingUnit GetHUFromXElementT(int id)
//{
//LoadHostingUnit();
// HostingUnit hostingUnit;
// try
// {
// hostingUnit = (from item in HostingUnitRoot.Elements()
// where int.Parse(item.Element("HostingUnitKey").Value) == id
// select new HostingUnit()
// {
// HostingUnitKey = Convert.ToInt32(item.Element("HostingUnitKey").Value),
// HostingUnitName = item.Element("HostingUnitName").Value,
// Owner = new Host()
// {
// HostKey = Convert.ToInt32(item.Element("Owner").Element("HostKey").Value),
// PrivateName = item.Element("Owner").Element("Name").Element("PrivateName").Value,
// FamilyName = item.Element("Owner").Element("Name").Element("FamilyName").Value,
// PhoneNumber = Convert.ToInt32(item.Element("Owner").Element("PhoneNumber").Value),
// MailAddress = item.Element("Owner").Element("MailAddress").Value,
// CollectionClearance = item.Element("Owner").Element("CollectionClearance").Value == "true",
// BankAccount = new BankBranch()
// {
// BankNumber = Convert.ToInt32(item.Element("Owner").Element("BankAccount").Element("BankNumber").Value),
// BankName = item.Element("Owner").Element("BankAccount").Element("BankName").Value,
// BranchNumber = Convert.ToInt32(item.Element("Owner").Element("BankAccount").Element("BranchNumber").Value),
// BranchAddress = item.Element("Owner").Element("BankAccount").Element("BranchAddress").Value,
// BranchCity = item.Element("Owner").Element("BankAccount").Element("BranchCity").Value,
// BankAccountNumber = Convert.ToInt32(item.Element("Owner").Element("BankAccount").Value),
// },
// },
// Area = (AreasInTheCountry)Enum.Parse(typeof(AreasInTheCountry), item.Element("Area").Value),
// Type = (TypesOfVacation)Enum.Parse(typeof(TypesOfVacation), item.Element("Type").Value),
// Adults = Convert.ToInt32(item.Element("Adults").Value),
// Children = Convert.ToInt32(item.Element("Children").Value),
// Pool = item.Element("Pool").Value == "true",
// Jacuzzi = item.Element("Jacuzzi").Value == "true",
// Garden = item.Element("Garden").Value == "true",
// ChildrensAttractions = item.Element("ChildrensAttractions").Value == "true",
// SubArea = (All)Enum.Parse(typeof(All), item.Element("SubArea").Value),
// Room = Convert.ToInt32(item.Element("Room").Value),
// Breakfast = item.Element("Breakfast").Value == "true",
// Lunch = item.Element("Lunch").Value == "true",
// Dinner = item.Element("Dinner").Value == "true",
// }).FirstOrDefault();
// }
// catch
// {
// hostingUnit = null;
// }
// return hostingUnit;
//}
//public void UpdateGuestRequest(GuestRequest G)
//{
//LoadHostingUnit();
// try
// {
// if (CheckGR(G.GuestRequestKey))
// {
// (from item in GuestRequestRoot.Elements()
// where item.Element("GuestRequestKey").Value == G.GuestRequestKey.ToString()
// select item
// ).FirstOrDefault().Remove();
// SavaGRToXElement(G);
// }
// else
// throw new KeyNotFoundException("GuestRequest to update doesn't exist");
// }
// catch (Exception a)
// {
// throw a;
// }
//}
////get
//public IEnumerable<GuestRequest> Get_GuestRequestList()
//{
//LoadHostingUnit();
// List<GuestRequest> guestRequest;
// try
// {
// guestRequest = (from item in GuestRequestRoot.Elements()
// select new GuestRequest()
// {
// GuestRequestKey = Convert.ToInt32(item.Element("GuestRequestKey").Value),
// PrivateName = item.Element("Name").Element("PrivateName").Value,
// FamilyName = item.Element("Name").Element("FamilyName").Value,
// MailAddress = item.Element("MailAddress").Value,
// Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), item.Element("Status").Value),
// RegistrationDate = new DateTime(int.Parse(item.Element("RegistrationDate").Element("YearReg").Value),
// int.Parse(item.Element("RegistrationDate").Element("MonthReg").Value),
// int.Parse(item.Element("RegistrationDate").Element("DayReg").Value)),
// EntryDate = new DateTime(int.Parse(item.Element("EntryDate").Element("YearEntry").Value),
// int.Parse(item.Element("EntryDate").Element("MonthEntry").Value),
// int.Parse(item.Element("EntryDate").Element("DayEntry").Value)),
// ReleaseDate = new DateTime(int.Parse(item.Element("ReleaseDate").Element("YearRelease").Value),
// int.Parse(item.Element("ReleaseDate").Element("MonthRelease").Value),
// int.Parse(item.Element("ReleaseDate").Element("DayRelease").Value)),
// Area = (AreasInTheCountry)Enum.Parse(typeof(AreasInTheCountry), item.Element("Area").Value),
// Type = (TypesOfVacation)Enum.Parse(typeof(TypesOfVacation), item.Element("Type").Value),
// Adults = Convert.ToInt32(item.Element("Adults").Value),
// Children = Convert.ToInt32(item.Element("Children").Value),
// Pool = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Pool").Value),
// Jacuzzi = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Jacuzzi").Value),
// Garden = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("Garden").Value),
// ChildrensAttractions = (ChoosingAttraction)Enum.Parse(typeof(ChoosingAttraction), item.Element("ChildrensAttractions").Value),
// SubArea = (All)Enum.Parse(typeof(All), item.Element("Area").Value),
// Room = Convert.ToInt32(item.Element("Room").Value),
// ID = Convert.ToInt32(item.Element("ID").Value),
// Breakfast = item.Element("Breakfast").Value == "true",
// Lunch = item.Element("Lunch").Value == "true",
// Dinner = item.Element("Dinner").Value == "true",
// Its_Signed = item.Element("Its_Signed").Value == "true"
// }).ToList();
// }
// catch (Exception)
// {
// guestRequest = null;
// }
// return guestRequest;
//}
// if (!File.Exists(BankPath))
// new Thread(() =>
// {
// do
// {
// try
// {
// LoadBank();
// BankFlag = true;
// }
// catch (Exception)
// {
// }
// Thread.Sleep(2000);
// } while (!BankFlag);
// }).Start();
// if (!File.Exists(siteOwner1Path))
// {
// CreateSiteOwner1();
// }
// else
// LoadSiteOwner();
//}
}
}<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/LinqHu.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BE;
using BL;
namespace PLWPF
{
/// <summary>
/// Interaction logic for LinqHu.xaml
/// </summary>
public partial class LinqHu : Window
{
BL.IBL bl;
public LinqHu()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
bl = BL.FactoryBL.GetBL();
}
private void AvailibleUnit_Click(object sender, RoutedEventArgs e)
{
if (EntryDate_DatePicker.SelectedDate != null && SumOFday.Text != "")
{
EntryDate_DatePicker.SelectedDate = null;
SumOFday.Text = "";
}
Bhu.Visibility = Visibility.Visible;
}
private void AllUnit_Click(object sender, RoutedEventArgs e)
{
ListView_HU.ItemsSource = bl.Get_HostingUnitsListB();
}
private void BusyUnit_Click(object sender, RoutedEventArgs e)
{
if (EntryDate_DatePicker.SelectedDate != null && SumOFday.Text != "")
{ EntryDate_DatePicker.SelectedDate = null;
SumOFday.Text = "";
}
BUSY.Visibility = Visibility.Visible;
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void AvailibleClickCheck(object sender, RoutedEventArgs e)
{
if (EntryDate_DatePicker.SelectedDate!= null && SumOFday.Text != "")
ListView_HU.ItemsSource = bl.AvailableUnitList(EntryDate_DatePicker.SelectedDate.Value.Date, int.Parse(SumOFday.Text));
Bhu.Visibility = Visibility.Collapsed;
}
private void BusyClickCheck(object sender, RoutedEventArgs e)
{
if (EntryDate_DatePicker.SelectedDate != null && SumOFday.Text != "")
ListView_HU.ItemsSource = bl.BusyUnitList(EntryDate_DatePicker.SelectedDate.Value.Date, int.Parse(SumOFday.Text));
BUSY.Visibility = Visibility.Collapsed;
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/PLWPF/PrivateHost.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BL;
using BE;
namespace PLWPF
{
/// <summary>
/// Interaction logic for PrivateHost.xaml
/// </summary>
public partial class PrivateHost : Window
{
BL.IBL bl;
Host H = new Host();
Order order = new Order();
public PrivateHost()
{
InitializeComponent();
NavigationService.NavigationStack.Push(this);
bl = BL.FactoryBL.GetBL();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
if (IdTxt.Text.Length == 9 )
{
grHost.Visibility = Visibility.Visible;
H = bl.CheckId(int.Parse(IdTxt.Text));
}
else
{
throw new FormatException("הכנס ת.ז בעלת 9 ספרות");
}
}
catch (Exception exp)
{
grHost.Visibility = Visibility.Collapsed;
MessageBox.Show(exp.Message);
}
}
void BackButton_Click(object sender, RoutedEventArgs e)
{
NavigationService.NavigateBack();
}
private void Update_Button_Click(object sender, RoutedEventArgs e)
{
UpdateHostingUnit Uhu = new UpdateHostingUnit(H);
Uhu.Show();
this.Visibility = Visibility.Collapsed;
}
private void OrderBtn_Upd_Click(object sender, RoutedEventArgs e)
{
UpdateOrder gso = new UpdateOrder(H);
gso.Show();
this.Visibility = Visibility.Collapsed;
}
private void Order_Button_Click(object sender, RoutedEventArgs e)
{
grOrder.Visibility = Visibility.Visible;
}
private void OrderBtn_Add_Click(object sender, RoutedEventArgs e)
{
AddOrder AO = new AddOrder(H);
AO.Show();
this.Visibility = Visibility.Collapsed;
}
private void Delete_Button_Click(object sender, RoutedEventArgs e)
{
DeleteHostingUnit Dhu = new DeleteHostingUnit(H);
Dhu.Show();
this.Visibility = Visibility.Collapsed;
}
private void IdTxt_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void grOrder_MouseLeave(object sender, RoutedEventArgs e)
{
grOrder.Visibility = Visibility.Collapsed;
}
private void Button_Click_AddHU(object sender, RoutedEventArgs e)
{
AddHostingUnitW w1 = new AddHostingUnitW(H);
w1.Show();
this.Visibility = Visibility.Collapsed;
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/DAL/Cloning.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
namespace DAL
{
public static class Cloning
{
public static HostingUnit Clone(this HostingUnit original)
{
HostingUnit target = new HostingUnit();
target.Adults = original.Adults;
target.Area = original.Area;
target.Children = original.Children;
target.ChildrensAttractions = original.ChildrensAttractions;
target.Diary= original.Diary;
target.Garden = original.Garden;
target.HostingUnitKey = original.HostingUnitKey;
target.HostingUnitName = original.HostingUnitName;
target.Jacuzzi = original.Jacuzzi;
target.Owner= original.Owner;
target.Pool= original.Pool;
target.Breakfast = original.Breakfast;
target.Dinner = original.Dinner;
target.Lunch = original.Lunch;
target.Room = original.Room;
target.Type = original.Type;
target.Adults = original.Adults;
return target;
}
public static GuestRequest Clone(this GuestRequest original)
{
GuestRequest target = new GuestRequest();
target.Adults = original.Adults;
target.Area = original.Area;
target.Children = original.Children;
target.ID = original.ID;
target.Room = original.Room;
target.ChildrensAttractions = original.ChildrensAttractions;
target.Garden = original.Garden;
target.Jacuzzi = original.Jacuzzi;
target.Pool = original.Pool;
target.FamilyName= original.FamilyName;
target.GuestRequestKey = original.GuestRequestKey;
target.MailAddress = original.MailAddress;
target.PrivateName = original.PrivateName;
target.RegistrationDate = original.RegistrationDate;
target.ReleaseDate= original.ReleaseDate;
target.Status= original.Status;
target.SubArea = original.SubArea;
target.Type = original.Type;
target.Breakfast = original.Breakfast;
target.Dinner = original.Dinner;
target.Lunch = original.Lunch;
return target;
}
public static Host Clone(this Host original)
{
Host target = new Host();
target.BankAccount = original.BankAccount;
target.CollectionClearance = original.CollectionClearance;
target.FamilyName = original.FamilyName;
target.PhoneNumber = original.PhoneNumber;
target.HostKey= original.HostKey;
target.MailAddress = original.MailAddress;
target.PrivateName= original.PrivateName;
return target;
}
//public static SiteOwner1 Clone(this SiteOwner1 original)
//{
// SiteOwner1 target = new SiteOwner1();
// target.Passwords = original.Passwords;
// // target.Commission = original.Commission;
// return target;
//}
public static BankBranch Clone(this BankBranch original)
{
BankBranch target = new BankBranch();
target.BankName = original.BankName;
target.BankNumber= original.BankNumber;
target.BranchAddress = original.BranchAddress;
target.BranchCity = original.BranchCity;
target.BranchNumber= original.BranchNumber;
return target;
}
public static Order Clone(this Order original)
{
Order target = new Order();
target.CreateDate= original.CreateDate;
target.GuestRequestKey = original.GuestRequestKey;
target.HostingUnitKey = original.HostingUnitKey;
target.OrderDate= original.OrderDate;
target.OrderKey = original.OrderKey;
target.Status = original.Status;
return target;
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/BE/BankBranch.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public class BankBranch : IClonable
{
private int bankNumber;
public int BankNumber { get => bankNumber; set => bankNumber = value; }
private string bankName;
public string BankName { get => bankName; set => bankName = value; }
private int branchNumber;
public int BranchNumber { get => branchNumber; set => branchNumber = value; }
private string branchAddress;
public string BranchAddress { get => branchAddress; set => branchAddress = value; }
private string branchCity;
public string BranchCity { get => branchCity; set => branchCity = value; }
private int bankAccountNumber;
public int BankAccountNumber { get => bankAccountNumber; set => bankAccountNumber = value; }
public override string ToString()
{
string BankAccount = " ";
return BankAccount += string.Format("Bank Number: {0}\n" + "Bank Name:{1}\n" + "Branch Number:{2}\n" + "Branch Address: {3}\n" + "Branch City: {4}\n" + "BankAccountNumber: {4}\n",
BankNumber, BankName, BranchNumber, BranchAddress, BranchCity, BankAccountNumber);
}
}
}
<file_sep>/Project01_5404_8555_dotNet5780/Project01_5404_8555_dotNet5780/BE/SiteOwner.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BE
{
public class SiteOwner : IClonable
{
private static int commission = 10;
public static int Commission { get => commission; set => commission = value;}
public override string ToString()
{
string siteOwner = " ";
return siteOwner += string.Format("SiteOwner Commission : {0}\n", commission);
}
}
}
| 858fc2d40f7a21d6600935844635a6f56afa73a6 | [
"C#"
] | 37 | C# | ruthico/Project01_5404_8555_dotNet5780 | 2d9b93759ca01a64ae1eb3ab30d2c243d77c602c | 251ada6b24e5dd870906f441fa4c390b6c8e5e9c |
refs/heads/master | <file_sep>const button = document.querySelector(".bm-button")
document.addEventListener("DOMContentLoaded", () => {
if ("dark" === localStorage.theme) {
document.documentElement.classList.add("dark")
}
})
button.addEventListener("click", () => {
document.documentElement.classList.toggle("dark");
console.log(document.documentElement.classList)
if (document.documentElement.classList.contains("dark")) {
localStorage.theme = "dark"
} else {
localStorage.theme = "light"
}
}
);
<file_sep>DarkMode made with tailwind css
[Here](https://janu8ry.github.io/darkmodetest/public/)
| e37d5872320aebeaa1ad9876cf130b159cf773c1 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | janu8ry/darkmodetest | 5dc7859b7fb3977fbb6d369853646d73416bb84d | 14cbe7cea83b5fba666b711656cff37ee5f880e4 |
refs/heads/master | <repo_name>mylukin/LazyFunc<file_sep>/smtpauth.py
#!/usr/bin/python
"""smtpauth.py: command-line smtp test mail sender
https://github.com/turbodog/python-smtp-mail-sending-tester
Usage: python smtpauth.py [options] fromaddress toaddress serveraddress
Examples:
python smtpauth.py <EMAIL> <EMAIL> <EMAIL>
python smtpauth.py --debuglevel 1 --usetls -u bob -p xyzzy "Bob <<EMAIL>>" <EMAIL> mail.example.com
At verbose == False and debuglevel == 0, smtpauth will either succeed silently or print an error. Setting verbose or a debuglevel to 1 will generate intermediate output.
See also http://docs.python.org/library/smtplib.html
"""
__version__ = "1.0"
__author__ = "Lukin (<EMAIL>)"
__copyright__ = "(C) 2016 Lukin GNU GPL 2 or 3."
import smtplib
from time import strftime
import sys
from optparse import OptionParser
serveraddr = ""
usage = "Usage: %prog [options] serveraddress"
parser = OptionParser(usage=usage)
parser.set_defaults(usetls=False)
parser.set_defaults(usessl=False)
parser.set_defaults(serverport=25)
parser.set_defaults(SMTP_USER="")
parser.set_defaults(SMTP_PASS="")
parser.set_defaults(debuglevel=0)
parser.set_defaults(verbose=False)
parser.add_option("-t", "--usetls", action="store_true", dest="usetls", default=False,
help="Connect using TLS, default is false")
parser.add_option("-s", "--usessl", action="store_true", dest="usessl", default=False,
help="Connect using SSL, default is false")
parser.add_option("-n", "--port", action="store", type="int", dest="serverport", help="SMTP server port", metavar="nnn")
parser.add_option("-u", "--username", action="store", type="string", dest="SMTP_USER", help="SMTP server auth username",
metavar="username")
parser.add_option("-p", "--password", action="store", type="string", dest="SMTP_PASS", help="SMTP server auth password",
metavar="password")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
help="Verbose message printing")
parser.add_option("-d", "--debuglevel", type="int", dest="debuglevel", help="Set to 1 to print smtplib.send messages",
metavar="n")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.print_help()
parser.error("incorrect number of arguments")
sys.exit(-1)
serveraddr = args[0]
if options.verbose:
print('usetls:', options.usetls)
print('usessl:', options.usessl)
print('server address:', serveraddr)
print('server port:', options.serverport)
print('smtp username:', options.SMTP_USER)
print('smtp password: *****')
print('smtplib debuglevel:', options.debuglevel)
server = None
if options.usessl:
server = smtplib.SMTP_SSL()
else:
server = smtplib.SMTP()
server.set_debuglevel(options.debuglevel)
server.connect(serveraddr, options.serverport)
server.ehlo()
if options.usetls: server.starttls()
server.ehlo()
if options.SMTP_USER != "":
try:
code, resp = server.login(options.SMTP_USER, options.SMTP_PASS)
print code
except Exception,e:
code, resp = e
print code
server.quit()
<file_sep>/QQWry.php
<?php
/**
* QQWry.php
*
* @author Lukin <<EMAIL>>
* @version $Id$
* @datetime 2014-06-02 21:23
*/
class QQWry {
private $fp = null;
private $start = 0, $end = 0, $ctype = 0;
private $fstart = 0, $lstart = 0, $offset = 0;
// QQWry instance
private static $instance;
/**
* Returns QQWry instance.
*
* @static
* @param string $dat_file
* @return QQWry
*/
public static function &instance($dat_file) {
if (!self::$instance) {
self::$instance = new QQWry($dat_file);
}
return self::$instance;
}
/**
* 翻译
*
* @param string $text
* @return mixed
*/
private static function __($text) {
if (function_exists('__')) {
return __($text);
} else {
return $text;
}
}
public function __construct($dat_file) {
if (is_file($dat_file)) {
$this->fp = fopen($dat_file,'rb');
}
}
private function init() {
$this->start = $this->end = $this->ctype = $this->fstart = $this->lstart = $this->offset = 0;
}
private function start($number) {
fseek($this->fp, $this->fstart + $number * 7);
$buf = fread($this->fp, 7);
$this->offset = ord($buf[4]) + (ord($buf[5]) * 256) + (ord($buf[6]) * 256 * 256);
$this->start = ord($buf[0]) + (ord($buf[1]) * 256) + (ord($buf[2]) * 256 * 256) + (ord($buf[3]) * 256 * 256 * 256);
return $this->start;
}
private function end() {
fseek($this->fp, $this->offset);
$buf = fread($this->fp, 5);
$this->end = ord($buf[0]) + (ord($buf[1]) * 256) + (ord($buf[2]) * 256 * 256) + (ord($buf[3]) * 256 * 256 * 256);
$this->ctype = ord($buf[4]);
return $this->end;
}
private function get_addr() {
$result = array();
switch ($this->ctype) {
case 1:
case 2:
$result['Country'] = $this->get_str($this->offset + 4);
$result['Local'] = (1 == $this->ctype) ? '' : $this->get_str($this->offset + 8);
break;
default :
$result['Country'] = $this->get_str($this->offset + 4);
$result['Local'] = $this->get_str(ftell($this->fp));
}
return $result;
}
private function get_str($offset) {
$result = '';
while (true) {
fseek($this->fp, $offset);
$flag = ord(fgetc($this->fp));
if ($flag == 1 || $flag == 2) {
$buf = fread($this->fp, 3);
if ($flag == 2) {
$this->ctype = 2;
$this->offset = $offset - 4;
}
$offset = ord($buf[0]) + (ord($buf[1]) * 256) + (ord($buf[2]) * 256 * 256);
} else {
break;
}
}
if ($offset < 12) return $result;
fseek($this->fp, $offset);
while (true) {
$c = fgetc($this->fp);
if (ord($c[0]) == 0) break;
$result.= $c;
}
return $result;
}
public function ip2addr($ipaddr) {
if (!$this->fp) return $ipaddr;
if (strpos($ipaddr, '.') !== false) {
if (preg_match('/^(127)/', $ipaddr))
return self::__('本地');
$ip = sprintf('%u',ip2long($ipaddr));
} else {
$ip = $ipaddr;
}
$this->init();
fseek($this->fp, 0);
$buf = fread($this->fp, 8);
$this->fstart = ord($buf[0]) + (ord($buf[1])*256) + (ord($buf[2])*256*256) + (ord($buf[3])*256*256*256);
$this->lstart = ord($buf[4]) + (ord($buf[5])*256) + (ord($buf[6])*256*256) + (ord($buf[7])*256*256*256);
$count = floor(($this->lstart - $this->fstart) / 7);
if ($count <= 1) {
fclose($this->fp);
return $ipaddr;
}
$start = 0;
$end = $count;
while ($start < $end - 1)
{
$number = floor(($start + $end) / 2);
$this->start($number);
if ($ip == $this->start) {
$start = $number;
break;
}
if ($ip > $this->start)
$start = $number;
else
$end = $number;
}
$this->start($start);
$this->end();
if (($this->start <= $ip) && ($this->end >= $ip)) {
$result = $this->get_addr();
} else {
$result = array(
'Country' => self::__('未知'),
'Local' => '',
);
}
$result = trim(implode(' ', $result));
$result = iconv('GBK', 'UTF-8', $result);
return $result;
}
public function __destruct() {
if ($this->fp) fclose($this->fp);
}
} <file_sep>/Validate.php
<?php
// 数字
define('VALIDATE_IS_NUMERIC','IS_NUMERIC');
// 字母
define('VALIDATE_IS_LETTERS','IS_LETTERS');
//电子邮箱
define('VALIDATE_IS_EMAIL','IS_EMAIL');
// 超链接
define('VALIDATE_IS_URL','IS_URL');
// 逗号分隔的数字列表
define('VALIDATE_IS_LIST','IS_LIST');
// 字母、数字、下划线、杠
define('VALIDATE_IS_CNUS','IS_CNUS');
// 字母、数字、下划线、杠、逗号、[、]
define('VALIDATE_IS_CNUSO','IS_CNUSO');
// 文件路径
define('VALIDATE_IS_PATH','IS_PATH');
// IP地址
define('VALIDATE_IS_IPADDR','IS_IPADDR');
// 不能为空
define('VALIDATE_EMPTY', 'EMPTY');
// 验证长度
define('VALIDATE_LENGTH','LENGTH');
// 两个值是否相等
define('VALIDATE_EQUAL','EQUAL');
/**
* 验证类
*
* @author Lukin <<EMAIL>>
* @version $Id$
*/
class Validate {
// 错误
private $errors = array();
/**
* 字符串验证
*
* @static
* @param string $str
* @param string $type 验证类型,常量或者正则表达式
* @return bool
*/
public static function is($str,$type){
switch ($type) {
case VALIDATE_IS_NUMERIC: case 'IS_NUMERIC':
$pattern = '/^\d+$/';
break;
case VALIDATE_IS_LETTERS: case 'IS_LETTERS':
$pattern = '/^[a-z]+$/i';
break;
case VALIDATE_IS_EMAIL: case 'IS_EMAIL':
$pattern = '/^\w+([\-\+\.]\w+)*@\w+([\-\.]\w+)*\.\w+([\-\.]\w+)*$/i';
break;
case VALIDATE_IS_URL: case 'IS_URL':
$pattern = '/^(http|https|ftp)\:(\/\/|\\\\)(([\w\/\\\+\-~`@\:%])+\.)+([\w\/\\\.\=\?\+\-~`@\'\:!%#]|(&)|&)+/i';
break;
case VALIDATE_IS_LIST: case 'IS_LIST':
$pattern = '/^[\d\,\.]+$/i';
break;
case VALIDATE_IS_CNUS: case 'IS_CNUS':
$pattern = '/^[\w\-]+$/i';
break;
case VALIDATE_IS_CNUSO: case 'IS_CNUSO':
$pattern = '/^[\w\,\/\-\[\]]+$/i';
break;
case VALIDATE_IS_PATH: case 'IS_PATH':
$pattern = '/^[^\:\*\<\>\|\\\\]+$/';
break;
case VALIDATE_IS_IPADDR: case 'IS_IPADDR':
$pattern = '/^(?:\d{1,3}\.){3}(?:\d{1,3})$/';
break;
default: // 自定义正则
$pattern = $type;
break;
}
return preg_match($pattern,$str);
}
/**
* 验证规则
*
* @example:
* 1.array('field',VALIDATE_TYPE,__('alert text'),params)
* 2.array(
* array('field',VALIDATE_TYPE,__('alert text'),params),
* array('field',VALIDATE_TYPE,__('alert text'),params)
* )
* @return bool|mixed
*/
public function check(){
$args = func_get_args();
if (is_array($args[0])) {
// Use method 2 rule.
if (is_array($args[0][0])) {
foreach ($args[0] as $rule) {
if (!$this->check($rule)) break;
}
}
// Use method 1 rule.
else {
return call_user_func_array(array(&$this,'check'),$args[0]);
}
} else {
// Validate single rule.
$error = false;
$value = isset($_POST[$args[0]]) ? rawurldecode(trim($_POST[$args[0]])) : null; // POST值
$type = $args[1]; // 类型
$text = $args[2]; // 提示文字
switch ($type) {
case VALIDATE_EMPTY: case 'IS_EMPTY':
if (empty($value)) $error = $text;
break;
case VALIDATE_LENGTH: case 'LENGTH_LIMIT':
if (!is_numeric($args[3]) && strpos($args[3],'-')!==false) {
$as = explode('-',$args[3]);
$args[3] = $as[0];
$args[4] = $as[1];
}
if (mb_strlen($value,'UTF-8') < (int)$args[3]
|| mb_strlen($value,'UTF-8') > (int)$args[4]) {
if ($args[3]) {
$error = sprintf($text,$args[3],$args[4]);
} else {
$error = sprintf($text,$args[4]);
}
}
break;
case VALIDATE_EQUAL: case 'IS_EQUAL':
$value1 = isset($_POST[$args[3]]) ? trim($_POST[$args[3]]) : null;
if ($value != $value1) $error = $text;
break;
case false: case 'FALSE':
$error = $text;
break;
default:
if (!$this->is($value,$type)) $error = $text;
break;
}
// 没有错误信息
if (!$error) return true;
$this->set_error($args[0], $error);
}
return false;
}
/**
* 没有错误
*
* @return bool
*/
public function is_ok(){
if (empty($this->errors)) {
return true;
} else {
echo json_encode(array('status' => 'validate', 'errors' => $this->errors));
}
}
/**
* 有错误
*
* @return array|bool
*/
public function is_error() {
return empty($this->errors) ? false : $this->errors;
}
/**
* 获取错误
*
* @return array
*/
public function get_error() {
return $this->errors;
}
/**
* 设置错误信息
*
* @param string $id
* @param string $text
* @return void
*/
private function set_error($id, $text){
static $i = 0;
$this->errors[$i]['id'] = $id;
$this->errors[$i]['text'] = $text;
$i++;
}
}
<file_sep>/LazyFunc.php
<?php
/**
* LazyFunc.php
*
* @author Lukin <<EMAIL>>
* @version $Id$
* @datetime 2014-06-02 21:13
*/
/**
* 块开始
*
* @return void
*/
function ob_block_start() {
global $lazy_tmp_content;
$lazy_tmp_content = ob_get_contents();
ob_clean();
ob_start();
}
/**
* get ob content for tag
*
* @param string $tag
* @param string $join
* @return array|null
*/
function ob_get_content($tag, $join = "\r\n") {
global $lazy_ob_contents;
if (isset($lazy_ob_contents[$tag])) {
array_multisort($lazy_ob_contents[$tag]['order'], SORT_DESC, $lazy_ob_contents[$tag]['content']);
return implode($join, $lazy_ob_contents[$tag]['content']);
}
return null;
}
/**
* set ob content for tag
*
* @param string $tag
* @param int $order
* @return array|null
*/
function ob_block_end($tag, $order = 0) {
global $lazy_ob_contents, $lazy_tmp_content;
$content = ob_get_contents();
ob_clean();
if (!isset($lazy_ob_contents[$tag])) $lazy_ob_contents[$tag] = array();
$lazy_ob_contents[$tag]['content'][] = $content;
$lazy_ob_contents[$tag]['order'][] = $order;
if ($lazy_tmp_content) {
echo $lazy_tmp_content;
$lazy_tmp_content = '';
}
return ob_get_content($tag);
}
/**
* 添加过滤器
*
* @param string $tag
* @param string $function
* @param int $priority
* @param int $accepted_args
* @return bool
*/
function add_filter($tag, $function, $priority = 10, $accepted_args = 1) {
global $lazy_filter;
static $filter_id_count = 0;
if (is_string($function)) {
$idx = $function;
} else {
if (is_object($function)) {
// Closures are currently implemented as objects
$function = array($function, '');
} else {
$function = (array)$function;
}
if (is_object($function[0])) {
// Object Class Calling
if (function_exists('spl_object_hash')) {
$idx = spl_object_hash($function[0]) . $function[1];
} else {
$idx = get_class($function[0]) . $function[1];
if (!isset($function[0]->lwp_filter_id)) {
$idx .= isset($lazy_filter[$tag][$priority]) ? count((array)$lazy_filter[$tag][$priority])
: $filter_id_count;
$function[0]->lwp_filter_id = $filter_id_count;
++$filter_id_count;
} else {
$idx .= $function[0]->lwp_filter_id;
}
}
} else if (is_string($function[0])) {
// Static Calling
$idx = $function[0] . $function[1];
}
}
$lazy_filter[$tag][$priority][$idx] = array('function' => $function, 'accepted_args' => $accepted_args);
return true;
}
/**
* Call the functions added to a filter hook.
*
* @param string $tag
* @param mixed $value
* @return mixed
*/
function apply_filters($tag, $value) {
global $lazy_filter;
if (!isset($lazy_filter[$tag])) {
return $value;
}
ksort($lazy_filter[$tag]);
reset($lazy_filter[$tag]);
$args = func_get_args();
do {
foreach ((array)current($lazy_filter[$tag]) as $self)
if (!is_null($self['function'])) {
$args[1] = $value;
$value = call_user_func_array($self['function'], array_slice($args, 1, (int)$self['accepted_args']));
}
} while (next($lazy_filter[$tag]) !== false);
return $value;
}
/**
* printf as e
*
* @return bool|mixed
*/
function e() {
$args = func_get_args();
if (count($args) == 1) {
echo $args[0];
} else {
return call_user_func_array('printf', $args);
}
return true;
}
/**
* 转换特殊字符为HTML实体
*
* @param string $str
* @return string
*/
function esc_html($str) {
if (empty($str)) {
return $str;
} elseif (is_array($str)) {
$str = array_map('esc_html', $str);
} elseif (is_object($str)) {
$vars = get_object_vars($str);
foreach ($vars as $key => $data) {
$str->{$key} = esc_html($data);
}
} else {
$str = htmlspecialchars($str);
}
return $str;
}
/**
* Escapes strings to be included in javascript
*
* @param string $str
* @return mixed
*/
function esc_js($str) {
return str_replace(
array("\r", "\n"),
array('', ''),
addcslashes(esc_html($str), "'")
);
}
/**
* ajax request
*
* @return bool
*/
function is_xhr_request() {
return ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? $_SERVER['HTTP_X_REQUESTED_WITH'] : null)
|| (isset($_POST['X-Requested-With']) ? $_POST['X-Requested-With'] : null)) == 'XMLHttpRequest';
}
/**
* ipad request
*
* @return bool
*/
function is_ipad_request() {
return strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false;
}
/**
* mobile request
*
* @return bool
*/
function is_mobile_request() {
return strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'iPod') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'webOS') !== false;
}
/**
* accept json
*
* @return bool
*/
function is_accept_json() {
return strpos(strtolower((isset($_POST['X-Http-Accept']) ? $_POST['X-Http-Accept'] . ',' : '') . $_SERVER['HTTP_ACCEPT']), 'application/json') !== false;
}
/**
* 检查数组类型
*
* @param array $array
* @return bool
*/
function is_assoc($array) {
return (is_array($array) && (0 !== count(array_diff_key($array, array_keys(array_keys($array)))) || count($array) == 0));
}
/**
* 判断是否为json格式
*
* @param $text
* @return bool
*/
function is_jsoned($text) {
return preg_match('/^("(\\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/', $text);
}
/**
* 检查值是否已经序列化
*
* @param mixed $data Value to check to see if was serialized.
* @return bool
*/
function is_serialized($data) {
// if it isn't a string, it isn't serialized
if (!is_string($data))
return false;
$data = trim($data);
if ('N;' == $data)
return true;
if (!preg_match('/^([adObis]):/', $data, $badions))
return false;
switch ($badions[1]) {
case 'a' :
case 'O' :
case 's' :
if (preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data))
return true;
break;
case 'b' :
case 'i' :
case 'd' :
if (preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data))
return true;
break;
}
return false;
}
/**
* 根据概率判定结果
*
* @param float $probability
* @return bool
*/
function is_happened($probability) {
return (mt_rand(1, 100000) / 100000) <= $probability;
}
/**
* 判断是否汉字
*
* @param string $str
* @return int
*/
function is_hanzi($str) {
return preg_match('%^(?:
[\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*$%xs', $str);
}
/**
* 判断是否搜索蜘蛛
*
* @static
* @return bool
*/
function is_spider() {
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (stripos($user_agent, 'Googlebot') !== false
|| stripos($user_agent, 'Sosospider') !== false
|| stripos($user_agent, 'Baiduspider') !== false
|| stripos($user_agent, 'Baidu-Transcoder') !== false
|| stripos($user_agent, 'Yahoo! Slurp') !== false
|| stripos($user_agent, 'iaskspider') !== false
|| stripos($user_agent, 'Sogou') !== false
|| stripos($user_agent, 'YodaoBot') !== false
|| stripos($user_agent, 'msnbot') !== false
|| stripos($user_agent, 'Sosoimagespider') !== false
) {
return true;
}
return false;
}
/**
* 全角转半角
*
* @param string $str
* @return string
*/
function semiangle($str) {
$arr = array(
'0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
'5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
'y' => 'y', 'z' => 'z',
'ɑ' => 'a', 'ā' => 'a', 'á' => 'a', 'ǎ' => 'a', 'à' => 'a',
'ō' => 'o', 'ó' => 'o', 'ǒ' => 'o', 'ò' => 'o',
'ē' => 'e', 'é' => 'e', 'ê' => 'e', 'ě' => 'e', 'è' => 'e',
'ī' => 'i', 'í' => 'i', 'ǐ' => 'i', 'ì' => 'i',
'ū' => 'u', 'ú' => 'u', 'ǔ' => 'u', 'ù' => 'u',
'ü' => 'v', 'ǖ' => 'v', 'ǘ' => 'v', 'ǚ' => 'v', 'ǜ' => 'v',
'ǹ' => 'n', 'ň' => 'n', 'ḿ' => 'm', 'ɡ' => 'g',
'(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[', '】' => ']',
'〖' => '[', '〗' => ']', '“' => '"', '”' => '"', '‘' => "'", '’' => "'",
'{' => '{', '}' => '}', '《' => '<', '》' => '>',
'%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',
':' => ':', '。' => '.', '、' => ',', ',' => ',',
';' => ';', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
'|' => '|', '〃' => '"', ' ' => ' ',
);
return strtr($str, $arr);
}
/**
* 全概率计算
*
* @param array $input array('a'=>0.5,'b'=>0.2,'c'=>0.4)
* @param int $pow 小数点位数
* @return array key
*/
function random($input, $pow = 2) {
$much = pow(10, $pow);
$max = array_sum($input) * $much;
$rand = mt_rand(1, $max);
$base = 0;
foreach ($input as $k => $v) {
$min = $base * $much + 1;
$max = ($base + $v) * $much;
if ($min <= $rand && $rand <= $max) {
return $k;
} else {
$base += $v;
}
}
return false;
}
/**
* 随机字符串
*
* @param int $length
* @param string $charlist
* @return string
*/
function str_rand($length = 6, $charlist = '0123456789abcdefghijklmnopqrstopwxyz') {
$charcount = strlen($charlist);
$str = null;
for ($i = 0; $i < $length; $i++) {
$str .= $charlist[mt_rand(0, $charcount - 1)];
}
return $str;
}
/**
* converts a UTF8-string into HTML entities
*
* @param string $content the UTF8-string to convert
* @param bool $encodeTags booloean. TRUE will convert "<" to "<"
* @return string returns the converted HTML-string
*/
function utf8tohtml($content, $encodeTags = true) {
$result = '';
for ($i = 0; $i < strlen($content); $i++) {
$char = $content[$i];
$ascii = ord($char);
if ($ascii < 128) {
// one-byte character
$result .= ($encodeTags) ? htmlentities($char) : $char;
} else if ($ascii < 192) {
// non-utf8 character or not a start byte
} else if ($ascii < 224) {
// two-byte character
$result .= htmlentities(substr($content, $i, 2), ENT_QUOTES, 'UTF-8');
$i++;
} else if ($ascii < 240) {
// three-byte character
$ascii1 = ord($content[$i + 1]);
$ascii2 = ord($content[$i + 2]);
$unicode = (15 & $ascii) * 4096 +
(63 & $ascii1) * 64 +
(63 & $ascii2);
$result .= "&#$unicode;";
$i += 2;
} else if ($ascii < 248) {
// four-byte character
$ascii1 = ord($content[$i + 1]);
$ascii2 = ord($content[$i + 2]);
$ascii3 = ord($content[$i + 3]);
$unicode = (15 & $ascii) * 262144 +
(63 & $ascii1) * 4096 +
(63 & $ascii2) * 64 +
(63 & $ascii3);
$result .= "&#$unicode;";
$i += 3;
}
}
return $result;
}
/**
* 格式化为XML
*
* @param string $content
* @return mixed
*/
function xmlencode($content) {
if (strlen($content) == 0) return $content;
return str_replace(
array('&', "'", '"', '>', '<'),
array('&', ''', '"', '>', '<'),
$content
);
}
/**
* XMLdecode
*
* @param string $content
* @return mixed
*/
function xmldecode($content) {
if (strlen($content) == 0) return $content;
return str_replace(
array('&', ''', '"', '>', '<'),
array('&', "'", '"', '>', '<'),
$content
);
}
/**
* 格式化大小
*
* @param int $bytes
* @return string
*/
function format_size($bytes) {
if ($bytes == 0) return '-';
$bytes = floatval($bytes);
$units = array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB');
$i = 0;
while ($bytes >= 1024) {
$bytes /= 1024;
$i++;
}
$precision = $i == 0 ? 0 : 2;
return number_format(round($bytes, $precision), $precision) . $units[$i];
}
/**
* array_splice 保留key
*
* @param array &$input
* @param int $start
* @param int $length
* @param mixed $replacement
* @return array|bool
*/
function array_ksplice(&$input, $start, $length = 0, $replacement = null) {
if (!is_array($replacement)) {
return array_splice($input, $start, $length, $replacement);
}
$keys = array_keys($input);
$values = array_values($input);
$replacement = (array)$replacement;
$rkeys = array_keys($replacement);
$rvalues = array_values($replacement);
array_splice($keys, $start, $length, $rkeys);
array_splice($values, $start, $length, $rvalues);
$input = array_combine($keys, $values);
return $input;
}
/**
* 递归地合并一个或多个数组
*
*
* Merges any number of arrays / parameters recursively, replacing
* entries with string keys with values from latter arrays.
* If the entry or the next value to be assigned is an array, then it
* automagically treats both arguments as an array.
* Numeric entries are appended, not replaced, but only if they are
* unique.
*
* @example:
* $result = array_merge_recursive_distinct($a1, $a2, ... $aN)
*
* @return array
*/
function array_merge_recursive_distinct() {
$arrays = func_get_args();
$base = array_shift($arrays);
if (!is_array($base)) $base = empty($base) ? array() : array($base);
foreach ($arrays as $append) {
if (!is_array($append)) $append = array($append);
foreach ($append as $key => $value) {
if (!array_key_exists($key, $base) and !is_numeric($key)) {
$base[$key] = $append[$key];
continue;
}
if (is_array($value) or is_array($base[$key])) {
$base[$key] = array_merge_recursive_distinct($base[$key], $append[$key]);
} else if (is_numeric($key)) {
if (!in_array($value, $base)) $base[] = $value;
} else {
$base[$key] = $value;
}
}
}
return $base;
}
/**
* 批量创建目录
*
* @param string $path 文件夹路径
* @param int $mode 权限
* @return bool
*/
function mkdirs($path, $mode = 0700) {
if (!is_dir($path)) {
mkdirs(dirname($path), $mode);
$error_level = error_reporting(0);
$result = mkdir($path, $mode);
error_reporting($error_level);
return $result;
}
return true;
}
/**
* 删除文件夹
*
* @param string $path 要删除的文件夹路径
* @return bool
*/
function rmdirs($path) {
$error_level = error_reporting(0);
if ($dh = opendir($path)) {
while (false !== ($file = readdir($dh))) {
if ($file != '.' && $file != '..') {
$file_path = $path . '/' . $file;
is_dir($file_path) ? rmdirs($file_path) : unlink($file_path);
}
}
closedir($dh);
}
$result = rmdir($path);
error_reporting($error_level);
return $result;
}
/**
* 自动转换字符集 支持数组转换
*
* @param string $from
* @param string $to
* @param mixed $data
* @return mixed
*/
function iconvs($from, $to, $data) {
$from = strtoupper($from) == 'UTF8' ? 'UTF-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'UTF-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($data) || (is_scalar($data) && !is_string($data))) {
//如果编码相同或者非字符串标量则不转换
return $data;
}
if (is_string($data)) {
if (function_exists('iconv')) {
$to = substr($to, -8) == '//IGNORE' ? $to : $to . '//IGNORE';
return iconv($from, $to, $data);
} elseif (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($data, $to, $from);
} else {
return $data;
}
} elseif (is_array($data)) {
foreach ($data as $key => $val) {
$_key = iconvs($from, $to, $key);
$data[$_key] = iconvs($from, $to, $val);
if ($key != $_key) {
unset($data[$key]);
}
}
return $data;
} else {
return $data;
}
}
/**
* 清除空白
*
* @param string $content
* @return string
*/
function clear_space($content) {
if (strlen($content) == 0) return $content;
$r = $content;
$r = str_replace(array(chr(9), chr(10), chr(13)), '', $r);
while (strpos($r, chr(32) . chr(32)) !== false || strpos($r, ' ') !== false) {
$r = str_replace(array(
' ',
chr(32) . chr(32),
),
chr(32),
$r
);
}
return $r;
}
/**
* 生成guid
*
* @param string $mix
* @param string $hyphen
* @return string
*/
function guid($mix = null, $hyphen = '-') {
if (is_null($mix)) {
$randid = uniqid(mt_rand(), true);
} else {
if (is_object($mix) && function_exists('spl_object_hash')) {
$randid = spl_object_hash($mix);
} elseif (is_resource($mix)) {
$randid = get_resource_type($mix) . strval($mix);
} else {
$randid = serialize($mix);
}
}
$randid = strtoupper(md5($randid));
$result = array();
$result[] = substr($randid, 0, 8);
$result[] = substr($randid, 8, 4);
$result[] = substr($randid, 12, 4);
$result[] = substr($randid, 16, 4);
$result[] = substr($randid, 20, 12);
return implode($hyphen, $result);
}
/**
* 取得客户端的IP
*
* @return string
*/
function get_client_ip() {
$ip = null;
if (!empty($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (!empty($_SERVER['HTTP_VIA '])) {
$ip = $_SERVER['HTTP_VIA '];
} else {
$ip = 'Unknown';
}
}
return $ip;
}
/**
* 页面跳转
*
* @param string $url
* @param int $status
* @return array | string
*/
function redirect($url, $status = 302) {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
return array('status' => $status, 'location' => $url);
} else {
if (!headers_sent()) header("Location: {$url}", true, $status);
$html = '<!DOCTYPE html>';
$html .= '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
$html .= '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
$html .= '<title>' . $url . '</title>';
$html .= '<script type="text/javascript" charset="utf-8">';
$html .= 'self.location.replace("' . addcslashes($url, "'") . '");';
$html .= '</script>';
$html .= '</head><body></body></html>';
return $html;
}
}
/**
* 内容截取,支持正则
*
* $start,$end,$clear 支持正则表达式,“/”斜杠开头为正则模式
* $clear 支持数组
*
* @param string $content 内容
* @param string $start 开始代码
* @param string $end 结束代码
* @param string|array $clear 清除内容
* @return string
*/
function mid($content, $start, $end = null, $clear = null) {
if (empty($content) || empty($start)) return null;
if (strncmp($start, '/', 1) === 0) {
if (preg_match($start, $content, $args)) {
$start = $args[0];
}
}
if ($end && strncmp($end, '/', 1) === 0) {
if (preg_match($end, $content, $args)) {
$end = $args[0];
}
}
$start_len = strlen($start);
$result = null;
$start_pos = stripos($content, $start);
if ($start_pos === false) return null;
$length = $end === null ? null : stripos(substr($content, -(strlen($content) - $start_pos - $start_len)), $end);
if ($start_pos !== false) {
if ($length === null) {
$result = trim(substr($content, $start_pos + $start_len));
} else {
$result = trim(substr($content, $start_pos + $start_len, $length));
}
}
if ($result && $clear) {
if (is_array($clear)) {
foreach ($clear as $v) {
if (strncmp($v, '/', 1) === 0) {
$result = preg_replace($v, '', $result);
} else {
if (strpos($result, $v) !== false) {
$result = str_replace($v, '', $result);
}
}
}
} else {
if (strncmp($clear, '/', 1) === 0) {
$result = preg_replace($clear, '', $result);
} else {
if (strpos($result, $clear) !== false) {
$result = str_replace($clear, '', $result);
}
}
}
}
return $result;
}
/**
* 格式化URL地址
*
* 补全url地址,方便采集
*
* @param string $base 页面地址
* @param string $html html代码
* @return string
*/
function format_url($base, $html) {
if (preg_match_all('/<(img|script)[^>]+src=([^\s]+)[^>]*>|<(a|link)[^>]+href=([^\s]+)[^>]*>/iU', $html, $matchs)) {
$pase_url = parse_url($base);
$base_host = sprintf('%s://%s', $pase_url['scheme'], $pase_url['host']);
if (($pos = strpos($pase_url['path'], '#')) !== false) {
$base_path = rtrim(dirname(substr($pase_url['path'], 0, $pos)), '\\/');
} else {
$base_path = rtrim(dirname($pase_url['path']), '\\/');
}
$base_url = $base_host . $base_path;
foreach ($matchs[0] as $match) {
if (preg_match('/^(.+(href|src)=)([^ >]+)(.+?)$/i', $match, $args)) {
$url = trim(trim($args[3], '"'), "'");
// http 开头,跳过
if (preg_match('/^(http|https|ftp)\:\/\//i', $url)) continue;
// 邮件地址和javascript
if (strncasecmp($url, 'mailto:', 7) === 0 || strncasecmp($url, 'javascript:', 11) === 0) continue;
// 绝对路径
if (strncmp($url, '/', 1) === 0) {
$url = $base_host . $url;
} // 相对路径
elseif (strncmp($url, '../', 3) === 0) {
while (strncmp($url, '../', 3) === 0) {
$url = substr($url, -(strlen($url) - 3));
if (strlen($base_path) > 0) {
$base_path = dirname($base_path);
if ($base_path == '/') $base_path = '';
}
if ($url == '../') {
$url = '';
break;
}
}
$url = $base_host . $base_path . '/' . $url;
} // 当前路径
elseif (strncmp($url, './', 2) === 0) {
$url = $base_url . '/' . substr($url, 2);
} // 其他
else {
$url = $base_url . '/' . $url;
}
// 替换标签
$html = str_replace($match, sprintf('%s"%s"%s', $args[1], $url, $args[4]), $html);
}
}
}
return $html;
}
/**
*
* Compat 兼容函数
*
*******************************************************/
if (!function_exists('mb_substr')) {
function mb_substr($str, $start, $length = null, $encoding = 'UTF-8') {
if (!in_array($encoding, array('utf8', 'utf-8', 'UTF8', 'UTF-8'))) {
return is_null($length) ? substr($str, $start) : substr($str, $start, $length);
}
if (function_exists('iconv_substr')) {
return iconv_substr($str, $start, $length, $encoding);
}
// use the regex unicode support to separate the UTF-8 characters into an array
preg_match_all('/./us', $str, $match);
$chars = is_null($length) ? array_slice($match[0], $start) : array_slice($match[0], $start, $length);
return implode('', $chars);
}
}
if (!function_exists('mb_strlen')) {
function mb_strlen($str, $encoding = 'UTF-8') {
if (!in_array($encoding, array('utf8', 'utf-8', 'UTF8', 'UTF-8'))) {
return strlen($str);
}
if (function_exists('iconv_strlen')) {
return iconv_strlen($str, $encoding);
}
// use the regex unicode support to separate the UTF-8 characters into an array
preg_match_all('/./us', $str, $match);
return count($match);
}
}
if (!function_exists('hash_hmac')) {
function hash_hmac($algo, $data, $key, $raw_output = false) {
$packs = array('md5' => 'H32', 'sha1' => 'H40');
if (!isset($packs[$algo]))
return false;
$pack = $packs[$algo];
if (strlen($key) > 64)
$key = pack($pack, $algo($key));
$key = str_pad($key, 64, chr(0));
$ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64));
$opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64));
$hmac = $algo($opad . pack($pack, $algo($ipad . $data)));
if ($raw_output)
return pack($pack, $hmac);
return $hmac;
}
}
if (!function_exists('gzinflate')) {
/**
* Decompression of deflated string while staying compatible with the majority of servers.
*
* Certain Servers will return deflated data with headers which PHP's gziniflate()
* function cannot handle out of the box. The following function lifted from
* http://au2.php.net/manual/en/function.gzinflate.php#77336 will attempt to deflate
* the various return forms used.
*
* @param binary $gz_data
* @return bool|string
*/
function gzinflate($gz_data) {
if (!strncmp($gz_data, "\x1f\x8b\x08", 3)) {
$i = 10;
$flg = ord(substr($gz_data, 3, 1));
if ($flg > 0) {
if ($flg & 4) {
list($xlen) = unpack('v', substr($gz_data, $i, 2));
$i = $i + 2 + $xlen;
}
if ($flg & 8)
$i = strpos($gz_data, "\0", $i) + 1;
if ($flg & 16)
$i = strpos($gz_data, "\0", $i) + 1;
if ($flg & 2)
$i = $i + 2;
}
return gzinflate(substr($gz_data, $i, -8));
} else {
return false;
}
}
}
if (!function_exists('gzdecode')) {
/**
* Opposite of gzencode. Decodes a gzip'ed file.
*
* @param string $data compressed data
* @return bool|null|string True if the creation was successfully
*/
function gzdecode($data) {
$len = strlen($data);
if ($len < 18 || strncmp($data, "\x1f\x8b", 2)) {
return false; // Not GZIP format (See RFC 1952)
}
$method = ord(substr($data, 2, 1)); // Compression method
$flags = ord(substr($data, 3, 1)); // Flags
if ($flags & 31 != $flags) {
// Reserved bits are set -- NOT ALLOWED by RFC 1952
return false;
}
// NOTE: $mtime may be negative (PHP integer limitations)
$mtime = unpack("V", substr($data, 4, 4));
$mtime = $mtime[1];
$xfl = substr($data, 8, 1);
$os = substr($data, 8, 1);
$headerlen = 10;
$extralen = 0;
$extra = "";
if ($flags & 4) {
// 2-byte length prefixed EXTRA data in header
if ($len - $headerlen - 2 < 8) {
return false; // Invalid format
}
$extralen = unpack("v", substr($data, 8, 2));
$extralen = $extralen[1];
if ($len - $headerlen - 2 - $extralen < 8) {
return false; // Invalid format
}
$extra = substr($data, 10, $extralen);
$headerlen += 2 + $extralen;
}
$filenamelen = 0;
$filename = "";
if ($flags & 8) {
// C-style string file NAME data in header
if ($len - $headerlen - 1 < 8) {
return false; // Invalid format
}
$filenamelen = strpos(substr($data, 8 + $extralen), chr(0));
if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
return false; // Invalid format
}
$filename = substr($data, $headerlen, $filenamelen);
$headerlen += $filenamelen + 1;
}
$commentlen = 0;
$comment = "";
if ($flags & 16) {
// C-style string COMMENT data in header
if ($len - $headerlen - 1 < 8) {
return false; // Invalid format
}
$commentlen = strpos(substr($data, 8 + $extralen + $filenamelen), chr(0));
if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
return false; // Invalid header format
}
$comment = substr($data, $headerlen, $commentlen);
$headerlen += $commentlen + 1;
}
$headercrc = "";
if ($flags & 1) {
// 2-bytes (lowest order) of CRC32 on header present
if ($len - $headerlen - 2 < 8) {
return false; // Invalid format
}
$calccrc = crc32(substr($data, 0, $headerlen)) & 0xffff;
$headercrc = unpack("v", substr($data, $headerlen, 2));
$headercrc = $headercrc[1];
if ($headercrc != $calccrc) {
return false; // Bad header CRC
}
$headerlen += 2;
}
// GZIP FOOTER - These be negative due to PHP's limitations
$datacrc = unpack("V", substr($data, -8, 4));
$datacrc = $datacrc[1];
$isize = unpack("V", substr($data, -4));
$isize = $isize[1];
// Perform the decompression:
$bodylen = $len - $headerlen - 8;
if ($bodylen < 1) {
// This should never happen - IMPLEMENTATION BUG!
return null;
}
$body = substr($data, $headerlen, $bodylen);
$data = "";
if ($bodylen > 0) {
switch ($method) {
case 8:
// Currently the only supported compression method:
$data = gzinflate($body);
break;
default:
// Unknown compression method
return false;
}
} else {
// I'm not sure if zero-byte body content is allowed.
// Allow it for now... Do nothing...
}
// Verifiy decompressed size and CRC32:
// NOTE: This may fail with large data sizes depending on how
// PHP's integer limitations affect strlen() since $isize
// may be negative for large sizes.
if ($isize != strlen($data) || crc32($data) != $datacrc) {
// Bad format! Length or CRC doesn't match!
return false;
}
return $data;
}
}
if (!function_exists('image_type_to_extension')) {
/**
* Get file extension for image type
*
* @param int $imagetype
* @param bool $include_dot
* @return bool|string
*/
function image_type_to_extension($imagetype, $include_dot = true) {
if (empty($imagetype)) return false;
$dot = $include_dot ? '.' : '';
switch ($imagetype) {
case IMAGETYPE_GIF :
return $dot . 'gif';
case IMAGETYPE_JPEG :
return $dot . 'jpg';
case IMAGETYPE_PNG :
return $dot . 'png';
case IMAGETYPE_SWF :
return $dot . 'swf';
case IMAGETYPE_PSD :
return $dot . 'psd';
case IMAGETYPE_BMP :
return $dot . 'bmp';
case IMAGETYPE_TIFF_II :
return $dot . 'tiff';
case IMAGETYPE_TIFF_MM :
return $dot . 'tiff';
case IMAGETYPE_JPC :
return $dot . 'jpc';
case IMAGETYPE_JP2 :
return $dot . 'jp2';
case IMAGETYPE_JPX :
return $dot . 'jpf';
case IMAGETYPE_JB2 :
return $dot . 'jb2';
case IMAGETYPE_SWC :
return $dot . 'swc';
case IMAGETYPE_IFF :
return $dot . 'aiff';
case IMAGETYPE_WBMP :
return $dot . 'wbmp';
case IMAGETYPE_XBM :
return $dot . 'xbm';
case IMAGETYPE_ICO :
return $dot . 'ico';
default :
return false;
}
}
}
/**
* Detect MIME Content-type for a file (deprecated)
*
* @param string $filename
* @return string
*/
function file_mime_type($filename) {
if (is_file($filename) && function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
} else if (is_file($filename) && function_exists('mime_content_type')) {
return mime_content_type($filename);
} else {
switch (strtolower(pathinfo($filename, PATHINFO_EXTENSION))) {
case 'txt':
return 'text/plain';
case 'htm':
case 'html':
case 'php':
return 'text/html';
case 'css':
return 'text/css';
case 'js':
return 'application/javascript';
case 'json':
return 'application/json';
case 'xml':
return 'application/xml';
case 'swf':
return 'application/x-shockwave-flash';
case 'flv':
return 'video/x-flv';
// images
case 'png':
return 'image/png';
case 'jpe':
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'gif':
return 'image/gif';
case 'bmp':
return 'image/bmp';
case 'ico':
return 'image/x-icon';
case 'tiff':
case 'tif':
return 'image/tiff';
case 'svg':
case 'svgz':
return 'image/svg+xml';
// archives
case 'zip':
return 'application/zip';
case 'rar':
return 'application/rar';
case 'exe':
case 'cpt':
case 'bat':
case 'dll':
return 'application/x-msdos-program';
case 'msi':
return 'application/x-msi';
case 'cab':
return 'application/x-cab';
case 'qtl':
return 'application/x-quicktimeplayer';
// audio/video
case 'mp3':
case 'mpga':
case 'mpega':
case 'mp2':
case 'm4a':
return 'audio/mpeg';
case 'qt':
case 'mov':
return 'video/quicktime';
case 'mpeg':
case 'mpg':
case 'mpe':
return 'video/mpeg';
case '3gp':
return 'video/3gpp';
case 'mp4':
return 'video/mp4';
// adobe
case 'pdf':
return 'application/pdf';
case 'psd':
return 'image/x-photoshop';
case 'ai':
case 'ps':
case 'eps':
case 'epsi':
case 'epsf':
case 'eps2':
case 'eps3':
return 'application/postscript';
// ms office
case 'doc':
case 'dot':
return 'application/msword';
case 'rtf':
return 'application/rtf';
case 'xls':
case 'xlb':
case 'xlt':
return 'application/vnd.ms-excel';
case 'ppt':
case 'pps':
return 'application/vnd.ms-powerpoint';
case 'xlsx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
case 'xltx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';
case 'pptx':
return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
case 'ppsx':
return 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
case 'potx':
return 'application/vnd.openxmlformats-officedocument.presentationml.template';
case 'docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
case 'dotx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
// open office
case 'odt':
return 'application/vnd.oasis.opendocument.text';
case 'ods':
return 'application/vnd.oasis.opendocument.spreadsheet';
case 'odp':
return 'application/vnd.oasis.opendocument.presentation';
case 'odb':
return 'application/vnd.oasis.opendocument.database';
case 'odg':
return 'application/vnd.oasis.opendocument.graphics';
case 'odi':
return 'application/vnd.oasis.opendocument.image';
default:
return 'application/octet-stream';
}
}
}
<file_sep>/README.md
LazyFunc
========
Lukin收集的PHP常用函数库
其他类库
--------
* 邮件解析 <http://pear.php.net/package/Mail_Mime/download>
* Markdown <https://github.com/michelf/php-markdown>
* 邮件收发 <https://github.com/PHPMailer/PHPMailer>
<file_sep>/DataAccess.php
<?php
/**
* DataAccess.php
*
* @author Lukin <<EMAIL>>
* @version $Id$
* @datetime 2014-05-30 17:21
*/
class DataAccess {
// DataAccess instance
private static $instance;
/**
* Returns DataAccess instance.
*
* @param string $dsn
* @param string $username
* @param string $password
* @param array $options
* @return DataAccess
*/
public static function &instance($dsn, $username = '', $password = '', $options = array()) {
if (!(self::$instance instanceof DataAccess)) {
self::$instance = new DataAccess($dsn, $username, $password, array_merge(array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
), $options));
}
return self::$instance;
}
/**
* @var PDO
*/
private $dbh;
/**
* @var PDOStatement
*/
private $sth;
/**
* @var string
*/
private $delimiter = '`';
/**
* @var string
*/
public $queryString = '';
public function __construct($dsn, $username = '', $password = '', $options = array()) {
// 连接PDO
$this->dbh = new PDO($dsn, $username, $password, $options);
}
public function __destruct() {
// 释放连接
$this->dbh = null;
}
/**
* 执行SQL,不返回执行结果
*
* @param string $query
* @return bool
*/
public function execute($query) {
$params = func_get_args();
// 兼容标签情况
if (count($params) == 2 && is_array($params[1])) {
$params = $params[1];
} else {
array_shift($params);
}
// 拼装SQL,为了Debugger
$this->queryString = $this->buildQuery($query, $params);
// 预编译SQL
$this->sth = $this->dbh->prepare($query);
// 执行SQL
return $this->sth->execute($params);
}
/**
* 执行SQL,并返回执行结果
*
* @param string $query
* @return array
*/
public function query($query) {
if (call_user_func_array(array(&$this, 'execute'), func_get_args())) {
return $this->fetchAll();
} else {
return array();
}
}
/**
* 获得一条记录
*
* @return bool|array
*/
public function fetch() {
if ($this->sth instanceof PDOStatement) {
return call_user_func_array(array(&$this->sth, 'fetch'), func_get_args());
} else {
return false;
}
}
/**
* 获取执行的所有结果
*
* @return array
*/
public function fetchAll() {
if ($this->sth instanceof PDOStatement) {
return call_user_func_array(array(&$this->sth, 'fetchAll'), func_get_args());
} else {
return array();
}
}
/**
* 从结果集中的下一行返回单独的一列
*
* @param int $column_number
* @return bool|string
*/
public function fetchColumn($column_number = 0) {
if ($this->sth instanceof PDOStatement) {
return call_user_func_array(array(&$this->sth, 'fetchColumn'), func_get_args());
} else {
return false;
}
}
/**
* 返回结果集中的列数
*
* @return int
*/
public function columnCount() {
if ($this->sth instanceof PDOStatement) {
return $this->sth->columnCount();
} else {
return 0;
}
}
/**
* 返回影响行数
*
* @return int
*/
public function rowCount() {
if ($this->sth instanceof PDOStatement) {
return $this->sth->rowCount();
} else {
return 0;
}
}
/**
* 插入数据
*
* @param string $table
* @param array $data
* @return bool|int
*/
public function insert($table, $data) {
$cols = array();
$vals = array();
foreach ($data as $col => $val) {
$cols[] = $this->identifier($col);
$vals[] = $val;
}
$sql = "insert into "
. $this->identifier($table)
. ' (' . implode(', ', $cols) . ') '
. "values ('" . implode("', '", array_fill(0, count($vals), '?')) . "')";
if ($this->execute($sql, $vals)) {
return $this->lastInsertId();
} else {
return false;
}
}
/**
* 更新数据表
*
* @param string $table
* @param array $data
* @param string $conditions
* @return int
*/
public function update($table, $data, $conditions) {
$params = func_get_args();
$argLen = count($params);
$isLabel = false;
if ($argLen > 3 && is_array($params[3])) {
$keys = implode(', ', array_keys($params[3]));
// :id, :sn
if (preg_match('/^\:[\w]+/', $keys)) {
$isLabel = true;
}
$params = $params[3];
} elseif ($argLen > 3) {
$params = array_slice($params, 3);
} else {
$params = array();
}
// extract and quote col names from the array keys
$sets = array();
$vals = array();
foreach ($data as $col => $val) {
if (substr($col, -1) == '+') {
$col = rtrim($col, '+');
$icol = $this->identifier($col);
$sets[] = $icol . ' = ' . $icol . ' + ' . ($isLabel ? ':' . $col : '?');
} elseif (substr($col, -1) == '-') {
$col = rtrim($col, '-');
$icol = $this->identifier($col);
$sets[] = $icol . ' = ' . $icol . ' - ' . ($isLabel ? ':' . $col : '?');
} else {
$sets[] = $this->identifier($col) . ' = ' . ($isLabel ? ':' . $col : '?');
}
if ($isLabel) {
$vals[':' . $col] = $val;
} else {
$vals[] = $val;
}
}
// build the statement
$sql = "update "
. $this->identifier($table)
. ' set ' . implode(', ', $sets)
. ' where ' . $conditions;
$params = array_merge($vals, $params);
if ($this->execute($sql, $params)) {
return $this->rowCount();
} else {
return 0;
}
}
/**
* 返回最后插入行的ID或序列值
*
* @return int
*/
public function lastInsertId() {
if ($this->dbh instanceof PDO) {
return $this->dbh->lastInsertId();
} else {
return 0;
}
}
/**
* Quotes a string for use in a query.
*
* @param string $value
* @return string
*/
public function quote($value) {
if ($this->dbh instanceof PDO) {
return $this->dbh->quote($value);
} else {
return addslashes($value);
}
}
/**
* 给字段加标识
*
* @param $filed
* @return null|string
*/
private function identifier($filed) {
$result = null;
// 检测是否是多个字段
if (strpos($filed, ',') !== false) {
// 多个字段,递归执行
$fileds = explode(',', $filed);
foreach ($fileds as $v) {
if (empty($result)) {
$result = $this->identifier($v);
} else {
$result .= ',' . $this->identifier($v);
}
}
return $result;
} else {
// 解析各个字段
if (strpos($filed, '.') !== false) {
$fileds = explode('.', $filed);
$_table = trim($fileds[0]);
$_filed = trim($fileds[1]);
$_as = chr(32) . 'as' . chr(32);
if (stripos($_filed, $_as) !== false) {
$_filed = sprintf(($this->delimiter . '%s' . $this->delimiter . '%s' . $this->delimiter . '%s' . $this->delimiter), trim(substr($_filed, 0, stripos($_filed, $_as))), $_as, trim(substr($_filed, stripos($_filed, $_as) + 4)));
}
return sprintf($this->delimiter . '%s' . $this->delimiter . '.%s', $_table, $_filed);
} else {
return sprintf($this->delimiter . '%s' . $this->delimiter, $filed);
}
}
}
/**
* 拼装SQL
*
* @param string $query
* @param array $params
* @return string
*/
private function buildQuery($query, $params) {
$keys = array();
$values = array();
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:' . ltrim($key, ':') . '/';
} else {
$keys[] = '/[?]/';
}
if (is_numeric($value)) {
$values[] = $value;
} else {
$values[] = $this->quote($value);
}
}
return preg_replace($keys, $values, $query, 1, $count);
}
}<file_sep>/Httplib.php
<?php
/**
* @author Lukin <<EMAIL>>
* @version $Id$
* @datetime 2011-09-25 17:33
*/
// 严重错误,必须记录
define('HTTPLIB_LOGGER_WARN', 1); // 警告信息
define('HTTPLIB_LOGGER_ERROR', 2); // 发生错误,但不影响系统运行
define('HTTPLIB_LOGGER_FATAL', 3); // 发生严重错误,系统运行中断
class Httplib {
// user-agent
const HTTPLIB_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0';
// begin time
private $begin_time, $type = 'curl';
// debug
public $debug = false;
/**
* debug
*
* @param $message
*/
private function debug($message) {
if ($this->debug) {
print_r($message);
}
}
/**
* 翻译
*
* @param string $text
* @return mixed
*/
private static function __($text) {
if (function_exists('__')) {
return __($text);
} else {
return $text;
}
}
/**
* 编码转换
*
* @param string $from
* @param string $to
* @param string $data
* @return string
*/
private static function iconvs($from, $to, $data) {
if (function_exists('iconvs')) {
return iconvs($from, $to, $data);
}
$from = strtoupper($from) == 'UTF8' ? 'UTF-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'UTF-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($data) || (is_scalar($data) && !is_string($data))) {
//如果编码相同或者非字符串标量则不转换
return $data;
}
if (function_exists('iconv')) {
$to = substr($to, -8) == '//IGNORE' ? $to : $to . '//IGNORE';
return iconv($from, $to, $data);
} elseif (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($data, $to, $from);
} else {
return $data;
}
}
/**
* 抛出异常
*
* @param $message
* @param $code
* @throws Exception
*/
private static function error($message, $code) {
throw new Exception($message, $code);
}
/**
* get
*
* @param string $url
* @param array $args
* @return array|bool|mixed|void
*/
public function get($url, $args = array()) {
$defaults = array(
'method' => 'GET',
);
$args = array_merge($args, $defaults);
return $this->request($url, $args);
}
/**
* post
*
* @param string $url
* @param array $args
* @param array $body
* @return array|bool|mixed|void
*/
public function post($url, $body, $args = array()) {
$defaults = array(
'method' => 'POST',
'body' => $body,
);
$args = array_merge($args, $defaults);
return $this->request($url, $args);
}
/**
* head
*
* @param string $url
* @param array $args
* @return array|bool|mixed|void
*/
public function head($url, $args = array()) {
$defaults = array('method' => 'HEAD');
$args = array_merge($args, $defaults);
return $this->request($url, $args);
}
/**
* 强制使用curl
*
* @return void
*/
public function use_curl() {
$this->type = 'curl';
}
/**
* 强制使用socket
*
* @return void
*/
public function use_socket() {
$this->type = 'socket';
}
/**
* request
*
* @param string $url
* @param array $options
* @return array|void
*/
public function request($url, $options = array()) {
$this->begin_time = microtime(true);
$defaults = array(
'method' => 'GET',
'timeout' => 30,
'redirection' => 3,
'user-agent' => self::HTTPLIB_USER_AGENT,
'blocking' => true,
'headers' => array(),
'body' => null,
'httpversion' => '1.1',
);
$r = array_merge($defaults, $options);
if (is_null($r['headers'])) $r['headers'] = array();
// headers 不是数组时需要处理
if (!is_array($r['headers'])) {
$headers = $this->parse_header($r['headers']);
$r['headers'] = $headers['headers'];
}
// 处理user-agent
if (isset($r['headers']['User-Agent'])) {
$r['user-agent'] = $r['headers']['User-Agent'];
unset($options['headers']['User-Agent']);
} else if (isset($r['headers']['user-agent'])) {
$r['user-agent'] = $r['headers']['user-agent'];
unset($r['headers']['user-agent']);
}
if (!isset($r['headers']['Accept']) && !isset($r['headers']['accept']))
$r['headers']['Accept'] = '*/*';
if (!isset($r['headers']['Accept-Language']) && !isset($r['headers']['accept-language']) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
$r['headers']['Accept-Language'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if (!isset($r['headers']['Accept-Charset']) && !isset($r['headers']['accept-charset']))
$r['headers']['Accept-Charset'] = empty($_SERVER['HTTP_ACCEPT_CHARSET']) ? 'utf-8' : $_SERVER['HTTP_ACCEPT_CHARSET'];
// Construct Cookie: header if any cookies are set
$this->build_cookie_header($r);
// 判断是否支持gzip
if (function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate'))
$r['headers']['Accept-Encoding'] = $this->accept_encoding();
// 判断数据处理类型
if (empty($r['body'])) {
if (($r['method'] == 'POST') && !isset($r['headers']['Content-Length'])) {
$r['headers']['Content-Length'] = 0;
}
} else {
if (is_array($r['body'])) {
$r['body'] = http_build_query($r['body'], null, '&');
$r['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
$r['headers']['Content-Length'] = strlen($r['body']);
}
if (!isset($r['headers']['Content-Length']) && !isset($r['headers']['content-length'])) {
$r['headers']['Content-Length'] = strlen($r['body']);
}
}
$response = array();
// force curl
if ($this->type == 'curl' && function_exists('curl_init') && function_exists('curl_exec')) {
$response = $this->cURL($url, $r);
} // force fsockopen
elseif ($this->type == 'socket' && function_exists('fsockopen')) {
$response = $this->fsockopen($url, $r);
} // cUrl
elseif (function_exists('curl_init') && function_exists('curl_exec')) {
$response = $this->cURL($url, $r);
} // fsockopen
elseif (function_exists('fsockopen')) {
$response = $this->fsockopen($url, $r);
}
return $response;
}
// 代理host port
private $proxy_host, $proxy_port;
/**
* 设置代理信息
*
* @param string $host
* @param string $port
* @return bool
*/
public function set_proxy($host, $port) {
$result = array($this->proxy_host, $this->proxy_port);
$this->proxy_host = $host;
$this->proxy_port = $port;
return $result;
}
/**
* curl 发送之前的处理
*
* @param resource $handle
* @param string $header
* @return int
*/
public function curl_before_send($handle, $header) {
if (preg_match("/Location\:(.+)\r\n/i", $header)) {
curl_setopt($handle, CURLOPT_POST, false);
curl_setopt($handle, CURLOPT_HTTPHEADER, array('Content-Length: 0'));
}
return strlen($header);
}
/**
* curl
*
* @param string $url
* @param array $r
* @return array|void
*/
public function cURL($url, $r) {
// 解析url
$aurl = $this->parse_url($url);
$handle = curl_init();
// 代理
if ($this->proxy_host && $this->proxy_port) {
if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($handle, CURLOPT_PROXY, $this->proxy_host);
curl_setopt($handle, CURLOPT_PROXYPORT, $this->proxy_port);
} else {
curl_setopt($handle, CURLOPT_PROXY, $this->proxy_host . ':' . $this->proxy_port);
}
$this->debug(sprintf("Use Proxy: [%s:%s]", $this->proxy_host, $this->proxy_port));
}
// CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since
// a value of 0 will allow an ulimited timeout.
$timeout = (int)ceil($r['timeout']);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($handle, CURLOPT_TIMEOUT, $timeout);
curl_setopt($handle, CURLINFO_HEADER_OUT, true);
curl_setopt($handle, CURLOPT_HEADERFUNCTION, array(&$this, 'curl_before_send'));
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_USERAGENT, $r['user-agent']);
// 添加用户名密码
if ($aurl['user'] && $aurl['pass']) {
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($handle, CURLOPT_USERPWD, $aurl['user'] . ':' . $aurl['pass']);
curl_setopt($handle, CURLOPT_SSLVERSION, 3);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2);
}
if ($r['redirection'] > 0)
curl_setopt($handle, CURLOPT_MAXREDIRS, $r['redirection']);
if (!isset($r['headers']['referer']) && !isset($r['headers']['Referer'])) {
curl_setopt($handle, CURLOPT_REFERER, $aurl['referer']);
}
switch ($r['method']) {
case 'HEAD':
curl_setopt($handle, CURLOPT_NOBODY, true);
break;
case 'POST':
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $r['body']);
break;
}
if (true === $r['blocking'])
curl_setopt($handle, CURLOPT_HEADER, true);
else
curl_setopt($handle, CURLOPT_HEADER, false);
// The option doesn't work with safe mode or when open_basedir is set.
// Disable HEAD when making HEAD requests.
if ($r['redirection'] > 0 && !ini_get('safe_mode') && !ini_get('open_basedir') && 'HEAD' != $r['method'])
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
if (!empty($r['headers'])) {
// cURL expects full header strings in each element
$headers = array();
foreach ($r['headers'] as $name => $value) {
$headers[] = "{$name}: $value";
}
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
}
if ($r['httpversion'] == '1.0')
curl_setopt($handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
else
curl_setopt($handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
// 提交
$str_response = curl_exec($handle);
$this->debug(sprintf("%01.6f %s Request: %s \n%s%s", microtime(true) - $this->begin_time, $r['method'], $url, curl_getinfo($handle, CURLINFO_HEADER_OUT), $r['body']));
// We don't need to return the body, so don't. Just execute request and return.
if (!$r['blocking']) {
curl_close($handle);
return array('headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array());
}
// 重置计时器
$this->begin_time = microtime(true);
// 获取数据
if (!empty($str_response)) {
$length = curl_getinfo($handle, CURLINFO_HEADER_SIZE);
$headers = trim(substr($str_response, 0, $length));
if (strlen($str_response) > $length)
$the_body = substr($str_response, $length);
else
$the_body = '';
if (false !== strrpos($headers, "\r\n\r\n")) {
$header_parts = explode("\r\n\r\n", $headers);
$headers = $header_parts[count($header_parts) - 1];
}
// 记录日志
$this->debug(sprintf("%01.6f %s Response: %s \n%s", microtime(true) - $this->begin_time, $r['method'], $url, $headers));
$headers = $this->parse_header($headers);
} else {
if ($curl_error = curl_error($handle))
self::error($curl_error, HTTPLIB_LOGGER_ERROR);
if (in_array(curl_getinfo($handle, CURLINFO_HTTP_CODE), array(301, 302)))
self::error(self::__('过多的重定向。'), HTTPLIB_LOGGER_WARN);
$headers = array('headers' => array(), 'cookies' => array());
$the_body = '';
}
$response = array();
$response['code'] = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$response['message'] = self::status_desc($response['code']);
curl_close($handle);
// When running under safe mode, redirection is disabled above. Handle it manually.
if (!empty($headers['headers']['location']) && $r['redirection'] > 0 && (ini_get('safe_mode') || ini_get('open_basedir'))) {
if ($r['redirection']-- > 0) {
return $this->request($this->get_redirection_url($aurl, $headers['headers']['location']), $r);
} else {
self::error(self::__('过多的重定向。'), HTTPLIB_LOGGER_WARN);
}
}
if (isset($headers['headers']['location'])) {
$headers['headers']['location'] = $this->get_redirection_url($aurl, $headers['headers']['location']);
}
if (true === $this->should_decode($headers['headers'])) {
$error_level = error_reporting(0);
$the_body = $this->decompress($the_body);
error_reporting($error_level);
}
// 自动编码转换
$get_charset = null;
if (preg_match("/<meta[^>]+charset\s*=\s*[\"']?([^\"']+)/i", $the_body, $match)) {
$get_charset = trim($match[1]);
$the_body = str_replace($match[0], str_replace($match[1], 'utf-8', $match[0]), $the_body);
} elseif (isset($headers['headers']['content-type']) && preg_match('/charset=(.+)$/i', $headers['headers']['content-type'], $match)) {
$get_charset = trim($match[1]);
}
if ($get_charset && strtolower($get_charset) != 'utf-8') {
$the_body = self::iconvs($get_charset, 'utf-8', $the_body);
}
return array(
'headers' => $headers['headers'],
'body' => $the_body,
'response' => $response,
'cookies' => $headers['cookies'],
);
}
private $sock_hosts = null;
/**
* fsockopen
*
* @param string $url
* @param array $r
* @return array|void
*/
public function fsockopen($url, $r) {
// 解析url
$aurl = $this->parse_url($url);
$host = $aurl['host'];
if ('localhost' == strtolower($host)) $host = '127.0.0.1';
// 安全请求
if ($aurl['scheme'] == 'https' && extension_loaded('openssl')) {
$host = 'ssl://' . $host;
$aurl['port'] = 443;
}
// 连接服务器
$start_delay = time();
$error_level = error_reporting(0);
// DNS缓存
if (!isset($this->sock_hosts[$host]) && !preg_match('/^(?:\d{1,3}\.){3}(?:\d{1,3})$/', $host)) {
$this->sock_hosts[$host] = $host = gethostbyname($host);
} elseif (isset($this->sock_hosts[$host])) {
$host = $this->sock_hosts[$host];
}
// 代理
if ($this->proxy_host && $this->proxy_port) {
$handle = fsockopen($this->proxy_host, $this->proxy_port, $errno, $errstr, $r['timeout']);
$this->debug(sprintf("Use Proxy: [%s:%s]", $this->proxy_host, $this->proxy_port));
} else {
$handle = fsockopen($host, $aurl['port'], $errno, $errstr, $r['timeout']);
}
$end_delay = time();
error_reporting($error_level);
// 连接错误
if (false === $handle) self::error(sprintf('%s: %s', $errno, $errstr), HTTPLIB_LOGGER_ERROR);
// 连接时间超过超时时间,暂时禁用当前方法
$elapse_delay = ($end_delay - $start_delay) > $r['timeout'];
if (true === $elapse_delay) {
// TODO 连接超时
}
// 设置超时时间
stream_set_timeout($handle, $r['timeout']);
if ($this->proxy_host && $this->proxy_port) {
$request_path = $url;
} else {
$request_path = $aurl['path'] . $aurl['query'];
}
// 拼装headers
if (empty($request_path)) $request_path = '/';
$str_headers = sprintf("%s %s HTTP/%s\r\n", strtoupper($r['method']), $request_path, $r['httpversion']);
// 有用户名密码,需要登录
if ($aurl['user'] && $aurl['pass']) {
$str_headers .= sprintf("Authorization: Basic %s\r\n", base64_encode($aurl['user'] . ':' . $aurl['pass']));
}
// user-agent
if (isset($r['user-agent']))
$str_headers .= sprintf("User-Agent: %s\r\n", $r['user-agent']);
if ($this->proxy_host && $this->proxy_port) {
$str_headers .= sprintf("Host: %s:%s\r\n", $aurl['host'], $aurl['port']);
} else {
$str_headers .= sprintf("Host: %s\r\n", $aurl['host']);
}
// referer
if (!isset($r['headers']['referer']) && !isset($r['headers']['Referer']))
$str_headers .= sprintf("Referer: %s\r\n", $aurl['referer']);
// 其他字段
if (is_array($r['headers'])) {
foreach ((array)$r['headers'] as $header => $headerValue)
$str_headers .= sprintf("%s: %s\r\n", $header, $headerValue);
} else {
$str_headers .= $r['headers'];
}
// connection
if (!isset($r['headers']['connection']))
$str_headers .= "Connection: close\r\n";
$str_headers .= "\r\n";
if (!is_null($r['body'])) $str_headers .= $r['body'];
// 提交
fwrite($handle, $str_headers);
// 记录日志
$this->debug(sprintf("%01.6f %s Request: %s \n%s", microtime(true) - $this->begin_time, $r['method'], $url, $str_headers));
// 非阻塞模式
if (!$r['blocking']) {
fclose($handle);
return array('headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array());
}
// 重置计时器
$this->begin_time = microtime(true);
// 读取服务器返回数据
$str_response = '';
while (!feof($handle)) {
$str_response .= fread($handle, 4096);
}
fclose($handle);
// 处理服务器返回的结果
$response = explode("\r\n\r\n", $str_response, 2);
$process = array('headers' => isset($response[0]) ? $response[0] : array(), 'body' => isset($response[1]) ? $response[1] : '');
// 记录日志
$this->debug(sprintf("%01.6f %s Response: %s \n%s", microtime(true) - $this->begin_time, $r['method'], $url, $process['headers']));
// 处理headers
$headers = $this->parse_header($process['headers']);
// 响应代码是400范围内?
if ((int)$headers['response']['code'] >= 400 && (int)$headers['response']['code'] < 500)
self::error($headers['response']['code'] . ': ' . $headers['response']['message'], HTTPLIB_LOGGER_WARN);
// 重定向到新的位置
if ('HEAD' != $r['method'] && $r['redirection'] > 0 && isset($headers['headers']['location'])) {
if ($r['redirection']-- > 0) {
$r['method'] = 'GET';
$r['headers']['Referer'] = $url;
$r['cookies'] = $headers['cookies'];
unset($r['body'], $r['headers']['Content-Type'], $r['headers']['Content-Length']);
return $this->request($this->get_redirection_url($aurl, $headers['headers']['location']), $r);
} else {
self::error(self::__('过多的重定向。'), HTTPLIB_LOGGER_WARN);
}
}
if (isset($headers['headers']['location'])) {
$headers['headers']['location'] = $this->get_redirection_url($aurl, $headers['headers']['location']);
}
// If the body was chunk encoded, then decode it.
if (!empty($process['body']) && isset($headers['headers']['transfer-encoding']) && 'chunked' == $headers['headers']['transfer-encoding'])
$process['body'] = self::decode_chunked($process['body']);
if (true === $this->should_decode($headers['headers'])) {
$error_level = error_reporting(0);
$process['body'] = $this->decompress($process['body']);
error_reporting($error_level);
}
// 自动编码转换
$get_charset = null;
if (preg_match("/<meta[^>]+charset\s*=\s*[\"']?([^\"']+)/i", $process['body'], $match)) {
$get_charset = trim($match[1]);
$process['body'] = str_replace($match[0], str_replace($match[1], 'utf-8', $match[0]), $process['body']);
} elseif (preg_match('/charset=(.+)$/i', $headers['headers']['content-type'], $match)) {
$get_charset = trim($match[1]);
}
if ($get_charset && strtolower($get_charset) != 'utf-8') {
$process['body'] = self::iconvs($get_charset, 'utf-8', $process['body']);
}
return array(
'headers' => $headers['headers'],
'body' => $process['body'],
'response' => $headers['response'],
'cookies' => $headers['cookies'],
);
}
/**
* 创建 cookie header
*
* @param $r
* @return void
*/
private function build_cookie_header(&$r) {
if (!empty($r['cookies'])) {
$cookies_header = '';
foreach ((array)$r['cookies'] as $name => $value) {
if (strlen(strval($name)) > 0 && strlen(strval($value)) > 0) {
$cookies_header .= $name . '=' . urlencode($value) . '; ';
}
}
$cookies_header = substr($cookies_header, 0, -2);
$r['headers']['Cookie'] = $cookies_header;
}
}
/**
* What encoding types to accept and their priority values.
*
* @return string Types of encoding to accept.
*/
private function accept_encoding() {
$type = array();
if (function_exists('gzinflate'))
$type[] = 'deflate;q=1.0';
if (function_exists('gzuncompress'))
$type[] = 'compress;q=0.5';
if (function_exists('gzdecode'))
$type[] = 'gzip;q=0.5';
return implode(', ', $type);
}
/**
* 判断是否需要解码
*
* @param array|string $headers
* @return bool
*/
private function should_decode($headers) {
if (is_array($headers)) {
if (array_key_exists('content-encoding', $headers) && !empty($headers['content-encoding']))
return true;
} else if (is_string($headers)) {
return (stripos($headers, 'content-encoding:') !== false);
}
return false;
}
/**
* 格式化url
*
* @param array $aurl
* @param string $location
* @return string
*/
private function get_redirection_url($aurl, $location) {
$scheme = $aurl['scheme'] . '://';
if (strncmp($scheme, $location, strlen($scheme)) === 0)
return $location;
$url = $scheme . $aurl['host'];
if (strncmp($location, '/', 1) === 0) {
$url .= $location;
} else {
$query = dirname($aurl['query']);
if (substr($aurl['query'], -1) == '/') {
$url .= $aurl['query'] . $location;
} else {
$url .= ($query == '/' ? $query : $query . '/') . $location;
}
}
return $url;
}
/**
* 解析URL
*
* @param $url
* @return mixed
*/
public static function parse_url($url) {
$referer = array();
$aurl = parse_url($url);
$aurl['scheme'] = isset($aurl['scheme']) ? $aurl['scheme'] : 'http';
$aurl['host'] = isset($aurl['host']) ? $aurl['host'] : '';
$aurl['port'] = isset($aurl['port']) ? intval($aurl['port']) : 80;
$aurl['user'] = isset($aurl['user']) ? $aurl['user'] : null;
$aurl['pass'] = isset($aurl['pass']) ? $aurl['pass'] : null;
$aurl['path'] = isset($aurl['path']) ? $aurl['path'] : '/';
$aurl['query'] = isset($aurl['query']) ? '?' . $aurl['query'] : '';
foreach (array('scheme', 'host', 'port', 'path', 'query') as $k) {
if ($k == 'port' && $aurl[$k] == 80) {
continue;
} elseif ($k == 'scheme') {
$referer[$k] = $aurl[$k] . '://';
} elseif ($k == 'port') {
$referer[$k] = ':' . $aurl[$k];
} else {
$referer[$k] = $aurl[$k];
}
}
$aurl['referer'] = implode('', $referer);
return $aurl;
}
/**
* 解析 header
*
* @param string|array $headers
* @return array
*/
private function parse_header($headers) {
// split headers, one per array element
if (is_string($headers)) {
// tolerate line terminator: CRLF = LF (RFC 2616 19.3)
$headers = str_replace("\r\n", "\n", $headers);
// unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2)
$headers = preg_replace('/\n[ \t]/', ' ', $headers);
// create the headers array
$headers = explode("\n", $headers);
}
$response = array('code' => 0, 'message' => '');
// If a redirection has taken place, The headers for each page request may have been passed.
// In this case, determine the final HTTP header and parse from there.
$count = count($headers) - 1;
for ($i = $count; $i >= 0; $i--) {
if (!empty($headers[$i]) && false === strpos($headers[$i], ':')) {
$headers = array_splice($headers, $i);
break;
}
}
$cookies = array();
$new_headers = array();
foreach ($headers as $temp_header) {
if (empty($temp_header))
continue;
if (false === strpos($temp_header, ':')) {
list(, $response['code'], $response['message']) = explode(' ', $temp_header, 3);
continue;
}
list($key, $value) = explode(':', $temp_header, 2);
if (!empty($value)) {
$key = strtolower($key);
if (isset($new_headers[$key])) {
if (!is_array($new_headers[$key]))
$new_headers[$key] = array($new_headers[$key]);
$new_headers[$key][] = trim($value);
} else {
$new_headers[$key] = trim($value);
}
if ('set-cookie' == strtolower($key))
$cookies[] = $this->parse_cookie($value);
}
}
return array('response' => $response, 'headers' => $new_headers, 'cookies' => $cookies);
}
/**
* 解析 cookie
*
* @param string|array $data
* @return array|bool
*/
private function parse_cookie($data) {
$result = array();
if (is_string($data)) {
// Assume it's a header string direct from a previous request
$pairs = explode(';', $data);
// Special handling for first pair; name=value. Also be careful of "=" in value
$name = trim(substr($pairs[0], 0, strpos($pairs[0], '=')));
$value = substr($pairs[0], strpos($pairs[0], '=') + 1);
$result['name'] = $name;
$result['value'] = urldecode($value);
array_shift($pairs); //Removes name=value from items.
// Set everything else as a property
foreach ($pairs as $pair) {
$pair = rtrim($pair);
if (empty($pair)) //Handles the cookie ending in ; which results in a empty final pair
continue;
list($key, $val) = strpos($pair, '=') ? explode('=', $pair) : array($pair, '');
$key = strtolower(trim($key));
if ('expires' == $key)
$val = strtotime($val);
$result[$key] = $val;
}
} else {
if (!isset($data['name']))
return false;
// Set properties based directly on parameters
$result['name'] = $data['name'];
$result['value'] = isset($data['value']) ? $data['value'] : '';
$result['path'] = isset($data['path']) ? $data['path'] : '';
$result['domain'] = isset($data['domain']) ? $data['domain'] : '';
if (isset($data['expires']))
$result['expires'] = is_int($data['expires']) ? $data['expires'] : strtotime($data['expires']);
else
$result['expires'] = null;
}
return $result;
}
/**
* Decompression of deflated string.
*
* Will attempt to decompress using the RFC 1950 standard, and if that fails
* then the RFC 1951 standard deflate will be attempted. Finally, the RFC
* 1952 standard gzip decode will be attempted. If all fail, then the
* original compressed string will be returned.
*
* @param $compressed
* @return bool|string
*/
private function decompress($compressed) {
if (empty($compressed))
return $compressed;
if (false !== ($decompressed = gzinflate($compressed)))
return $decompressed;
if (false !== ($decompressed = gzuncompress($compressed)))
return $decompressed;
if (false !== ($decompressed = gzdecode($compressed)))
return $decompressed;
return $compressed;
}
/**
* decode a string that is encoded w/ "chunked' transfer encoding
* as defined in RFC2068 19.4.6
*
* @param string $buffer
* @return string
*/
public static function decode_chunked($buffer) {
$length = 0;
$newstr = '';
// read chunk-size, chunk-extension (if any) and CRLF
// get the position of the linebreak
$chunkend = strpos($buffer, "\r\n") + 2;
$chunk_size = hexdec(trim(substr($buffer, 0, $chunkend)));
$chunkstart = $chunkend;
$new = '';
// while (chunk-size > 0) {
while ($chunk_size > 0) {
$chunkend = strpos($buffer, "\r\n", $chunkstart + $chunk_size);
// Just in case we got a broken connection
if ($chunkend == false) {
$chunk = substr($buffer, $chunkstart);
// append chunk-data to entity-body
$new .= $chunk;
$length += strlen($chunk);
break;
}
// read chunk-data and CRLF
$chunk = substr($buffer, $chunkstart, $chunkend - $chunkstart);
// append chunk-data to entity-body
$newstr .= $chunk;
// length := length + chunk-size
$length += strlen($chunk);
// read chunk-size and CRLF
$chunkstart = $chunkend + 2;
$chunkend = strpos($buffer, "\r\n", $chunkstart) + 2;
if ($chunkend == false) {
break; //Just in case we got a broken connection
}
$chunk_size = hexdec(trim(substr($buffer, $chunkstart, $chunkend - $chunkstart)));
$chunkstart = $chunkend;
}
return $newstr;
}
/**
* 查询HTTP状态的描述
*
* @param int $code HTTP status code.
* @return string Empty string if not found, or description if found.
*/
public static function status_desc($code) {
$code = abs(intval($code));
$header_desc = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
510 => 'Not Extended'
);
if (isset($header_desc[$code]))
return $header_desc[$code];
else
return '';
}
}
| ddfce9127d1e602e2b08aa7b018395da5bd93d8f | [
"Markdown",
"Python",
"PHP"
] | 7 | Python | mylukin/LazyFunc | 17ec582cb8ef2685137f88b40b0883cff31565ed | 8aa4b3946c2bb4139caae3347bec0bbacff4aee4 |
refs/heads/main | <repo_name>ajuajay1986/techmtask<file_sep>/data.sql
CREATE DATABASE techm_task;
--
-- Table structure for table `school`
--
DROP TABLE IF EXISTS `school`;
CREATE TABLE `school` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL,
`name` varchar(255) DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
--
-- Table structure for table `student`
--
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created_at` datetime DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`school_id` bigint(20) DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
<file_sep>/school-service/src/main/java/com/techm/school/controller/SchoolController.java
package com.techm.school.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.techm.school.model.School;
import com.techm.school.repository.SchoolRepository;
import com.techm.school.service.SchoolService;
/**
* @author achyutananda
*
*/
@RestController
@RequestMapping("/api")
public class SchoolController {
@Autowired
SchoolService schoolService;
@Autowired
SchoolRepository schoolRepository;
/**
* @author Achyutanada
* @return all school data
* @purpose: get all schools list which are available
**/
@GetMapping("/schools")
public ResponseEntity<Object> getAllSchools() {
return new ResponseEntity<Object>(schoolRepository.findAll(), HttpStatus.OK);
}
/**
* @author Achyutanada
* @return school data which is created newly
* @purpose: create schools data and save it into database
**/
@PostMapping("/schools")
public ResponseEntity<Object> createSchool(@Valid @RequestBody School school) {
return new ResponseEntity<>(schoolService.saveData(school), HttpStatus.CREATED);
}
/**
* @author Achyutanada
* @return school data with respective to school id
* @purpose: match and return schools data with respective to school id
**/
@GetMapping(value="/schools/{id}", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getSchoolById(@PathVariable(value = "id") Long sId) {
return new ResponseEntity<>(schoolService.findDataById(sId).toString(), HttpStatus.OK);
}
}
<file_sep>/README.md
# School and Student Service
## API methods
### Create school
```bash
curl -X POST --header 'Content-Type: application/json' --header 'Accept: */*' -d '{ \
"name": "DAV", \
}' 'http://localhost:8181/api/schools'
```
### Get a school details
```bash
curl -X GET --header 'Accept: application/json' 'http://localhost:8181/api/schools/2'
```
### Create student
```bash
curl -X POST --header 'Content-Type: application/json' --header 'Accept: */*' -d '{ \
"name": "Ajay", \
"schoolId": "1", \
}' 'http://localhost:8080/api/students'
```
### Get a student details
```bash
curl -X GET --header 'Accept: application/json' 'http://localhost:8080/api/students/1'
```
<file_sep>/student-service/src/main/java/com/techm/student/service/StudentService.java
package com.techm.student.service;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.techm.student.exception.SchoolNotFoundException;
import com.techm.student.exception.StudentNotFoundException;
import com.techm.student.model.Student;
import com.techm.student.repository.StudentRepository;
@Service
public class StudentService {
JSONObject rr = new JSONObject();
@Autowired
StudentRepository studentRepository;
final String uri = "http://localhost:8181/api/schools";
public List<Student> findAllData() {
return studentRepository.findAll();
}
public JSONObject saveData(@Valid Student student) {
/*start calling school service to get school data with respective to id*/
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri+"/"+student.getSchoolId(), String.class);
JSONObject response = new JSONObject(result);
JSONObject res = new JSONObject();
if(response.has("status") && response.getInt("status")==200) {
res.put("status", 200);
res.put("message", "success");
res.put("data", new JSONObject(studentRepository.save(student)).
put("schoolName", response.getJSONObject("data").getString("name")));
}else {
throw new SchoolNotFoundException(student.getSchoolId().toString());
}
return res;
}
public JSONObject findDataById(Long sId) {
JSONObject resp = new JSONObject();
Optional<Student> student = studentRepository.findById(sId);
if(student.isPresent()) {
/*start calling school service to get school data with respective to id*/
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri+"/"+student.get().getSchoolId(), String.class);
JSONObject response = new JSONObject(result);
resp.put("status", 200);
resp.put("message", "Success");
resp.put("data", new JSONObject(student.get())
.put("schoolName", response.getJSONObject("data").getString("name")));
}else {
throw new StudentNotFoundException(sId.toString());
}
return resp;
}
}
<file_sep>/student-service/src/main/java/com/techm/student/controller/StudentController.java
package com.techm.student.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.techm.student.model.Student;
import com.techm.student.service.StudentService;
@RestController
@RequestMapping("/api")
public class StudentController {
@Autowired
StudentService studentService;
/**
* @author Achyutanada
* @return all students data
* @purpose: get all students list which are available
**/
@GetMapping(value="/students", produces=MediaType.APPLICATION_JSON_VALUE)
public List<Student> getAllStudents() {
return studentService.findAllData();
}
/**
* @author Achyutanada
* @return students data which is created newly with school name
* @purpose: create students data and save it into database
**/
@PostMapping(value="/students", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> createStudent(@Valid @RequestBody Student student) {
return new ResponseEntity<Object>(studentService.saveData(student).toString(), HttpStatus.OK);
}
/**
* @author Achyutanada
* @return students data with respective to school id
* @purpose: match and return students data with respective to school id
**/
@GetMapping(value="/students/{id}", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getStundetById(@PathVariable(value = "id") Long sId) {
return new ResponseEntity<>(studentService.findDataById(sId).toString(), HttpStatus.OK);
}
}
<file_sep>/student-service/src/main/java/com/techm/student/exception/SchoolNotFoundException.java
package com.techm.student.exception;
public class SchoolNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public SchoolNotFoundException(String id) {
super("Could not find school with id: '" + id + "'");
}
}
| 5138e4e8d90d06a857fa1f562c07bdc3bc120808 | [
"Java",
"SQL",
"Markdown"
] | 6 | SQL | ajuajay1986/techmtask | a1f1894fa17e583abb88cc5022dff71d74cf6201 | 3d9aca5ccfff786406006a4c459d9dbe05773edc |
refs/heads/master | <file_sep> Based on sphinx.ext.ifconfig
Provides the ``custver`` directive that allows to write documentation
and the generate different content depending on configuration variables.
Usage::
1. Include section for certain clients
General remarks.
.. custver:: client in ('Company A', 'Company B')
This stuff is only included for client 'Company A', 'Company B'
2. Include section for everyone except certain clients
General remarks.
.. custver:: client not in ('Company B')
This stuff is included for everyone beside 'Company B'
3. Include the whole article for certain clients
.. toctree::
MOD/description.rst
.. custver:: client in ('Company A')
.. toctree::
MOD/dedicated.rst
The argument for ``custver`` is a plain Python expression, evaluated in the
namespace of the project configuration (that is, all variables from
``conf.py`` are available.)
However this extension provides dedicated variable: client. If it is set tu **None**
then Sphinx will generate the documentation with information when specific section will be included.
<file_sep>"""
Based on sphinx.ext.ifconfig
Provides the ``custver`` directive that allows to write documentation
and the generate different content depending on configuration variables.
Usage::
1. Include section for certain clients
General remarks.
.. custver:: client in ('Company A', 'Company B')
This stuff is only included for client 'Company A', 'Company B'
2. Include section for everyone except certain clients
General remarks.
.. custver:: client not in ('Company B')
This stuff is included for everyone beside 'Company B'
3. Include the whole article for certain clients
.. toctree::
MOD/description.rst
.. custver:: client in ('Company A')
.. toctree::
MOD/dedicated.rst
The argument for ``custver`` is a plain Python expression, evaluated in the
namespace of the project configuration (that is, all variables from
``conf.py`` are available.)
However this extension provides dedicated variable: client. If it is set tu **None**
then Sphinx will generate the documentation with information when specific section will be included.
:license: MIT, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import Directive
import sphinx
from sphinx.util.nodes import set_source_info
if False:
# For type annotation
from typing import Any, Dict, List # NOQA
from sphinx.application import Sphinx # NOQA
class custver(nodes.Element):
pass
class CustVer(Directive):
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {} # type: Dict
def run(self):
# type: () -> List[nodes.Node]
node = custver()
node.document = self.state.document
set_source_info(self, node)
node['expr'] = self.arguments[0]
self.state.nested_parse(self.content, self.content_offset,
node, match_titles=1)
return [node]
def process_custver_nodes(app, doctree, docname):
# type: (Sphinx, nodes.Node, unicode) -> None
ns = dict((confval.name, confval.value) for confval in app.config) # type: ignore
ns.update(app.config.__dict__.copy())
ns['builder'] = app.builder.name
for node in doctree.traverse(custver):
if app.config['client'] is None:
newnode = nodes.subscript('', node['expr'])
node.parent.append(newnode)
for n in node.children:
node.parent.append(n)
node.replace_self([])
continue
try:
res = eval(node['expr'], ns)
except Exception as err:
# handle exceptions in a clean fashion
from traceback import format_exception_only
msg = ''.join(format_exception_only(err.__class__, err))
newnode = doctree.reporter.error('Exception occured in '
'custver expression: \n%s' %
msg, base_node=node)
node.replace_self(newnode)
else:
if not res:
node.replace_self([])
else:
node.replace_self(node.children)
def setup(app):
# type: (Sphinx) -> Dict[unicode, Any]
app.add_node(custver)
app.add_directive('custver', CustVer)
app.connect('doctree-resolved', process_custver_nodes)
app.add_config_value('client', None, True)
return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
| 9ae191bfc4864bca8a90a5b5bf7e5160ac523216 | [
"Markdown",
"Python"
] | 2 | Markdown | lukasszz/custver | 34472dc167cdb3398035a2f531258f3ca0ad629a | fa513034416a133196d9980a37555219f20c223e |
refs/heads/master | <file_sep>#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<time.h>
#define R1 "WON"
#define R2 "LOST"
char n[20];res[10];
int NUM, tries, gopt;
void rni(int);
void bnb();
void bnbs();
void delet();
void history();
void welcome();
struct history
{
char name[20];
char game[10];
int number;
int tries;
struct history *l;
struct history *r;
}*first=NULL, *last=NULL, *temp=NULL;
FILE *fptr=NULL;
char c;
void bnb() //asking game
{
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
printf("\n\t\t\t\t\t\t\t\t\t\t BULLS AND BEARS ");
printf("\n\t\t\t\t\t\t\t\t\t\t ----------------- ");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n\n\t\t\t\tPlease enter your name: ");
scanf("%s",n);
int n, a=0, b=0, c, d, tempa, tempb, tempc, tempd, B=0, C, counter=0;
srand(time(NULL));
while(a==b||a==c||a==d||b==c||b==d||c==d) //generate random number without repetition
{
d=rand()%10;
c=rand()%10;
b=rand()%10;
a=rand()%10;
}
//printf("%d%d%d%d",a,b,c,d);
while(B!=4)
{
n=0;
while(tempa==tempb||tempa==tempc||tempa==tempd||tempb==tempc||tempb==tempd||tempc==tempd||n<123||n>9876) //input guess without repetition
{
printf("\n\t\t\t\tGuess : ");
scanf("%d",&n);
tempd=n%10;
tempc=(n/10)%10;
tempb=(n/100)%10;
tempa=(n/1000)%10;
if(tempa==tempb||tempa==tempc||tempa==tempd||tempb==tempc||tempb==tempd||tempc==tempd||n<123||n>9876) //error message
{
printf("\n\t\t\t\tPlease enter a 4 digit number without repetition.");
}
}
B=0; C=0;
//Calculate Bulls and Bears
if(tempa==b||tempa==c||tempa==d)
{
C=C+1;
}
else if(tempa==a)
{
B=B+1;
}
if(tempb==a||tempb==c||tempb==d)
{
C=C+1;
}
else if(tempb==b)
{
B=B+1;
}
if(tempc==b||tempc==a||tempc==d)
{
C=C+1;
}
else if(tempc==c)
{
B=B+1;
}
if(tempd==b||tempd==c||tempd==a)
{
C=C+1;
}
else if(tempd==d)
{
B=B+1;
}
counter=counter+1;
NUM=a*1000+b*100+c*10+d;
tries=counter;
printf("\n\t\t\t\tBulls\tBears\n\t\t\t\t%d \t %d\n",B,C);
if(tries>9)
{
printf("\n\t\t\t\tThe computer won the game and you lost :(\n\t\t\t\tNice try!!!\n\t\t\t\t");
strcpy(res,R2);
break;
}
else
{
if(B==4)
printf("\n\t\t\t\tYou won in %d tries\n\n\t\t\t\t",counter);
printf("\n\t\t\t\t");
strcpy(res,R1);
}
}
system("pause");
}
void bnbs() //answering game
{
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
printf("\n\t\t\t\t\t\t\t\t\t\t BULLS AND BEARS ");
printf("\n\t\t\t\t\t\t\t\t\t\t ----------------- ");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n\n\t\t\t\tPlease enter your name: ");
scanf("%s",n);
int counter, a[9], b[9], c[9], d[9], B[9], C[9], tempB, tempC, i, j;
srand(time(NULL));
for(i=0;B[i-1]!=4;i++)
{
a[i]=0, b[i]=0;
while(a[i]==b[i]||a[i]==c[i]||a[i]==d[i]||b[i]==c[i]||b[i]==d[i]||c[i]==d[i])
{
d[i]=rand()%10;
c[i]=rand()%10;
b[i]=rand()%10;
a[i]=rand()%10;
}
for(j=0;j<i;j++) //check prior responses
{
tempB=0, tempC=0;
if(a[j]==b[i]||a[j]==c[i]||a[j]==d[i])
{
tempC = tempC+1;
}
else if(a[j]==a[i])
{
tempB = tempB+1;
}
if(b[j]==a[i]||b[j]==c[i]||b[j]==d[i])
{
tempC = tempC+1;
}
else if(b[j]==b[i])
{
tempB = tempB+1;
}
if(c[j]==a[i]||c[j]==b[i]||c[j]==d[i])
{
tempC = tempC+1;
}
else if(c[j]==c[i])
{
tempB = tempB+1;
}
if(d[j]==a[i]||d[j]==b[i]||d[j]==c[i])
{
tempC = tempC+1;
}
else if(d[j]==d[i])
{
tempB = tempB+1;
}
if(tempB!=B[j]||tempC!=C[j])
{
a[i]=0, b[i]=0;
while(a[i]==b[i]||a[i]==c[i]||a[i]==d[i]||b[i]==c[i]||b[i]==d[i]||c[i]==d[i])
{
d[i]=rand()%10;
c[i]=rand()%10;
b[i]=rand()%10;
a[i]=rand()%10;
}
j = -1;
}
}
printf("\n\n\t\t\t\tGuess: %d%d%d%d\n", a[i], b[i], c[i], d[i]);
printf("\t\t\t\tBulls: ");
scanf("%d", &B[i]);
if(B[i]!=4)
{
printf("\t\t\t\tBears: ");
scanf("%d", &C[i]);
}
else
{
NUM=a[i]*1000+b[i]*100+c[i]*10+d[i];
counter = i+1;
tries=counter;
if(counter<=7)
{
printf("\n\t\t\t\tThe computer guessed your number in %d tries.\n\t\t\t\t", counter);
printf("\n\t\t\t\t");
strcpy(res,R2);
}
else if(counter>7)
{
printf("\n\t\t\t\tYou won!!!\n\t\t\t\tThe computer took %d tries to guess your number\n\t\t\t\t", counter);
printf("\n\t\t\t\t");
strcpy(res,R1);
}
}
}
system("pause");
}
void store(char n[20],char g[10],int num, int t,char re[10]) //add and create a list
{
temp = (struct history*)malloc(sizeof(struct history));
fptr=fopen("bnb.txt","r");
c=getc(fptr);
fptr=fopen("bnb.txt","a");
strcpy(temp->name, n);
strcpy(temp->game,g);
strcpy(re,res);
temp->number=num;
temp->tries=t;
temp->l=NULL;
temp->r=NULL;
time_t tt = time(NULL);
struct tm tmm = *localtime(&tt);
if(c==EOF)
{
fprintf(fptr,"\t\tNAME\t\tGAME MODE \tNUMBER\t\tTRIES\t\tDATE\t\tTIME\t\tRESULT\n\n");
}
fprintf(fptr,"\t\t%-16s%-16s%-16d%-16d%02d-%02d-%02d %7d:%02d:%02d\t%s\n",n,g,num,t, tmm.tm_mday, tmm.tm_mon + 1, tmm.tm_year + 1900, tmm.tm_hour, tmm.tm_min, tmm.tm_sec,re);
if(first==NULL)
{
first=temp;
last=temp;
}
else
{
last->r=temp;
temp->l=last;
last=temp;
}
fclose(fptr);
}
void delet() //clear history
{
temp=first;
fptr=fopen("bnb.txt","r");
c=getc(fptr);
if(c==EOF)
{
printf("\n\n\t\tThere is no record to delete.\n\t\tWe will redirect you to the main menu.\n\n\t\t");
return;
}
fptr=fopen("bnb.txt","w");
if(first==last)
{
free(temp);
first=NULL;
last=NULL;
}
else
{
while(temp->r!=NULL)
{
free(temp);
temp=temp->r;
}
first=NULL;
last=NULL;
}
printf("\n\n\t\tHistory has been cleared successfully!!\n\t\tWe will redirect you to the main menu.\n\n\t\t\t");
fclose(fptr);
}
void history() //display history
{
int i,j;
printf("\n\n\t\tHISTORY");
printf("\n\t ---------\n\n\n");
fptr=fopen("bnb.txt","r");
c=getc(fptr);
if(first==NULL&&c==EOF)
{
printf("\n\n\t\tNAME\t\tGAME MODE \tNUMBER\t\tTRIES\t\tDATE\t\tTIME\t\tRESULT\n");
printf("\n\n\t\tNo History\n\n");
}
while(c!=EOF)
{
printf("%c",c);
c=getc(fptr);
}
fclose(fptr);
printf("\n\t\t");
system("pause");
}
void rni(int ch) //rules and information
{
system("cls");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
printf("\n\t\t\t\t\t\t\t\t\t\t BULLS AND BEARS ");
printf("\n\t\t\t\t\t\t\t\t\t\t ----------------- ");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n\n");
switch(ch)
{
case 1: printf("\n\t\t\t\tRULES FOR BULLS AND BEARS ASKING GAME: ");
printf("\n");
printf("\n\t\t\t\t1.The game is played with 4 digits.");
printf("\n\t\t\t\t2.The computer thinks of a 4-digit secret number.");
printf("\n\t\t\t\t3.The digits will be different. A 4-digit number can also have 0 as its digit in any position. We consider it digit wise and not the number's significance.");
printf("\n\t\t\t\t4.The user(you) will try to guess the 4-digit number and the computer will tell you the number of matches.");
printf("\n\t\t\t\t5.If the matching digits are in their right positions, they are \"bulls\", if in different positions, they are \"bears\".");
printf("\n\t\t\t\t6.Once you get 4 bulls, you guessed the correct 4-digit number.");
printf("\n\t\t\t\t7.You have 9 chances to guess the 4-digit number. Good luck!! :)\n\n\t\t\t\t");
system("pause");
system("cls");
break;
case 2: printf("\n\t\t\t\tRULES FOR BULLS AND BEARS ANSWERING GAME: ");
printf("\n");
printf("\n\t\t\t\t1.The game is played with 4 digits.");
printf("\n\t\t\t\t2.You must thinks of a 4-digit secret number where all the digits must be different.");
printf("\n\t\t\t\t3.A 4-digit number can also have 0 as its digit in any position. We consider it digit wise and not the number's significance.");
printf("\n\t\t\t\t4.The computer will try to guess the 4-digit number.");
printf("\n\t\t\t\t5.Once the computer guesses a 4-digit number you are prompted to enter the number of BULLS and the number of BEARS.");
printf("\n\t\t\t\t6.If the matching digits are in their right positions, they are \"bulls\", if in different positions, they are \"bears\".");
printf("\n\t\t\t\t7.The computer has 7 chances to guess the 4-digit number, beyond which you win.");
printf("\n\t\t\t\t8.Good luck deceiving the computer ;)\n\n\t\t\t\t");
system("pause");
system("cls");
break;
}
}
void main()
{
if((fptr=fopen("bnb.txt","r"))==NULL)
fptr=fopen("bnb.txt","w");
char ch;
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
printf("\n\t\t\t\t\t\t\t\t\t\t\t WELCOME ");
printf("\n\t\t\t\t\t\t\t\t\t\t\t TO ");
printf("\n\t\t\t\t\t\t\t\t\t\t\t THE GAME ");
printf("\n\t\t\t\t\t\t\t\t\t\t\t\t\t -<NAME>, <NAME>, <NAME>");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
label1: while(1)
{
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
printf("\n\t\t\t\t\t\t\t\t\t\t BULLS AND BEARS ");
printf("\n\t\t\t\t\t\t\t\t\t\t ----------------- ");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
printf("\n\t\t\t\t\t\t\t\t\t > Press S to start the game");
printf("\n\t\t\t\t\t\t\t\t\t > Press H to view the history ");
printf("\n\t\t\t\t\t\t\t\t\t > Press C to clear history");
printf("\n\t\t\t\t\t\t\t\t\t > press Q to quit ");
printf("\n\t\t\t\t____________________________________________________________________________________________________________________\n\n\t\t\t\t");
scanf("%c",&ch);
system("cls");
switch(ch)
{
case 'S':
case 's':
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n");
printf("\n\t\t\t\t\t\t\t\t\t\t BULLS AND BEARS ");
printf("\n\t\t\t\t\t\t\t\t\t\t ----------------- ");
printf("\n\t\t\t\t___________________________________________________________________________________________________________________");
printf("\n\n\t\t\t\tWe have two games for you to play: ASK and ANSWER\n\n\t\t\t\tThe rules for both the games appear once you make this choice.\n\n\t\t\t\tEnter:\n\t\t\t\t1. ASK\n\t\t\t\t2. ANSWER\n\t\t\t\t3.Return to main menu\t\t\t\t\n\n\t\t\t\t");
scanf("%d",&gopt);
if(gopt==1||gopt==2)
{
rni(gopt);
if(gopt==1)
{
bnb();
store(n,"ASK",NUM,tries,res);
}
else if(gopt==2)
{
bnbs();
store(n,"ANSWER",NUM,tries,res);
}
}
else if(gopt==3)
{
goto label1;
}
else
{
printf("\n\t\t\t\tInvalid Entry. We will redirect you to the main menu.");
sleep(4);
goto label1;
}
system("cls");
goto label1;
break;
case 'H':
case 'h': history();
break;
case 'C':
case 'c': delet();
sleep(4);
break;
case 'Q':
case 'q': printf("\n\n\n\t\tBYE BYE!!\n\t\tWE HOPE TO SEE YOU AGAIN :)");
printf("\n\n\t\t");
exit(0);
}
}
}
<file_sep># Bulls-and-Bears
# <NAME>, <NAME>, <NAME>
Bulls and Bears is a Mini Mathematical Game developed in C which is inspired by the traditional pen and paper game called Bulls and Cows.
In, this project, we have implemented data structures like arrays, doubly linked lists and file structures.
In the forthcoming future, we would like to implement an easy to use interface to make the exoperience much better.
| 0bad6b837da978289cb50fa46bd7f9fb95d7272d | [
"Markdown",
"C"
] | 2 | C | AbhayaSimhaSP/Bulls-and-Bears | 3ce29ee6aebda97a721948933efe16bb992ef452 | 79a3b91493d87857d53df92287ab7f7a6d10556e |
refs/heads/main | <file_sep>var elMoviesList = $_('.movies');
var elMoviesTemplate = $_('#movies-card-template').content;
// ===========================================================
var normalizedMovies = movies.map(function (movie) {
return {
title: movie.Title.toString(),
year: movie.movie_year,
categories: movie.Categories.split('|').join(', '),
youtubeId: `https://www.youtube.com/watch?v=${movie.ytid}`
};
});
var createMovies = function (movie) {
var elNewMovie = elMoviesTemplate.cloneNode(true);
elNewMovie.querySelector('.js-movie-title').textContent = movie.title;
elNewMovie.querySelector('.js-movie-year').textContent = `Year: ${movie.year}`;
elNewMovie.querySelector('.js-movie-categories').textContent = `Categories: ${movie.categories}`;
elNewMovie.querySelector('.js-movie-you-tube-id').textContent = `Watch trailer`;
elNewMovie.querySelector('.js-movie-you-tube-id').href = movie.youtubeId;
return elNewMovie;
};
var renderMovies = function (normalizedMovies) {
elMoviesList.innerHTML = '';
var elMoviesFragment = document.createDocumentFragment();
normalizedMovies.forEach(function (movie) {
elMoviesFragment.appendChild(createMovies(movie));
});
elMoviesList.appendChild(elMoviesFragment);
};
renderMovies(normalizedMovies.slice(0, 100)); // cut other movies exept 100 movies
var elForm = $_('.js-form');
var elInput = $_('.js-search-input', elForm);
var searchMovies = function (e) {
e.preventDefault();
var searchFilm = elInput.value.trim();
var searchQuery = new RegExp(searchFilm, 'gi');
var moviesSearch = normalizedMovies.filter(function (movie) {
return movie.title.match(searchQuery);
});
renderMovies(moviesSearch);
};
elForm.addEventListener('submit', searchMovies); | 7eebffa6846c06a5908a46bd9fd098cce0dc6815 | [
"JavaScript"
] | 1 | JavaScript | shohjahon-sohibov/js-movies-search | 2bb6042c3d6438b18de422bca32c52446fa5c72b | 02bc944d446a0431d6da5fe10fa2784b91683349 |
refs/heads/main | <repo_name>HenraL/install_csfml_fedora<file_sep>/test.c
/*
** EPITECH PROJECT, 2020
** main
** File description:
** test
*/
#include <SFML/Graphics.h>
sfRenderWindow *open_window(int width, int height, char *name)
{
sfRenderWindow *window;
sfVideoMode video_mode;
video_mode.width = width;
video_mode.height = height;
video_mode.bitsPerPixel = 32;
window = sfRenderWindow_create(video_mode, name, sfDefaultStyle, NULL);
return (window);
}
int main(void)
{
/* Create Window */
sfRenderWindow *window = open_window(800, 600, "Window");
sfTexture* texture;
sfSprite* sprite;
sfEvent event;
/* Load a sprite to display */
texture = sfTexture_createFromFile("test.jpg", NULL);
if (!texture)
return (84);
sprite = sfSprite_create();
sfSprite_setTexture(sprite, texture, sfTrue);
/* Start the game loop */
while (sfRenderWindow_isOpen(window)) {
/* Process events */
while (sfRenderWindow_pollEvent(window, &event)) {
/* Close window : exit */
if (event.type == sfEvtClosed)
sfRenderWindow_close(window);
}
/* Clear the screen */
sfRenderWindow_clear(window, sfBlack);
/* Draw the sprite */
sfRenderWindow_drawSprite(window, sprite, NULL);
/* Update the window */
sfRenderWindow_display(window);
}
/* Cleanup resources */
sfSprite_destroy(sprite);
sfTexture_destroy(texture);
sfRenderWindow_destroy(window);
return (0);
}<file_sep>/install_csfml_fedora.sh
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" 1>&2
exit 1
fi
dnf install -y cmake make libX11-devel-1.6.12-1.fc33.x86_64 mesa-libGL-devel systemd-devel openal-soft-devel libvorbis-devel flac-devel libXrandr-devel SFML SFML-devel
yum -y install qt-devel cmake
SFML_SOURCE_URL="http://www.sfml-dev.org/files/SFML-2.5.1-sources.zip"
CSFML_SOURCE_URL="http://www.sfml-dev.org/files/CSFML-2.5-sources.zip"
CSFML_ZIP="CSFML.zip"
SFML_ZIP="SFML.zip"
echo "Download SFML Sources"
curl -Lo "$SFML_ZIP" $SFML_SOURCE_URL
echo "Download CSFML Sources"
curl -Lo "$CSFML_ZIP" $CSFML_SOURCE_URL
echo "Unzip SFML"
unzip -qq -o $SFML_ZIP
echo "Unzip CSFML"
unzip -qq -o $CSFML_ZIP
mv SFML-* SFML
mv CSFML-* CSFML
SFML_PATH="$(realpath SFML)"
CSFML_PATH="$(realpath CSFML)"
echo "SFML Compilation"
cd SFML
cmake .
make
cd ..
echo "CSFML Compilation"
cd CSFML
cmake -DSFML_ROOT="$SFML_PATH" -DSFML_INCLUDE_DIR="$SFML_PATH/include" -DCMAKE_MODULE_PATH="$SFML_PATH/cmake/Modules" .
LD_LIBRARY_PATH="$SFML_PATH/lib"
make
make install
cd ..
echo "/usr/local/lib/" > /etc/ld.so.conf.d/csfml.conf
# Update the Dynamic Linker Run Time Bindings
ldconfig
# Clean
rm -rf "$CSFML_ZIP" "$CSFML_PATH" "$SFML_ZIP" "$SFML_PATH"
echo "# GDM configuration storage
#
# See /usr/share/gdm/gdm.schemas for a list of available options.
[daemon]
# Uncomment the line below to force the login screen to use Xorg
WaylandEnable=false
# Enabling automatic login
# AutomaticLoginEnable = true
# AutomaticLogin = user1
# Enabling timed login
# TimedLoginEnable = true
# TimedLogin = user1
# TimedLoginDelay = 10
DefaultSession=gnome-xorg.desktop
[security]
[xdmcp]
[chooser]
[debug]
# Uncomment the line below to turn on debugging
# More verbose logs
# Additionally lets the X server dump core if it crashes
#Enable=true" > /etc/gdm/custom.conf
| 459244a43f73d81d2ae1b6d262b2d52eb691b29e | [
"C",
"Shell"
] | 2 | C | HenraL/install_csfml_fedora | 35e3b353008191581ad47ee5457c472d40ce55c4 | ad4489ffe220a0eb4e06ed2ad3abd3ea06d7a7c3 |
refs/heads/master | <file_sep># yearCal
一个 Kendo UI 插件,用于整年度的节假日工作日设置,支持万年历
demo: http://gochant.github.io/yearCal<file_sep>
var lunarCalendar = (function () {
/**
* @1900-2100区间内的公历、农历互转
* @charset UTF-8
* @Author Jea杨(<EMAIL>)
* @Time 2014-7-21
* @Time 2016-8-13 Fixed 2033hex、Attribution Annals
* @Version 1.0.1
* @公历转农历:calendar.solar2lunar(1987,11,01); //[you can ignore params of prefix 0]
* @农历转公历:calendar.lunar2solar(1987,09,10); //[you can ignore params of prefix 0]
*/
var calendar = {
/**
* 农历1900-2100的润大小信息表
* @Array Of Property
* @return Hex
*/
lunarInfo: [0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,//1900-1909
0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,//1910-1919
0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,//1920-1929
0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,//1930-1939
0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,//1940-1949
0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0,//1950-1959
0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,//1960-1969
0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6,//1970-1979
0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,//1980-1989
0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,//1990-1999
0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,//2000-2009
0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,//2010-2019
0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,//2020-2029
0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,//2030-2039
0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0,//2040-2049
/**Add By <EMAIL>**/
0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0,//2050-2059
0x0a2e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4,//2060-2069
0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0,//2070-2079
0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160,//2080-2089
0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252,//2090-2099
0x0d520],//2100
/**
* 公历每个月份的天数普通表
* @Array Of Property
* @return Number
*/
solarMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
/**
* 天干地支之天干速查表
* @Array Of Property trans["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
* @return Cn string
*/
Gan: ["\u7532", "\u4e59", "\u4e19", "\u4e01", "\u620a", "\u5df1", "\u5e9a", "\u8f9b", "\u58ec", "\u7678"],
/**
* 天干地支之地支速查表
* @Array Of Property
* @trans["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"]
* @return Cn string
*/
Zhi: ["\u5b50", "\u4e11", "\u5bc5", "\u536f", "\u8fb0", "\u5df3", "\u5348", "\u672a", "\u7533", "\u9149", "\u620c", "\u4ea5"],
/**
* 天干地支之地支速查表<=>生肖
* @Array Of Property
* @trans["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
* @return Cn string
*/
Animals: ["\u9f20", "\u725b", "\u864e", "\u5154", "\u9f99", "\u86c7", "\u9a6c", "\u7f8a", "\u7334", "\u9e21", "\u72d7", "\u732a"],
/**
* 24节气速查表
* @Array Of Property
* @trans["小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"]
* @return Cn string
*/
solarTerm: ["\u5c0f\u5bd2", "\u5927\u5bd2", "\u7acb\u6625", "\u96e8\u6c34", "\u60ca\u86f0", "\u6625\u5206", "\u6e05\u660e", "\u8c37\u96e8", "\u7acb\u590f", "\u5c0f\u6ee1", "\u8292\u79cd", "\u590f\u81f3", "\u5c0f\u6691", "\u5927\u6691", "\u7acb\u79cb", "\u5904\u6691", "\u767d\u9732", "\u79cb\u5206", "\u5bd2\u9732", "\u971c\u964d", "\u7acb\u51ac", "\u5c0f\u96ea", "\u5927\u96ea", "\u51ac\u81f3"],
/**
* 1900-2100各年的24节气日期速查表
* @Array Of Property
* @return 0x string For splice
*/
sTermInfo: ['<KEY>', '97b6b97bd19801ec9210c965cc920e', '<KEY>',
'<KEY>', '<KEY>', '97b6b97bd19801ec9210c965cc920e',
'<KEY>', '<KEY>', '<KEY>',
'97b6b97bd19801ec9210c965cc920e', '<KEY>', '<KEY>',
'<KEY>', '9778397bd19801ec9210c965cc920e', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '97b6b97bd19801ec9210c965cc920e',
'<KEY>', '<KEY>', '<KEY>',
'97b6b97bd19801ec9210c965cc920e', '<KEY>', '<KEY>',
'<KEY>', '97b6b97bd19801ec9210c965cc920e', '<KEY>',
'<KEY>', '<KEY>', '97b6b97bd19801ec9210c965cc920e',
'<KEY>', '<KEY>', '<KEY>',
'97b6b97bd19801ec9210c965cc920e', '<KEY>', '<KEY>',
'<KEY>', '9778397bd19801ec9210c9274c920e', '<KEY>',
'<KEY>0722', '<KEY>', '9778397bd097c36c9210c9274c920e',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '97b6b97bd19801ec9210c965cc920e', '<KEY>',
'<KEY>', '<KEY>', '97b6b97bd19801ec9210c965cc920e',
'<KEY>', '<KEY>', '<KEY>',
'97b6b97bd19801ec9210c965cc920e', '<KEY>', '<KEY>',
'<KEY>', '97b6b97bd19801ec9210c965cc920e', '<KEY>',
'<KEY>', '<KEY>', '97b6b97bd19801ec9210c965cc920e',
'<KEY>', '<KEY>', '<KEY>',
'97b6b97bd19801ec9210c9274c920e', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '9778397bd097c36c9210c9274c920e',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'977837f0e37f14998082b0787b0721', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'7f07e7f0e47f149b0723b0787b0721', '<KEY>', '<KEY>',
'<KEY>', '7f07e7f0e37f149b0723b0787b0721', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '7f0e37f0e37f14898082b072297c35', '<KEY>',
'<KEY>', '<KEY>', '7f0e37f0e37f14898082b072297c35',
'<KEY>', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '7f07e7f0e47f149b0723b0787b0721',
'<KEY>', '<KEY>', '<KEY>',
'7f07e7f0e47f149b0723b0787b0721', '<KEY>', '<KEY>',
'<KEY>', '7f07e7f0e37f14998083b0787b0721', '<KEY>',
'<KEY>', '<KEY>', '7f07e7f0e37f14998082b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '<KEY>', '<KEY>',
'<KEY>', '<KEY>', '7f0e36665b66a449801e9808297c35',
'<KEY>', '<KEY>', '<KEY>',
'7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b072297c35', '<KEY>',
'<KEY>', '7f0e26665b66a449801e9808297c35', '665f67f0e37f1489801eb072297c35',
'<KEY>', '<KEY>', '7f0e27f1487f531b0b0bb0b6fb0722'],
/**
* 数字转中文速查表
* @Array Of Property
* @trans ['日','一','二','三','四','五','六','七','八','九','十']
* @return Cn string
*/
nStr1: ["\u65e5", "\u4e00", "\u4e8c", "\u4e09", "\u56db", "\u4e94", "\u516d", "\u4e03", "\u516b", "\u4e5d", "\u5341"],
/**
* 日期转农历称呼速查表
* @Array Of Property
* @trans ['初','十','廿','卅']
* @return Cn string
*/
nStr2: ["\u521d", "\u5341", "\u5eff", "\u5345"],
/**
* 月份转农历称呼速查表
* @Array Of Property
* @trans ['正','一','二','三','四','五','六','七','八','九','十','冬','腊']
* @return Cn string
*/
nStr3: ["\u6b63", "\u4e8c", "\u4e09", "\u56db", "\u4e94", "\u516d", "\u4e03", "\u516b", "\u4e5d", "\u5341", "\u51ac", "\u814a"],
/**
* 返回农历y年一整年的总天数
* @param lunar Year
* @return Number
* @eg:var count = calendar.lYearDays(1987) ;//count=387
*/
lYearDays: function (y) {
var i, sum = 348;
for (i = 0x8000; i > 0x8; i >>= 1) { sum += (calendar.lunarInfo[y - 1900] & i) ? 1 : 0; }
return (sum + calendar.leapDays(y));
},
/**
* 返回农历y年闰月是哪个月;若y年没有闰月 则返回0
* @param lunar Year
* @return Number (0-12)
* @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6
*/
leapMonth: function (y) { //闰字编码 \u95f0
return (calendar.lunarInfo[y - 1900] & 0xf);
},
/**
* 返回农历y年闰月的天数 若该年没有闰月则返回0
* @param lunar Year
* @return Number (0、29、30)
* @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29
*/
leapDays: function (y) {
if (calendar.leapMonth(y)) {
return ((calendar.lunarInfo[y - 1900] & 0x10000) ? 30 : 29);
}
return (0);
},
/**
* 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapDays方法
* @param lunar Year
* @return Number (-1、29、30)
* @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29
*/
monthDays: function (y, m) {
if (m > 12 || m < 1) { return -1 }//月份参数从1至12,参数错误返回-1
return ((calendar.lunarInfo[y - 1900] & (0x10000 >> m)) ? 30 : 29);
},
/**
* 返回公历(!)y年m月的天数
* @param solar Year
* @return Number (-1、28、29、30、31)
* @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30
*/
solarDays: function (y, m) {
if (m > 12 || m < 1) { return -1 } //若参数错误 返回-1
var ms = m - 1;
if (ms == 1) { //2月份的闰平规律测算后确认返回28或29
return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28);
} else {
return (calendar.solarMonth[ms]);
}
},
/**
* 农历年份转换为干支纪年
* @param lYear 农历年的年份数
* @return Cn string
*/
toGanZhiYear: function (lYear) {
var ganKey = (lYear - 3) % 10;
var zhiKey = (lYear - 3) % 12;
if (ganKey == 0) ganKey = 10;//如果余数为0则为最后一个天干
if (zhiKey == 0) zhiKey = 12;//如果余数为0则为最后一个地支
return calendar.Gan[ganKey - 1] + calendar.Zhi[zhiKey - 1];
},
/**
* 公历月、日判断所属星座
* @param cMonth [description]
* @param cDay [description]
* @return Cn string
*/
toAstro: function (cMonth, cDay) {
var s = "\u9b54\u7faf\u6c34\u74f6\u53cc\u9c7c\u767d\u7f8a\u91d1\u725b\u53cc\u5b50\u5de8\u87f9\u72ee\u5b50\u5904\u5973\u5929\u79e4\u5929\u874e\u5c04\u624b\u9b54\u7faf";
var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22];
return s.substr(cMonth * 2 - (cDay < arr[cMonth - 1] ? 2 : 0), 2) + "\u5ea7";//座
},
/**
* 传入offset偏移量返回干支
* @param offset 相对甲子的偏移量
* @return Cn string
*/
toGanZhi: function (offset) {
return calendar.Gan[offset % 10] + calendar.Zhi[offset % 12];
},
/**
* 传入公历(!)y年获得该年第n个节气的公历日期
* @param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起
* @return day Number
* @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春
*/
getTerm: function (y, n) {
if (y < 1900 || y > 2100) { return -1; }
if (n < 1 || n > 24) { return -1; }
var _table = calendar.sTermInfo[y - 1900];
var _info = [
parseInt('0x' + _table.substr(0, 5)).toString(),
parseInt('0x' + _table.substr(5, 5)).toString(),
parseInt('0x' + _table.substr(10, 5)).toString(),
parseInt('0x' + _table.substr(15, 5)).toString(),
parseInt('0x' + _table.substr(20, 5)).toString(),
parseInt('0x' + _table.substr(25, 5)).toString()
];
var _calday = [
_info[0].substr(0, 1),
_info[0].substr(1, 2),
_info[0].substr(3, 1),
_info[0].substr(4, 2),
_info[1].substr(0, 1),
_info[1].substr(1, 2),
_info[1].substr(3, 1),
_info[1].substr(4, 2),
_info[2].substr(0, 1),
_info[2].substr(1, 2),
_info[2].substr(3, 1),
_info[2].substr(4, 2),
_info[3].substr(0, 1),
_info[3].substr(1, 2),
_info[3].substr(3, 1),
_info[3].substr(4, 2),
_info[4].substr(0, 1),
_info[4].substr(1, 2),
_info[4].substr(3, 1),
_info[4].substr(4, 2),
_info[5].substr(0, 1),
_info[5].substr(1, 2),
_info[5].substr(3, 1),
_info[5].substr(4, 2),
];
return parseInt(_calday[n - 1]);
},
/**
* 传入农历数字月份返回汉语通俗表示法
* @param lunar month
* @return Cn string
* @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月'
*/
toChinaMonth: function (m) { // 月 => \u6708
if (m > 12 || m < 1) { return -1 } //若参数错误 返回-1
var s = calendar.nStr3[m - 1];
s += "\u6708";//加上月字
return s;
},
/**
* 传入农历日期数字返回汉字表示法
* @param lunar day
* @return Cn string
* @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一'
*/
toChinaDay: function (d) { //日 => \u65e5
var s;
switch (d) {
case 10:
s = '\u521d\u5341'; break;
case 20:
s = '\u4e8c\u5341'; break;
break;
case 30:
s = '\u4e09\u5341'; break;
break;
default:
s = calendar.nStr2[Math.floor(d / 10)];
s += calendar.nStr1[d % 10];
}
return (s);
},
/**
* 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春”
* @param y year
* @return Cn string
* @eg:var animal = calendar.getAnimal(1987) ;//animal='兔'
*/
getAnimal: function (y) {
return calendar.Animals[(y - 4) % 12]
},
/**
* 传入公历年月日获得详细的公历、农历object信息 <=>JSON
* @param y solar year
* @param m solar month
* @param d solar day
* @return JSON object
* @eg:console.log(calendar.solar2lunar(1987,11,01));
*/
solar2lunar: function (y, m, d) { //参数区间1900.1.31~2100.12.31
if (y < 1900 || y > 2100) { return -1; }//年份限定、上限
if (y == 1900 && m == 1 && d < 31) { return -1; }//下限
if (!y) { //未传参 获得当天
var objDate = new Date();
} else {
var objDate = new Date(y, parseInt(m) - 1, d)
}
var i, leap = 0, temp = 0;
//修正ymd参数
var y = objDate.getFullYear(), m = objDate.getMonth() + 1, d = objDate.getDate();
var offset = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - Date.UTC(1900, 0, 31)) / 86400000;
for (i = 1900; i < 2101 && offset > 0; i++) { temp = calendar.lYearDays(i); offset -= temp; }
if (offset < 0) { offset += temp; i--; }
//是否今天
var isTodayObj = new Date(), isToday = false;
if (isTodayObj.getFullYear() == y && isTodayObj.getMonth() + 1 == m && isTodayObj.getDate() == d) {
isToday = true;
}
//星期几
var nWeek = objDate.getDay(), cWeek = calendar.nStr1[nWeek];
if (nWeek == 0) { nWeek = 7; }//数字表示周几顺应天朝周一开始的惯例
//农历年
var year = i;
var leap = calendar.leapMonth(i); //闰哪个月
var isLeap = false;
//效验闰月
for (i = 1; i < 13 && offset > 0; i++) {
//闰月
if (leap > 0 && i == (leap + 1) && isLeap == false) {
--i;
isLeap = true; temp = calendar.leapDays(year); //计算农历闰月天数
}
else {
temp = calendar.monthDays(year, i);//计算农历普通月天数
}
//解除闰月
if (isLeap == true && i == (leap + 1)) { isLeap = false; }
offset -= temp;
}
if (offset == 0 && leap > 0 && i == leap + 1)
if (isLeap) {
isLeap = false;
} else {
isLeap = true; --i;
}
if (offset < 0) { offset += temp; --i; }
//农历月
var month = i;
//农历日
var day = offset + 1;
//天干地支处理
var sm = m - 1;
var gzY = calendar.toGanZhiYear(year);
//月柱 1900年1月小寒以前为 丙子月(60进制12)
var firstNode = calendar.getTerm(year, (m * 2 - 1));//返回当月「节」为几日开始
var secondNode = calendar.getTerm(year, (m * 2));//返回当月「节」为几日开始
//依据12节气修正干支月
var gzM = calendar.toGanZhi((y - 1900) * 12 + m + 11);
if (d >= firstNode) {
gzM = calendar.toGanZhi((y - 1900) * 12 + m + 12);
}
//传入的日期的节气与否
var isTerm = false;
var Term = null;
if (firstNode == d) {
isTerm = true;
Term = calendar.solarTerm[m * 2 - 2];
}
if (secondNode == d) {
isTerm = true;
Term = calendar.solarTerm[m * 2 - 1];
}
//日柱 当月一日与 1900/1/1 相差天数
var dayCyclical = Date.UTC(y, sm, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10;
var gzD = calendar.toGanZhi(dayCyclical + d - 1);
//该日期所属的星座
var astro = calendar.toAstro(m, d);
return { 'lYear': year, 'lMonth': month, 'lDay': day, 'Animal': calendar.getAnimal(year), 'IMonthCn': (isLeap ? "\u95f0" : '') + calendar.toChinaMonth(month), 'IDayCn': calendar.toChinaDay(day), 'cYear': y, 'cMonth': m, 'cDay': d, 'gzYear': gzY, 'gzMonth': gzM, 'gzDay': gzD, 'isToday': isToday, 'isLeap': isLeap, 'nWeek': nWeek, 'ncWeek': "\u661f\u671f" + cWeek, 'isTerm': isTerm, 'Term': Term, 'astro': astro };
},
/**
* 传入公历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON
* @param y lunar year
* @param m lunar month
* @param d lunar day
* @param isLeapMonth lunar month is leap or not.
* @return JSON object
* @eg:console.log(calendar.lunar2solar(1987,9,10));
*/
lunar2solar: function (y, m, d, isLeapMonth) { //参数区间1900.1.31~2100.12.1
var leapOffset = 0;
var leapMonth = calendar.leapMonth(y);
var leapDay = calendar.leapDays(y);
if (isLeapMonth && (leapMonth != m)) { return -1; }//传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同
if (y == 2100 && m == 12 && d > 1 || y == 1900 && m == 1 && d < 31) { return -1; }//超出了最大极限值
var day = calendar.monthDays(y, m);
if (y < 1900 || y > 2100 || d > day) { return -1; }//参数合法性效验
//计算农历的时间差
var offset = 0;
for (var i = 1900; i < y; i++) {
offset += calendar.lYearDays(i);
}
var leap = 0, isAdd = false;
for (var i = 1; i < m; i++) {
leap = calendar.leapMonth(y);
if (!isAdd) {//处理闰月
if (leap <= i && leap > 0) {
offset += calendar.leapDays(y); isAdd = true;
}
}
offset += calendar.monthDays(y, i);
}
//转换闰月农历 需补充该年闰月的前一个月的时差
if (isLeapMonth) { offset += day; }
//1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点)
var stmap = Date.UTC(1900, 1, 30, 0, 0, 0);
var calObj = new Date((offset + d - 31) * 86400000 + stmap);
var cY = calObj.getUTCFullYear();
var cM = calObj.getUTCMonth() + 1;
var cD = calObj.getUTCDate();
return calendar.solar2lunar(cY, cM, cD);
}
};
return calendar;
})();
/**
* widget: YearCal
*/
(function () {
var kendo = window.kendo;
var ui = kendo.ui;
var Widget = ui.Widget;
var progress = kendo.ui.progress;
var NS = '.kendoYearCal';
var CHANGE = "change";
var PROGRESS = "progress";
var ERROR = "error";
var DataSource = kendo.data.DataSource;
var dataProvider = {
solarMonthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
weeks: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
solarFestivals: {
'd0101': '元旦节',
'd0202': '世界湿地日',
'd0210': '国际气象节',
'd0214': '情人节',
'd0301': '国际海豹日',
'd0303': '全国爱耳日',
'd0305': '学雷锋纪念日',
'd0308': '妇女节',
'd0312': '植树节,孙中山逝世纪念日',
'd0314': '国际警察日',
'd0315': '消费者权益日',
'd0317': '中国国医节,国际航海日',
'd0321': '世界森林日,消除种族歧视国际日,世界儿歌日',
'd0322': '世界水日',
'd0323': '世界气象日',
'd0324': '世界防治结核病日',
'd0325': '全国中小学生安全教育日',
'd0330': '巴勒斯坦国土日',
'd0401': '愚人节,全国爱国卫生运动月(四月),税收宣传月(四月)',
'd0407': '世界卫生日',
'd0422': '世界地球日',
'd0423': '世界图书和版权日',
'd0424': '亚非新闻工作者日',
'd0501': '劳动节',
'd0504': '青年节',
'd0505': '碘缺乏病防治日',
'd0508': '世界红十字日',
'd0512': '国际护士节',
'd0515': '国际家庭日',
'd0517': '世界电信日',
'd0518': '国际博物馆日',
'd0520': '全国学生营养日',
'd0522': '国际生物多样性日',
'd0523': '国际牛奶日',
'd0531': '世界无烟日',
'd0601': '国际儿童节',
'd0605': '世界环境日',
'd0606': '全国爱眼日',
'd0617': '防治荒漠化和干旱日',
'd0623': '国际奥林匹克日',
'd0625': '全国土地日',
'd0626': '国际禁毒日',
'd0701': '香港回归纪念日,中共诞辰,世界建筑日',
'd0702': '国际体育记者日',
'd0707': '抗日战争纪念日',
'd0711': '世界人口日',
'd0730': '非洲妇女日',
'd0801': '建军节',
'd0808': '中国男子节(爸爸节)',
'd0815': '抗日战争胜利纪念',
'd0908': '国际扫盲日,国际新闻工作者日',
'd0909': '毛泽东逝世纪念',
'd0910': '中国教师节',
'd0914': '世界清洁地球日',
'd0916': '国际臭氧层保护日',
'd0918': '九一八事变纪念日',
'd0920': '国际爱牙日',
'd0927': '世界旅游日',
'd0928': '孔子诞辰',
'd1001': '国庆节,世界音乐日,国际老人节',
'd1002': '国际和平与民主自由斗争日',
'd1004': '世界动物日',
'd1006': '老人节',
'd1008': '全国高血压日,世界视觉日',
'd1009': '世界邮政日,万国邮联日',
'd1010': '辛亥革命纪念日,世界精神卫生日',
'd1013': '世界保健日,国际教师节',
'd1014': '世界标准日',
'd1015': '国际盲人节(白手杖节)',
'd1016': '世界粮食日',
'd1017': '世界消除贫困日',
'd1022': '世界传统医药日',
'd1024': '联合国日,世界发展信息日',
'd1031': '世界勤俭日',
'd1107': '十月社会主义革命纪念日',
'd1108': '中国记者日',
'd1109': '全国消防安全宣传教育日',
'd1110': '世界青年节',
'd1111': '国际科学与和平周(本日所属的一周)',
'd1112': '孙中山诞辰纪念日',
'd1114': '世界糖尿病日',
'd1117': '国际大学生节,世界学生节',
'd1121': '世界问候日,世界电视日',
'd1129': '国际声援巴勒斯坦人民国际日',
'd1201': '世界艾滋病日',
'd1203': '世界残疾人日',
'd1205': '国际经济和社会发展志愿人员日',
'd1208': '国际儿童电视日',
'd1209': '世界足球日',
'd1210': '世界人权日',
'd1212': '西安事变纪念日',
'd1213': '南京大屠杀(1937年)纪念日',
'd1220': '澳门回归纪念',
'd1221': '国际篮球日',
'd1224': '平安夜',
'd1225': '圣诞节',
'd1226': '毛泽东诞辰纪念'
},
lunarFestivals: {
'd0101': '春节',
'd0115': '元宵节',
'd0202': '龙抬头节',
'd0323': '妈祖生辰',
'd0505': '端午节',
'd0707': '七夕情人节',
'd0715': '中元节',
'd0815': '中秋节',
'd0909': '重阳节',
'd1015': '下元节',
'd1208': '腊八节',
'd1223': '小年',
'd0100': '除夕'
},
_data: {},
/**
* 判断公历年是否是闰年
* @param {number} year 公历年
*/
_isSolarLeapYear: function (year) {
return ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0));
},
/**
* 获取公历月份的天数
* @param {number} year 公历年
* @param {number} month 公历月
*/
_getSolarMonthDayCount: function (year, month) {
var monthDays = [31, this._isSolarLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return monthDays[month - 1];
// 另一种方法
// return new Date(year, month + 1, 0).getDate();
},
_getD4String: function (month, day) {
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
return 'd' + month + day;
},
_getSolarFestival: function (month, day) {
var me = this;
return me.solarFestivals[me._getD4String(month, day)];
},
_getLunarFestival: function (lmonth, lday) {
var me = this;
return me.lunarFestivals[me._getD4String(lmonth, lday)];
},
_getSolarMonthName: function (month) {
return this.solarMonthNames[month - 1];
},
_getCombineFestival: function (data) {
var me = this;
var r = [];
var sf = me.festival;
if (sf != null) {
r = r.concat(sf.split(','));
}
var lf = data.lunar.festival;
if (lf != null) {
r = r.concat(lf.split(','));
}
var term = data.lunar.term;
if (term != null) {
r.push(term);
}
return r;
},
_getDayName: function (week) {
return this.weeks[week];
},
getSolarData: function (year, month, day) {
var me = this;
var date = new Date(year, month - 1, day);
var week = date.getDay();
var day = date.getDate();
var data = {
id: me._getD4String(month, day),
day: day,
year: year,
month: month,
date: date,
week: week,
dayName: this._getDayName(week),
festival: this._getSolarFestival(month, day),
isWeekend: week === 0 || week === 6
};
return data;
},
getLunarData: function (year, month, day) {
var d = lunarCalendar.solar2lunar(year, month, day);
var lmonth = d.lMonth;
var lday = d.lDay;
var data = {
year: d.lYear,
month: lmonth,
day: lday,
monthName: d.IMonthCn,
dayName: d.IDayCn,
term: d.Term,
festival: this._getLunarFestival(lmonth, lday)
}
return data;
},
getFullData: function (year, month, day) {
var data = this.getSolarData(year, month, day);
data.lunar = this.getLunarData(year, month, day);
data.festival = this._getCombineFestival(data);
return data;
},
getMonthOfData: function (year, month) {
var me = this;
var days = [[]];
var dayCount = this._getSolarMonthDayCount(year, month);
for (var i = 0; i < dayCount; i++) {
var data = me.getFullData(year, month, i + 1);
me._data[data.id] = data;
var weekIdx = data.week === 0 ? 6 : data.week - 1;
if (weekIdx === 0 && i !== 0) {
days.push([]);
}
var currWeek = days[days.length - 1];
currWeek[weekIdx] = data;
// 后补空
if (i === dayCount - 1 && weekIdx < 6) {
currWeek[6] = undefined;
}
}
if (days.length < 6) {
var idx = days.length;
while (idx < 6) {
var blank = [];
blank[6] = undefined;
days.push(blank);
idx++;
}
}
var result = {
title: this._getSolarMonthName(month),
days: days
};
return result;
},
findData: function (id) {
return this._data[id];
}
};
var YearCal = Widget.extend({
options: {
name: 'YearCal',
year: '',
dataSource: null,
autoBind: true,
template: '<div class="cal">' +
'<div class="cal__header">' +
'<span class="cal__info_month_year" id="label"> #: data.title # </span>' +
'</div> ' +
'<table class="cal__frame cal__frame-head"> ' +
'<tr>' +
'<td class="cal__cell cal__cell-head">一</td>' +
'<td class="cal__cell cal__cell-head">二</td> ' +
'<td class="cal__cell cal__cell-head">三</td>' +
'<td class="cal__cell cal__cell-head">四</td>' +
'<td class="cal__cell cal__cell-head">五</td>' +
'<td class="cal__cell cal__cell-head cal__cell-weekend">六</td>' +
'<td class="cal__cell cal__cell-head cal__cell-weekend">日</td>' +
'</tr>' +
'</table>' +
'<table class="cal__frame cal__frame-day">' +
'<tbody>' +
'# for(var i=0; i < data.days.length; i++){ #' +
'# var line=data.days[i]; #' +
'<tr> ' +
'# for(var j=0; j < line.length; j++){ #' +
'<td class="cal__cell cal__cell-day">' +
'# var item=line[j]; #' +
'# if(item !=null){ #' +
'<div data-id="#: item.id #" class="cal__day">' +
'<span class="cal__info_day_number">#: item.day #</span> ' +
'# if(item.festival.length===0){ # ' +
'<span class="cal__info_lunar_day_name">#: item.lunar.dayName #</span>' +
' # } else { # ' +
'<span title="#: item.festival[0] #" class="cal__info_festival">#: item.festival[0] #</span>' +
' # } # ' +
'</div>' +
'# }else{ } # ' +
'</td>' +
'# } #' +
'</tr>' +
'# } #' +
'</tbody>' +
'</table>' +
'</div>',
popupTemplate: '<div data-id="#: data.id #">' +
'<div> #: data.lunar.monthName # #: data.lunar.dayName # #: data.dayName #</div>' +
'<hr class="hr-sm" />' +
'<div>' +
'# if(data.dayState && data.dayState !==0){ #' +
'<button data-value="0" class="btn-cancel btn btn-default btn-xs">撤销设置</button> ' +
'# } #' +
'# if(data.dayState !==1){ #' +
'<button data-value="1" class="btn-cancel btn btn-default btn-xs">设为工作日</button> ' +
'# } #' +
'# if(data.dayState !==2){ #' +
'<button data-value="2" class="btn-cancel btn btn-default btn-xs">设为休息日</button> ' +
'# } #' +
'</div>' +
'</div>'
},
events: [
'change',
'edit'
],
dataProvider: dataProvider,
init: function (element, options) {
var me = this;
Widget.fn.init.call(me, element, options);
options = me.options;
this.year = this.options.year;
this._templates();
this._initPopup();
this._html();
this._bindEvents();
this._bindDomEvents();
this._dataSource();
if (options.autoBind) {
me.dataSource.fetch();
}
kendo.notify(me);
},
_renderMonth: function (year, month) {
var data = this.dataProvider.getMonthOfData(year, month);
return this.template(data);
},
_html: function () {
var year = this.year;
if (year == false) {
return;
}
var html = '';
var month = 1;
while (month <= 12) {
html += this._renderMonth(year, month);
month++;
}
this.element.html(html);
},
changeYear: function (year) {
this.year = year;
this._html();
this.trigger('changeYear', this.year);
},
setDataSource: function(dataSource){
this.options.dataSource = dataSource;
this._dataSource();
if (this.options.autoBind) {
dataSource.fetch();
}
},
_dataSource: function () {
var me = this;
if (me.dataSource && me._refreshHandler) {
me._unbindDataSource();
} else {
me._refreshHandler = $.proxy(me.refresh, me);
me._progressHandler = $.proxy(me._progress, me);
me._errorHandler = $.proxy(me._error, me);
}
me.dataSource = DataSource.create(me.options.dataSource)
.bind(CHANGE, me._refreshHandler)
.bind(PROGRESS, me._progressHandler)
.bind(ERROR, me._errorHandler);
},
_unbindDataSource: function () {
var me = this;
me.dataSource.unbind(CHANGE, me._refreshHandler)
.unbind(PROGRESS, me._progressHandler)
.unbind(ERROR, me._errorHandler);
},
_progress: function () {
progress(this.element, true);
},
_error: function () {
progress(this.element, false);
},
_templates: function () {
var options = this.options;
this.template = kendo.template(options.template, {useWithBlock: false});
this.popupTemplate = kendo.template(options.popupTemplate, {useWithBlock: false});
},
refresh: function () {
var me = this;
var view = me.dataSource.view();
if(view.length > 0){
me.element.find('.cal__day').removeClass('cal__day-record off_day work_day');
}
for (var idx = 0, length = view.length; idx < length; idx++) {
var item = view[idx];
// 设置数据的状态
var state = item.state;
var id = item.id;
if (state === 1 || state === 2) {
var cls = 'cal__day-record';
var statCls = state === 2 ? 'off_day' : 'work_day';
me.element.find('.cal__day[data-id=' + id + ']').addClass(cls + ' ' + statCls);
}
var data = me.dataProvider.findData(item.id);
if (data != null) {
data.dayState = state;
}
}
progress(this.element, false);
},
select: function ($el) {
this.element.find('.active').removeClass('active');
$el.addClass('active');
var id = $el.data('id');
this.trigger('change', {
target: $el,
id: id
});
},
_initPopup: function () {
this.popup = this.element.qtip({
id: 'cal',
content: {
text: '加载中...'
},
position: {
my: 'bottom center',
at: 'top center',
target: 'body'
},
style: {
classes: 'qtip-light qtip-shadow'
},
show: {
delay: '5',
event: 'click'
},
hide: {
event: 'unfocus'
}
}).qtip('api').show().hide();
},
_bindEvents: function () {
var me = this;
this.bind('change', function (e) {
var data = me.dataProvider.findData(e.id);
if (data != null) {
me._openPopup(e.target, data);
}
});
},
_openPopup: function ($target, data) {
var me = this;
// me.element.find('.cal__day[data-id='+ data.id +']')
me.popup.set({
'content.title': data.date.toLocaleDateString('zh'),
'content.text': me.popupTemplate(data),
'position.target': $target
});
me.popup.show();
},
_bindDomEvents: function () {
var clickNS = 'click' + NS;
var me = this;
this.element.on(clickNS, '.cal__day', function (e) {
var $target = $(e.currentTarget);
var id = $target.data('id');
me.select($target);
});
this.popup.elements.tooltip.on(clickNS, '.btn', function(e){
me.trigger('edit', {
target: e.currentTarget
})
})
},
destroy: function () {
Widget.fn.destroy.call(this);
this._unbindDataSource();
this.element.off(NS);
if (this.popup) {
this.popup.elements.tooltip.off(NS);
this.popup.destroy(true);
}
kendo.destroy(this.element);
}
});
kendo.ui.plugin(YearCal);
})();
<file_sep>var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('script', function() {
return gulp.src(['./src/js/lunar.js', './src/js/index.js'])
.pipe(concat('index.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('style', function(){
return gulp.src('./src/less/index.css')
.pipe(gulp.dest('./dist/'))
})
gulp.task('default', ['script', 'style']); | 822ab9164a8d498ecd1793fd1bb28e13128e5069 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | gochant/yearCal | da5fdb1f8fc71fb1a41ab2e0960331f18e62585d | 79ad55fbf8f2ebf083969e79ad0b6e566c74de39 |
refs/heads/master | <file_sep>#!/bin/bash
# setup download links
ANT_DOWNLOAD_LINK=http://ftp.carnet.hr/misc/apache//ant/binaries/apache-ant-1.9.4-bin.tar.gz
M2_DOWNLOAD_LINK=http://ftp.carnet.hr/misc/apache/maven/maven-3/3.2.2/binaries/apache-maven-3.2.2-bin.tar.gz
GRADLE_DOWNLOAD_LINK=https://services.gradle.org/distributions/gradle-2.0-all.zip
CS_DOWNLOAD_LINK=http://sourceforge.net/projects/checkstyle/files/latest/download?source=files
XALAN_DOWNLOAD_LINK=http://archive.apache.org/dist/xml/xalan-j/xalan-j_2_7_1-bin.zip
PMD_DOWNLOAD_LINK=http://sourceforge.net/projects/pmd/files/pmd/5.1.2/pmd-bin-5.1.2.zip/download
FINDBUGS_DOWNLOAD_LINK=http://sourceforge.net/projects/findbugs/files/findbugs/3.0.0/findbugs-3.0.0.tar.gz/download
JUNIT_DOWNLOAD_LINK=http://search.maven.org/remotecontent?filepath=junit/junit/4.11/junit-4.11.jar
HAMCREST_DOWNLOAD_LINK=http://search.maven.org/remotecontent?filepath=org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar
JACOCO_DOWNLOAD_LINK=http://search.maven.org/remotecontent?filepath=org/jacoco/jacoco/0.7.1.201405082137/jacoco-0.7.1.201405082137.zip
MOCKITO_DOWNLOAD_LINK=https://mockito.googlecode.com/files/mockito-all-1.9.5.jar
TOMCAT_DOWNLOAD_LINK=http://ftp.carnet.hr/misc/apache/tomcat/tomcat-8/v8.0.9/bin/apache-tomcat-8.0.9.tar.gz
# setup destination
DEST=/usr/local/bin # destination where all tools will be installed
DIR_INIT=$(pwd) # desination of all tools before install
CONFIG_PATH=~/.profile # destination where path will be written
ANT_INIT=apache-ant # name of apache ant folder
M2_INIT=apache-maven # name of apache maven folder
GRADLE_INIT=gradle # name of gradle folder
CS_INIT=checkstyle # name of chechstyle folder
XALAN_INIT=xalan # name of xalan folder
PMD_INIT=pmd # name of pmd folder
FINDBUGS_INIT=findbugs # name of findbugs folder
JUNIT_INIT=junit.jar # name of junit jar
HAMCREST_INIT=hamcrest-core.jar # name of hamcrest jar
DIRNAME=junit # name of folder where $HAMCREST_INIT and $JUNIT_INIT will be installed
JACOCO_INIT=jacoco # name of jacoco folder
MOCKITO_INIT=mockito.jar # name of mockito jar
MOCKITO_DIR=mockito # name of folder where mockito will be installed
TOMCAT_INIT=apache-tomcat # name of apache tomcat folder
# download and extract apache-ant
wget $ANT_DOWNLOAD_LINK -O $ANT_INIT.tar.gz
mkdir $ANT_INIT
tar -xvf $ANT_INIT.tar.gz -C $ANT_INIT --strip-components 1
# download and extract apache-maven
wget $M2_DOWNLOAD_LINK -O $M2_INIT.tar.gz
mkdir $M2_INIT
tar -xvf $M2_INIT.tar.gz -C $M2_INIT --strip-components 1
# download and extract gradle
wget $GRADLE_DOWNLOAD_LINK -O $GRADLE_INIT.zip
unzip $GRADLE_INIT.zip -d $GRADLE_INIT-tmp
TMP_DIR=$(ls $GRADLE_INIT-tmp)
mv $GRADLE_INIT-tmp/$TMP_DIR $GRADLE_INIT-tmp/$GRADLE_INIT
mv $GRADLE_INIT-tmp/$GRADLE_INIT .
rm -rf $GRADLE_INIT-tmp
# download and extract checkstyle
wget $CS_DOWNLOAD_LINK -O $CS_INIT.tar.gz
mkdir $CS_INIT
tar -xvf $CS_INIT.tar.gz -C $CS_INIT --strip-components 1
# download and extract xalan
wget $XALAN_DOWNLOAD_LINK -O $XALAN_INIT.zip
unzip $XALAN_INIT.zip -d $XALAN_INIT-tmp
export TMP_DIR=$(ls $XALAN_INIT-tmp)
mv $XALAN_INIT-tmp/$TMP_DIR $XALAN_INIT-tmp/$XALAN_INIT
mv $XALAN_INIT-tmp/$XALAN_INIT .
rm -rf $XALAN_INIT-tmp
# download and extract pmd
wget $PMD_DOWNLOAD_LINK -O $PMD_INIT.zip
unzip $PMD_INIT.zip -d $PMD_INIT-tmp
TMP_DIR=$(ls $PMD_INIT-tmp)
mv $PMD_INIT-tmp/$TMP_DIR $PMD_INIT-tmp/$PMD_INIT
mv $PMD_INIT-tmp/$PMD_INIT .
rm -rf $PMD_INIT-tmp
# download and extract findbugs
wget $FINDBUGS_DOWNLOAD_LINK -O $FINDBUGS_INIT.tar.gz
mkdir $FINDBUGS_INIT
tar -xvf $FINDBUGS_INIT.tar.gz -C $FINDBUGS_INIT --strip-components 1
# download junit and hamcrest
wget $JUNIT_DOWNLOAD_LINK -O $JUNIT_INIT
wget $HAMCREST_DOWNLOAD_LINK -O $HAMCREST_INIT
# download and extract jacoco
wget $JACOCO_DOWNLOAD_LINK -O $JACOCO_INIT.zip
unzip $JACOCO_INIT.zip -d $JACOCO_INIT
# download mocikto
wget $MOCKITO_DOWNLOAD_LINK -O $MOCKITO_INIT
# download and extract apache-tomcat
wget $TOMCAT_DOWNLOAD_LINK -O $TOMCAT_INIT.tar.gz
mkdir $TOMCAT_INIT
tar -xvf $TOMCAT_INIT.tar.gz -C $TOMCAT_INIT --strip-components 1
# create destination directory - no error if exsist
mkdir -p $DEST
# setting up apache-ant
sudo cp -rf $DIR_INIT/$ANT_INIT $DEST
export ANT_HOME=$DEST/$ANT_INIT
echo "# apache-ant" >> $CONFIG_PATH
echo "export ANT_HOME=$DEST/$ANT_INIT" >> $CONFIG_PATH
export PATH=$ANT_HOME/bin:$PATH
echo -e 'export PATH=$PATH:$ANT_HOME/bin\n' >> $CONFIG_PATH
# setting up apache-maven
sudo cp -rf $DIR_INIT/$M2_INIT $DEST
export M2_HOME=$DEST/$M2_INIT
echo "# apache-maven" >> $CONFIG_PATH
echo "export M2_HOME=$DEST/$M2_INIT" >> $CONFIG_PATH
export PATH=$M2_HOME/bin:$PATH
echo -e 'export PATH=$PATH:$M2_HOME/bin\n' >> $CONFIG_PATH
# setting up gradle
sudo cp -rf $DIR_INIT/$GRADLE_INIT $DEST
export GRADLE_HOME=$DEST/$GRADLE_INIT
echo "# gradle" >> $CONFIG_PATH
echo "export GRADLE_HOME=$DEST/$GRADLE_INIT" >> $CONFIG_PATH
export PATH=$GRADLE_HOME/bin:$PATH
echo =e 'export PATH=$PATH:$GRADLE_HOME/bin\n' >> $CONFIG_PATH
# setting up checkstyle
sudo cp -rf $DIR_INIT/$CS_INIT $DEST
# setting up xalan
sudo cp -rf $DIR_INIT/$XALAN_INIT $DEST
# setting up pmd
sudo cp -rf $DIR_INIT/$PMD_INIT $DEST
# setting up findbugs
sudo cp -rf $DIR_INIT/$FINDBUGS_INIT $DEST
export FINDBUGS_HOME=$DEST/$FINDBUGS_INIT
echo "# findbugs" >> $CONFIG_PATH
echo "export FINDBUGS_HOME=$DEST/$FINDBUGS_INIT" >> $CONFIG_PATH
export PATH=$FINDBUGS_HOME/bin:$PATH
echo -e 'export PATH=$PATH:$FINDBUGS_HOME/bin\n' >> $CONFIG_PATH
# setting up junit
sudo mkdir $DEST/$DIRNAME
sudo cp $DIR_INIT/$JUNIT_INIT $DEST/$DIRNAME
sudo chmod +x $DEST/$DIRNAME/$JUNIT_INIT
sudo cp $DIR_INIT/$HAMCREST_INIT $DEST/$DIRNAME
sudo chmod +x $DEST/$DIRNAME/$HAMCREST_INIT
# setting up jacoco
sudo cp -rf $DIR_INIT/$JACOCO_INIT $DEST
# setting up mockito
sudo mkdir $DEST/$MOCKITO_DIR
sudo cp $DIR_INIT/$MOCKITO_INIT $DEST/$MOCKITO_DIR
sudo chmod +x $DEST/$MOCKITO_DIR/$MOCKITO_INIT
# setting up apache-tomcat
sudo cp -rf $DIR_INIT/$TOMCAT_INIT $DEST
export CATALINA_HOME=$DEST/$TOMCAT_INIT
echo "# apache-tomcat" >> $CONFIG_PATH
echo "export CATALINA_HOME=$DEST/$TOMCAT_INIT" >> $CONFIG_PATH
export PATH=$CATALINA_HOME/bin:$PATH
echo -e 'export PATH=$PATH:$CATALINA_HOME/bin\n' >> $CONFIG_PATH
sudo chown -R $USER $CATALINA_HOME
# remove unused ant
rm -rf $ANT_INIT
rm $ANT_INIT.tar.gz
# remove unused maven
rm -rf $M2_INIT
rm $M2_INIT.tar.gz
# remove unused gradle
rm -rf $GRADLE_INIT
rm $GRADLE_INIT.zip
# remove unused checkstyle
rm -rf $CS_INIT
rm $CS_INIT.tar.gz
# remove unused xalan
rm -rf $XALAN_INIT
rm $XALAN_INIT.zip
# remove unused pmd
rm -rf $PMD_INIT
rm $PMD_INIT.zip
# remove unused findbugs
rm -rf $FINDBUGS_INIT
rm $FINDBUGS_INIT.tar.gz
# remove unused junit and hamcrest
rm $JUNIT_INIT
rm $HAMCREST_INIT
# remove unused jocooc
rm -rf $JACOCO_INIT
rm $JACOCO_INIT.zip
# remove unused mockito
rm $MOCKITO_INIT
# remove unused tomcat
rm -rf $TOMCAT_INIT
rm $TOMCAT_INIT.tar.gz
echo "--- Tools are now installed in $DEST and paths are written in $CONFIG_PATH ---"
echo "--- All done ---"
<file_sep>#!/bin/bash
ID="$(xinput | egrep -i ".*touchpad" | egrep -o "id=[[:digit:]]+" | egrep -o "[[:digit:]]+")"
S="$(xinput --list-props $ID | egrep 'Device Enabled' | egrep -o "[[:digit:]]+$")"
if [ $S -eq 1 ]
then
xinput disable $ID
echo "Touchpad disabled!"
else
xinput enable $ID
echo "Touchpad enabled!"
fi
<file_sep>#!/bin/bash
source_code="$1"
gcc $source_code
if [[ $? > 0 ]]; then
exit
fi
for i in {1..100}; do
input="$i.in"
output="$i.out"
user_output="$i.out.user"
if [[ ! -f $input ]]; then
break
fi
./a.out < $input > $user_output
echo "- Test #$i -"
cmp -s $output $user_output
if [[ $? -eq 1 ]]; then
echo "WRONG"
else
echo "ACCEPTED"
rm $user_output
fi
echo
done
<file_sep>#!/bin/bash
help_link="https://github.com/hermanzdosilovic/scripts/tree/master/testcase-fit"
log_file=$HOME/.tcfit.log
if [[ $# -lt 4 ]]; then
echo "usage: tcfit <inext> <outext> <name> <dest>"
echo "
<inext>
extension of input test case file
<outext>
extension of output test case files
<name>
new name for test case group
<dest>
destination where test cases will be stored
"
echo "For more help and examples please visit $help_link"
exit
fi
inext="$1"
outext="$2"
name="$3"
dest="$4"
start="$5"
if [[ ! $5 =~ ^[1-9][0-9]*$ ]]; then
start="1"
fi
inputs=( $(find . -type f -regextype posix-egrep -regex "^.*/(.*\.|.{0})$inext(\..*|.{0})$" | sort) )
outputs=( $(find . -type f -regextype posix-egrep -regex "^.*/(.*\.|.{0})$outext(\..*|.{0})$" | sort) )
date > $log_file; echo >> $log_file
echo "Listing all found input test cases:" >> $log_file
printf "%s\n" "${inputs[@]}" >> $log_file; echo >> $log_file
echo "Listing all found output test cases:" >> $log_file
printf "%s\n" "${outputs[@]}" >> $log_file; echo >> $log_file
if [[ ${#inputs[@]} != ${#outputs[@]} ]]; then
echo "ERROR: Number of input test cases and output test cases should be the same!" 1>&2
echo "ERROR: Number of input test cases and output test cases should be the same!" >> $log_file
echo "For more help and examples please visit $help_link" | tee -a $log_file
exit
fi
if [ ! -d "$dest" ]; then
echo "ERROR: Directory $dest not found" 1>&2
echo "ERROR: Directory '$dest' not found" >> $log_file
echo "For more help and examples please visit $help_link" | tee -a $log_file
exit
fi
test_dir="$dest/test/$name"
mkdir -p "$test_dir"
for (( i=0; i<${#inputs[@]}; i++ )); do
k="$(printf "%02d" $start)"
start=$[$start+1]
cp "${inputs[i]}" "$test_dir/$name.in.$k"
echo "cp ${inputs[i]} $test_dir/$name.in.$k" | tee -a $log_file
cp "${outputs[i]}" "$test_dir/$name.out.$k"
echo "cp ${outputs[i]} $test_dir/$name.out.$k" | tee -a $log_file
echo | tee -a $log_file
done
echo "All done. Updated $log_file"
<file_sep># fast-ev
Simple script for fast task evaluation on programming contests.
## Example Structure
```
competition_folder/
|-- task_1/
| |-- 1.in
| |-- 1.out
| |-- 2.in
| |-- 2.out
| |-- solution.c
| |-- solution_brute.c
| |-- task_1.c
|
|-- task_2/
| |-- 1.in
| |-- 1.out
| |-- 2.in
| |-- 2.out
| |-- 3.in
| |-- 3.out
| |-- 4.in
| |-- 4.out
| |-- first_try.c
| |-- second_try.c
|
|-- fast-ev.sh
```
In `task_1` folder run following command for testing `solution_brute.c`:
``` bash
fast-ev solution_brute.c
```
## Example Output
```
- Test #1 -
ACCEPTED
- Test #2 -
ACCEPTED
- Test #3 -
ACCEPTED
- Test #4 -
WRONG
```
<file_sep>Java Course
===========
[Java Course](http://java.zemris.fer.hr/) originally called *Osnove programskog jezika Java* is a great Java course that I attended in my second semester at [Faculty of Electrical Engineering and Computing (FER)](http://www.fer.unizg.hr/en) in [Zagreb](http://en.wikipedia.org/wiki/Zagreb).
On the course we needed to use several tools for [code analysis](http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis), few for [TDD](http://en.wikipedia.org/wiki/Test-driven_development) and few for web application development.
After the course I swiched my OS few times and every time I found myself downloading and setuping these tools. And after my third setup by hand it became a pain in the butt, so I decided to write a little bash script that will download and setup these tools for me.
###Attention: OS X and Linux only!
Who is this for
----------------
* For every future student who will attend the same Java Course as I did.
* For everybody who needs to use these tools **now** and does not want to do it by hand.
* For me. :P
What can you install with this script
-------------------------------------
This script includes following tools:
* [Apache Ant 1.9.4](http://ant.apache.org/)
* [Apache Tomcat 8.0.9](http://tomcat.apache.org/)
* [Apache Maven 3.2.2](http://maven.apache.org/)
* [Checkstyle 5.7](http://checkstyle.sourceforge.net/)
* [Findbugs 3.0.0](http://findbugs.sourceforge.net/)
* [Gradle 2.0](http://www.gradle.org/)
* [Hamcrest 1.3](https://github.com/hamcrest/JavaHamcrest)
* [Jacoco 0.7.1](http://www.eclemma.org/jacoco/)
* [Junit 4.11](http://junit.org/)
* [Mockito 1.9.5](https://code.google.com/p/mockito/)
* [PMD 5.1.2](http://pmd.sourceforge.net/)
* [Xalan-Java 2.7.1](http://xml.apache.org/xalan-j/)
How to run
----------
Please follow these steps:
1. Get the project
2. Open *java-course* folder in your terminal
3. Run the script
4. Logout and login again
###1. Get the project
[Download](https://github.com/hermanzdosilovic/scripts/archive/master.zip) the project to your computer.
or
Clone git repository with this command:
git clone https://github.com/hermanzdosilovic/scripts.git
If you downloaded the project make sure that you extract .zip file that you got. If you cloned repository you do not have to do that.
###2. Open *java-course* folder in your terminal
1. Open project in your terminal. I now assume that you can see *java-course* folder when you type `ls`.
2. Type `cd java-course` to position yourself into *java-course* folder.
###3. Run the script
I now assume that you are in *java-course* folder. If so, run this command to start script:
sudo ./tools.sh
**You will need to enter your administrator password to run this script.**
The script will start downloading and extracting your tools. It will take a few minutes.
###4. Logout and login again
Just do it. :)
Important notes
---------------
Tools will be installed in `/usr/local/bin` and the paths that every tool needs to work properly will be written in `~/.profile`.
If you want you can change this default locations.
* If you want to change location where tools will be installed, edit:
* [`DEST`](https://github.com/hermanzdosilovic/scripts/blob/master/java-course/tools.sh#L18) variable that specifies where tools will be installed.
* If you want to change location where paths will be written, edit:
* [`CONFIG_PATH`](https://github.com/hermanzdosilovic/scripts/blob/master/java-course/tools.sh#L20) variable that specifies where paths will be written.
For additional changes that you would like to make in your installation package, please check the [`tools.sh`](https://github.com/hermanzdosilovic/scripts/blob/master/java-course/tools.sh) for more information.
###Skip some tools
If you want you can skip installing some tools by commenting specific lines of the script. For example, if you do not want to install [Gradle 2.0](http://www.gradle.org/) comment following lines:
* [Setting up a download link](https://github.com/hermanzdosilovic/scripts/blob/master/java-course/tools.sh#L6)
* [Downloading and extracting gradle](https://github.com/hermanzdosilovic/scripts/blob/master/java-course/tools.sh#L47-L53)
* [Setting up gradle](https://github.com/hermanzdosilovic/scripts/blob/master/java-course/tools.sh#L116-L122)
* [Remove unused gradle files](https://github.com/hermanzdosilovic/scripts/blob/master/java-course/tools.sh#L116-L122)
The same logic applies to other tools. :)
Testing Machines
----------------
I have tested this script on these machines:
* Ubuntu 12.04, 12.10, 13.04, 13.10, 14.04
* Linux Mint 16, 17
* OS X 10.9.5
<file_sep>#!/bin/bash
if [ -z "$REPO" ]; then
echo "Export you paths in REPO environment variable."
exit
fi
for directory in ${REPO//:/ }; do
echo " - $directory - "
if [ -d "$directory" ]; then
cd $directory
git pull
else
echo "Directory does not exists."
fi
echo
done
<file_sep>Git Helpers
===========
Scripts for helping in git tasks.
Helpers
-------
* [ggp](https://github.com/hermanzdosilovic/scripts/tree/master/git-helpers#ggp) - global `git pull` script
###ggp
1. In your `~/.profile` export a `REPO` variable that contains paths to your git repositories:
export REPO="$HOME/workspace/project1"
export REPO=$REPO:"$HOME/Documents/project2"
export REPO=$REPO:"/Volumes/MyHDD/workspace/my-secret-project"
This is just an example. I prefere one path per line, because I can then easily remove one from `$REPO`.
2. Download script and make it executable:
$ chmod +x ggp
3. Copy or move script in some directory that is included in your `$PATH` environment variable.
Copy:
$ cp ggp /usr/local/bin
Or move:
$ mv ggp /usr/local/bin
Now you will be able to use `ggp` from terminal anywhere you are and it will do `git pull` on all of your repositories that you included in `$REPO` environment variable.
<file_sep># tcfit
## About
Test case fit (`tcfit`) is an bash script for converting custom test case folder structure into structure that [`ev`](https://github.com/hermanzdosilovic/ev) recognizes.
## Basic Example
Lets say you have this kind of test case folder structure:
+ my-tests
+ test01
test.a
test.b
+ test02
test.a
test.b
+ test03
test.a
test.b
Here, the input file for first test case (**test01**) is **test.a** and output file **test.b**. The same goes for second and third test case.
If you want to test your `hello.c` program with these test cases using _ev_ you need to convert them to appropriate format, which is:
+ test
+ hello
hello.1.in
hello.2.in
hello.3.in
hello.1.out
hello.2.out
hello.2.out
As you can see, file `my-tests/test01/test.a` now became `test/hello/hello.1.in`.
To do just that you need to run:
</path/to/your/my-tests/folder>$ tcfit a b hello </path/to/root/of/test/folder>
### Explained:
`</path/to/your/my-tests/folder>` - you need to be located in folder where your custom-formated-test-cases are, in this case this is the `my-tests/` folder
`a` - this is an string which identifies your input test case file
`b` - this is an string which identifies your outout test case file
`hello` - this is the name of the program you will test
`</path/to/root/of/test/folder>` - this is the path where you will save your newly-formated-test-cases | fb51309d03a9f235fd3e11d9663966a8d4cc7f68 | [
"Markdown",
"Shell"
] | 9 | Shell | hermanzdosilovic/scripts | 1d0969a4d6fae57dd78ed40e149aab3117b47245 | 0361c31799521f7ffad1edd3212f027b08126dbd |
refs/heads/master | <file_sep>//
// Created by <NAME> on 3/20/18.
//
#ifndef TAREACORTA1_SORTING_HPP
#define TAREACORTA1_SORTING_HPP
#include "../PagedArray/PagedArray.h"
class Sorting {
public:
static void quickSort(PagedArray *arr, int left, int right);
static void insertionSort(PagedArray *arr, int length);
};
#endif //TAREACORTA1_SORTING_HPP
<file_sep>cmake_minimum_required(VERSION 3.9)
project(TareaCorta1)
set(CMAKE_CXX_STANDARD 11)
add_executable(TareaCorta1 main.cpp Memory/Memory.h PagedArray/Reader.cpp PagedArray/Reader.h Memory/Memory.cpp PagedArray/PagedArray.cpp PagedArray/PagedArray.h Sorting/Sorting.cpp Sorting/Sorting.hpp)<file_sep>//
// Created by karina on 19/03/18.
//
#ifndef TAREACORTA1_PAGEDARRAY_H
#define TAREACORTA1_PAGEDARRAY_H
#include "../Memory/Memory.h"
#include <iostream>
#include <string>
using std::string;
class PagedArray {
public:
Memory virtualMemory;
int MAX_INDEX;
PagedArray();
int& operator[](int);
void printTodasLasPaginas();
int *getSize();
};
#endif //TAREACORTA1_PAGEDARRAY_H
<file_sep>//
// Created by karina on 19/03/18.
//
#include "PagedArray.h"
#include <cmath>
#include <iostream>
#include "PagedArray.h"
#include "Reader.h"
PagedArray::PagedArray() {
Reader reader;
reader.writeFile();
MAX_INDEX = 1000;
}
int& PagedArray::operator[](int index) {
int requestedIndex = (index % 100);
int requestedPageNumber = (int) ceil(index/100) + 1;
struct Pagina* requestedPage = virtualMemory.cargarpagina(index);
//std::cout << "el indice que voy a pedir: " << requestedIndex << " de la pagina: " << requestedPageNumber <<std::endl;
for(int i = 0; i < 4; ++i){
if(*virtualMemory.todaslaspaginas[i].numerodepagina == requestedPageNumber){
requestedPage = &virtualMemory.todaslaspaginas[i];
}
}
//int* requestedValue = &requestedPage -> elementos[requestedIndex];
// std::cout << "Puntero: " << requestedValue << std::endl;
// std::cout << "Valor de puntero: " << *requestedValue << std::endl;
return requestedPage->elementos[requestedIndex];;
}
/*
* PARA TENER EL TAMANO EN BYTES DEL ARRAY Y ASI PODER USARLO EN QUICKSORT COMO LEFT
*/
int *PagedArray::getSize() {
return virtualMemory.getSize();
}
void PagedArray::printTodasLasPaginas(){
for(int x = 0; x < 4; x++) {
Pagina page = virtualMemory.todaslaspaginas[x];
for (int i = 0; i < 100; i++) {
std::cout << "Pagina: " << *page.numerodepagina << " Posicion: " << i << " valor: " << page.elementos[i]
<< std::endl;
}
std::cout << "-------" << std::endl;
}
}
<file_sep>#include <iostream>
#include "PagedArray/Reader.h"
#include "Memory/Memory.h"
#include "PagedArray/PagedArray.h"
#include "Sorting/Sorting.hpp"
using namespace std;
int main() {
PagedArray array;
/*std::cout << "----Prueba 1 regresa: " << array[0] << std::endl;//2
std::cout << "----Prueba 2 regresa: " << array[1] << std::endl;//8
std::cout << "----Prueba 3 regresa: " << array[100] << std::endl;//1
std::cout << "----Prueba 4 regresa: " << array[199] << std::endl;//1
std::cout << "----Prueba 5 regresa: " << array[200] << std::endl;//3*/
//int num = array[1];
//std::cout << "array[]: " << num << std::endl;
//array.printTodasLasPaginas();
// num = 18;
// std::cout << "array[]: " << num << std::endl;
// array.printTodasLasPaginas();
//std::cout<< "EL TAMANO DE MI ARCHIVO ES :" << *memoria.getSize() << " bytes" <<std::endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;
cout << "-----------------------------WELCOME---------------------------------" << endl;
cout << "----------------PLEASE CHOOSE ANY SORTING ALGORITHM------------------" << endl;
cout << "-------------------------Type QS for QuickSort-----------------------" << endl;
cout << "----------------------Type SS for SelectionSort----------------------" << endl;
cout << "----------------------Type IS for InsertionSort----------------------" << endl;
int *length = array.getSize();
// cout << "LENGTH: " << *length << endl;
int fl = *length / 4;
string input;
cin >> input;
if (input == "QS") {
Sorting::quickSort(&array, 0, fl - 1);
array.printTodasLasPaginas();
} else if (input == "IS") {
Sorting::insertionSort(&array, fl);
array.printTodasLasPaginas();
} else {
cout << "input not valid, type QS, IS, SS" << endl;
}
return 0;
}
| 16ad249b9d0aff4b3cd35870c7148d6675c97aee | [
"CMake",
"C++"
] | 5 | C++ | isaacporras/Tarea-Corta1 | 2d85584db76e2f73f0bffc4a8a887261957a3e98 | 02085f1b0b86dd539d1c0845c01525d7d151f195 |
refs/heads/main | <file_sep># frozen_string_literal: true
module Haml
# TODO: unify Haml::Error (former Hamlit::Error) and Haml::HamlError (former Haml::Error)
class Error < StandardError
attr_reader :line
def initialize(message = nil, line = nil)
super(message)
@line = line
end
end
class SyntaxError < Error; end
class InternalError < Error; end
class FilterNotFound < Error; end
end
<file_sep>#!/usr/bin/env ruby
require 'bundler/setup'
require 'hamlit'
require 'faml'
require 'benchmark/ips'
require_relative '../utils/benchmark_ips_extension'
h = { 'user' => { id: 1234, name: 'k0kubun' }, book_id: 5432 }
Benchmark.ips do |x|
quote = "'"
faml_options = { data: h }
x.report("Faml::AB.build") { Faml::AttributeBuilder.build(quote, true, nil, faml_options) }
x.report("Haml.build_data") { Haml::AttributeBuilder.build_data(true, quote, h) }
x.compare!
end
<file_sep># frozen_string_literal: true
module Haml
VERSION = '6.0.0.alpha'
end
<file_sep>#!/usr/bin/env ruby
require 'bundler/setup'
require 'hamlit'
require 'faml'
require 'benchmark/ips'
require_relative '../utils/benchmark_ips_extension'
Benchmark.ips do |x|
x.report("Faml::AB.build") { Faml::AttributeBuilder.build("'", true, nil, {:id=>"book"}, id: %w[content active]) }
x.report("Haml::AB.build_id") { Haml::AttributeBuilder.build_id(true, "book", %w[content active]) }
x.compare!
end
<file_sep># frozen_string_literal: true
require 'rails'
module Haml
class Railtie < ::Rails::Railtie
initializer :haml, before: :load_config_initializers do |app|
# Load haml/plugin first to override if available
begin
require 'haml/plugin'
rescue LoadError
end
require 'haml/rails_template'
end
end
end
<file_sep>describe Tilt::HamlTemplate do
describe '#render' do
it 'works normally' do
template = Tilt::HamlTemplate.new { "%p= name" }
assert_equal "<p>tilt</p>\n", template.render(Object.new, name: 'tilt')
end
end
end
| 161b07a1b9b919afecb05c7493727239c7e2e175 | [
"Ruby"
] | 6 | Ruby | Jay8181/haml | 1b47fd19a4e97ba3ec560866f0b54d06b206eaa6 | 639347590d6cabfedd05af88587b873e6328736d |
refs/heads/master | <file_sep>import urllib2
from jenkinsapi.jenkins import Jenkins
from twisted.internet import reactor
from twisted.web.http_headers import Headers
from settings import *
class Authentication():
def __init__(self):
self.jenkins_url()
self.user_credentials()
def jenkins_data(self):
self.agent = Agent(reactor)
self.data = self.agent.request(
'GET',
self.build_url,
Headers({'User-Agent': ['Display Jenkins Content']}),None)
def authenticate_user(self):
self.jenkins = Jenkins(self.new_url, self.username, self.password)
def data_from_url(self):
urllib2.urlopen(self.new_url).read()
def build_url(self):
return self.url + self.url_filter + self.api_call
def jenkins_url(self):
self.url = file_meta["url"]
self.url_filter = file_meta["filter"]
self.api_call = file_meta["api_call"]
def user_credentials(self):
self.username = file_meta["username"]
self.password = file_meta["password"]
import code
code.interact(local=locals())
<file_sep>import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class MockServer:
def __init__(self):
self._handler_class = SimpleHTTPRequestHandler
self._server_class = BaseHTTPServer.HTTPServer
self._protocol = "HTTP/1.0"
def port(self):
if sys.argv[1:]:
self._port = int(sys.argv[1])
else:
self._port = 8000
self.server_address = ('127.0.0.1', self._port)
def httpd(self):
self.HandlerClass.protocol_version = self._protocol
self.httpd = ServerClass(server_address, self._handler_class)
def socket_name(self):
self.sa = self.httpd.socket.getsocketname()
print "Serving on HTTP on", self._sa[0], "port", self._sa[1], "..."
def run_server(self):
httpd.serve_forever()
def handler(self):
print self.port
| b39f49a796df5cfab4016ae30664312ac5117343 | [
"Python"
] | 2 | Python | katmutua/mock-server | d39bc573f682cc9e11334de68f2d5232619ce210 | e72623dbb281840f0b35cd0124352d82b1b129be |
refs/heads/master | <file_sep>class AddPublishedAtToLinks < ActiveRecord::Migration[5.0]
def change
add_column :links, :published_at, :string
end
end
<file_sep># yt_local tst
<file_sep>class CreateLinks < ActiveRecord::Migration[5.0]
def change
create_table :links do |t|
t.string :link_text
t.string :ranking
t.string :videoid
t.timestamps
end
end
end
<file_sep>class Api::Common
# require 'net/http'
# require 'uri'
def get_video
response = HTTParty.get('https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=4Y4YSpF6d6w&key=AIzaSyBeMC4eMb_u-IqGeYRSpAzED8m5RcjTumg')
puts "DATA - #{response["items"][0]["statistics"]["viewCount"]}"
@response = JSON.parse response.to_json
end
end<file_sep>class Link < ApplicationRecord
validates :link_text, presence: true, uniqueness: { case_sensitive: false}
# after_create :save_video_viewcount
# after_update :save_video_viewcount
def save_video_viewcount
response = HTTParty.get('https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=4Y4YSpF6d6w&key=AIzaSyBeMC4eMb_u-IqGeYRSpAzED8m5RcjTumg')
puts "Calling save video count"
puts "DATA - #{response["items"][0]["statistics"]["viewCount"]}"
self.update.attributes(:ranking => response["items"][0]["statistics"]["viewCount"] )
end
end
<file_sep>class LinksController < ApplicationController
# include Httparty
before_action :set_link, only: [:show, :edit, :update, :destroy]
# GET /links
# GET /links.json
def api_common
Api::Common.save_video_viewcount
# return Api::Common.new
end
def index
# @links = Link.all
@links = Link.order(ranking: :desc)
end
# GET /links/1
# GET /links/1.json
def show
end
# GET /links/new
def new
@link = Link.new
end
# GET /links/1/edit
def edit
end
# POST /links
# POST /links.json
def create
@link = Link.new(link_params)
respond_to do |format|
if @link.save
save_video_viewcount(@link)
format.html { redirect_to @link, notice: 'Link was successfully created.' }
format.json { render :show, status: :created, location: @link }
else
save_video_viewcount(@link)
format.html { render :new }
format.json { render json: @link.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /links/1
# PATCH/PUT /links/1.json
def update
respond_to do |format|
if @link.update(link_params)
save_video_viewcount(@link)
format.html { redirect_to @link, notice: 'Link was successfully updated.' }
format.json { render :show, status: :ok, location: @link }
else
# save_video_viewcount(@link)
format.html { render :edit }
format.json { render json: @link.errors, status: :unprocessable_entity }
end
end
end
# DELETE /links/1
# DELETE /links/1.json
def destroy
@link.destroy
respond_to do |format|
format.html { redirect_to links_url, notice: 'Link was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_link
@link = Link.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def link_params
params.require(:link).permit(:link_text, :view_count, :videoid,:published_at)
end
def save_video_viewcount(link)
id = parse_youtube(link.link_text)
puts "id = #{id}"
# api = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=#{id}&key=AIzaSyBeMC4eMb_u-IqGeYRSpAzED8m5RcjTumg"
api = "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=#{id}&key=AIzaSyBeMC4eMb_u-IqGeYRSpAzED8m5RcjTumg"
response = HTTParty.get(api.to_s)
link.update_attributes(:view_count => response["items"][0]["statistics"]["viewCount"],:published_at => response["items"][0]["snippet"]["publishedAt"],
:ranking => (response["items"][0]["statistics"]["viewCount"].to_i / (Date.today - Date.parse(response["items"][0]["snippet"]["publishedAt"])).to_i ).to_f,
:thumbnail => response["items"][0]["snippet"]["thumbnails"]["default"]["url"],
:title => response["items"][0]["snippet"]["title"]
)
end
def parse_youtube(url)
regex = /(?:.be\/|\/watch\?v=|\/(?=p\/))([\w\/\-]+)/
url.match(regex)[1]
end
end
<file_sep>namespace :store_ranking do
desc "Storing data for ranking column"
task :store_ranks => :environment do
Link.all.each do |l|
rank = l.view_count.to_i/(Date.today - Date.parse(l.published_at) ).to_i
l.update_attributes(:ranking => rank)
end
end
end<file_sep>class RenameColumnNameToViewcount < ActiveRecord::Migration[5.0]
def change
rename_column :links, :ranking, :view_count
end
end
| f41bbd2889442df00547a671e8553a6c7c7ad64b | [
"Markdown",
"Ruby"
] | 8 | Ruby | sand33pn/yt_local | 4eb6c9189d157b49ad441d7311c0ed33cbe3850f | f9c842d5bc699e068884c36534c16569c3066659 |
refs/heads/master | <file_sep>// Define a Playlist class. It should have...
// A PLAYLIST title property that is determined by some input.
// A songs TITLE property that is determined by some input. It should contain multiple songs, each of which can just be a song title.
// A favorites property that is initialized at 0. This cannot be set by user input.
// An addSong method that adds a song to the songs property.
// Create an instance of the Playlist class.
// Create an Album class that inherits from Playlist. It should also...
// Have an artist property that is determined by some input.
// Create an instance of the Album class.
//Third attempt
class Playlist{
constructor(name, genre){
this.name = name;
this.genre = genre;
this.songtitle = [];
}
addSong(song){
this.songtitle.push(song);
console.log(this.songtitle);
}
}
let favs = new Playlist('faves', 'hard rock')
//Second attempt
// class Playlist{
// constructor(pltitle){
// this.pltitle = title;
// this.songtitle = [];
// }
// addSong(song){
// this.songtitle.push(song);
// console.log(this.songtitle)
// }
//
// }
// let playlist1 = new Playlist("<NAME>")
//First attempt
// class Playlist {
// constructor(title, songs){
// this.title = title;
// this.songs = songs;
// this.favorites = 0;
// this.song = [];
// }
// addSong(songs){
// this.song.push(songs);
// console.log(this.song);
//
// }
//
// }
// const go = new Playlist("Go");
| bea1cdf2042336c99de6bf17740f6773533ba34a | [
"JavaScript"
] | 1 | JavaScript | laburr27/checkpoint-03 | 9c02929649b6faf11e177caf6e4cdc881e64e446 | 7f15a9f32d6d75281d70c283cc4f5882a1ed0762 |
refs/heads/master | <repo_name>Ihorbar1/marwel<file_sep>/js/main.js
$(document).ready(function(){
$(".owl-carousel").owlCarousel({
items: 1,
dots: true,
// margin: 10
});
});
var test = document.getElementById("test");
console.dir(test)
| eaab6ddc76d499353aa3e516f59a8747c197e63f | [
"JavaScript"
] | 1 | JavaScript | Ihorbar1/marwel | bdf10493c6422a1fb42ff5dd0ef901cdc65d7f46 | 8e0b7da84ed05ab6456a20a164022d5347060248 |
refs/heads/master | <file_sep>"""This module moves the stepper motors"""
import time
import atexit
import threading
from Adafruit_MotorHAT import Adafruit_MotorHAT
STEP_SIZE = 200
STEP_SPEED = 50 # Speed of rotation (max = 200?)
NUM_STEPS = 10 # 50 = 1/4 circle
STEP_STYLE = Adafruit_MotorHAT.DOUBLE
last_x = None
last_y = None
stepper1 = None
stepper2 = None
mh = None
width = None
height = None
def init(w, h):
global mh, stepper1, stepper2, width, height
width = w
height = h
# create a default object, no changes to I2C address or frequency
mh = Adafruit_MotorHAT(addr=0x60)
atexit.register(turn_off_motors)
stepper1 = mh.getStepper(STEP_SIZE, 1) # 200 steps/rev, motor port #1
stepper2 = mh.getStepper(STEP_SIZE, 2) # 200 steps/rev, motor port #1
stepper1.setSpeed(STEP_SPEED)
stepper2.setSpeed(STEP_SPEED)
# recommended for auto-disabling motors on shutdown!
def turn_off_motors():
global mh
mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE)
def stepper_worker(stepper, num_steps, direction, style):
stepper.step(num_steps, direction, style)
def demo_steppers():
global stepper1, stepper2
st1 = threading.Thread(target=stepper_worker, args=(stepper1, 40, Adafruit_MotorHAT.FORWARD, STEP_STYLE))
st1.start()
time.sleep(1)
st2 = threading.Thread(target=stepper_worker, args=(stepper1, 40, Adafruit_MotorHAT.BACKWARD, STEP_STYLE))
st2.start()
def move_steppers(x, y):
global last_y, last_x, width, height
max_horizontal = 25
input_max_x = width
steps_x = (x / (input_max_x / (max_horizontal * 2))) - max_horizontal
last_x = steps_x
# Calculate vertical steps, we start in a 45degree position
max_vertical = 25
input_max_y = height
steps_y = (y / (input_max_y / (max_vertical * 2))) - max_vertical
last_y = steps_y
move_horizontal(steps_x)
#move_vertical(steps_y)
def move_horizontal(steps):
hor_direction = Adafruit_MotorHAT.BACKWARD
if steps < 0:
hor_direction = Adafruit_MotorHAT.FORWARD
steps = steps * -1
stepper1.step(steps, hor_direction, STEP_STYLE)
def move_vertical(steps):
ver_direction = Adafruit_MotorHAT.FORWARD
if steps < 0:
ver_direction = Adafruit_MotorHAT.BACKWARD
steps = steps * -1
st2 = threading.Thread(target=stepper_worker, args=(stepper2, steps, ver_direction, STEP_STYLE))
st2.start()
def return_steppers():
global last_y, last_x
move_horizontal(last_x * -1)
#move_vertical(last_y * -1)
if __name__ == "__main__":
init(100,100)
#move_steppers(50, 50)
#time.sleep(2)
#return_steppers()
demo_steppers()
<file_sep># caturret
Caturret w00tcamp 2017
## Raspberry Pi setup:
- [OpenCV install](https://www.pyimagesearch.com/2017/09/04/raspbian-stretch-install-opencv-3-python-on-your-raspberry-pi/)
- [GPIOzero pin schematics](https://gpiozero.readthedocs.io/en/stable/recipes.html#module-gpiozero)
- [Adafruit motor HAT](https://learn.adafruit.com/adafruit-dc-and-stepper-motor-hat-for-raspberry-pi/overview)
Add `bcm2835-v4l2` to `/etc/modules` to ensure v4l loads at boot time
## Packages
- Linux
- See OpenCV install link above for package list
- Pygame dependencies: `sudo apt-get build-dep python-pygame`
- Python
- `pip install -r requirements.txt`
## Part list
- [Adafruit DC & Stepper Motor HAT for Raspberry Pi](https://www.adafruit.com/product/2348)
- [Stepper motor - NEMA-17 size - 200 steps/rev, 12V 350mA](https://www.adafruit.com/product/324)
- [Two-channel 5V relais module](https://www.kiwi-electronics.nl/tweekanaals-relais-module-5v)
- [Raspberry Pi Camera Board](https://www.adafruit.com/product/3099)
- <file_sep>import imutils
import numpy
import time
import cv2
def monitor(callback, w, h, headless):
camera = cv2.VideoCapture(0)
time.sleep(0.25)
first_frame = None
width = w
height = h
while True:
(grabbed, frame) = camera.read()
if not grabbed:
break
frame = imutils.resize(frame, width)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if first_frame is None:
first_frame = gray
continue
frame_delta = cv2.absdiff(first_frame, gray)
thresh = cv2.threshold(frame_delta, 25, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
(_, contours, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_area, max_x, max_y, max_h, max_w = 0, 0, 0, 0, 0
for contour in contours:
if cv2.contourArea(contour) < 500:
continue
(x, y, w, h) = cv2.boundingRect(contour)
area = x * h
if area > max_area:
max_area, max_x, max_y, max_h, max_w = area, x, y, w, h
if max_area > 100:
# cv2.rectangle(frame, (max_x, max_y), (max_x + max_w, max_y + max_h), (0, 0, 255), 2)
target = (max_x + (max_w / 2), max_y + (max_h / 2))
cv2.circle(frame, target, 10, (0, 0, 255), 2)
callback(target)
if not headless:
cv2.imshow("caturret", frame)
frame_delta = cv2.merge([frame_delta, frame_delta, frame_delta])
thresh = cv2.merge([thresh, thresh, thresh])
gray = cv2.merge([gray, gray, gray])
output = numpy.zeros((height * 2, width * 2, 3), dtype="uint8")
output[0:height, 0:width] = gray
output[0:height, width:width * 2] = frame_delta
output[height:height * 2, 0:width] = thresh
output[height:height * 2, width:width * 2] = frame
cv2.waitKey(1)
camera.release()
cv2.destroyAllWindows()
<file_sep>import time, sys
from motion_detector import monitor
from cateyes import open_eyes, close_eyes
from pump import start_spray, stop_spray
from sound import play_random_sound
from stepper import init, move_steppers, return_steppers, demo_steppers
# Camera dimensions
width = 512
height = 384
# Loop delay
seconds_pause = 5
last_target_time = -1
SPRAY_DURATION = 1
LED_PIN = 27 # FIXME: Use this to init cateyes.py
RELAIS_PIN = 17 # FIXME: Use this to init pump.py
def main(headless):
global width, height
init(width, height)
monitor(on_target, width, height, headless)
def on_target(target):
global last_target_time
if should_fire():
last_target_time = time.time()
print "target=%s" % str(target)
open_eyes()
move_steppers(target[0], target[1])
# demo_steppers() # Only used if no camera available, instead of move_steppers()
start_spray()
# The sound is thread-blocking, so it also serves as interval timer
play_random_sound()
stop_spray()
return_steppers()
close_eyes()
def should_fire():
global last_target_time, seconds_pause
return last_target_time + seconds_pause < time.time()
if __name__ == "__main__":
#print "Received args: %s" % sys.argv
main(len(sys.argv) > 1)
# Demo crud (if no camera is available)
# init(100, 100)
# on_target(None)
<file_sep>from os import listdir
import pygame
import random
sounds_dir = "./sounds"
def play_random_sound():
global sounds_dir
try:
files = [f for f in listdir(sounds_dir) if f.endswith(".wav")]
random.randint(1, 10)
f = "%s/%s" % (sounds_dir, files[random.randint(0, len(files) - 1)])
pygame.mixer.init()
pygame.mixer.music.load(f)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
continue
except:
pass
if __name__ == "__main__":
play_random_sound()
<file_sep>Adafruit-GPIO==1.0.3
Adafruit-MotorHAT==1.4.0
Adafruit-PureIO==0.2.1
appnope==0.1.0
backports.functools-lru-cache==1.4
backports.shutil-get-terminal-size==1.0.0
cycler==0.10.0
decorator==4.1.2
enum34==1.1.6
gpiozero==1.4.0
imutils==0.4.3
ipython==5.5.0
ipython-genutils==0.2.0
matplotlib==2.1.0
networkx==2.0
numpy==1.13.3
olefile==0.44
pathlib2==2.3.0
pexpect==4.2.1
picamera==1.13
pickleshare==0.7.4
pigpio==1.38
Pillow==4.3.0
prompt-toolkit==1.0.15
ptyprocess==0.5.2
pygame==1.9.3
Pygments==2.2.0
pyparsing==2.2.0
python-dateutil==2.6.1
pytz==2017.2
PyWavelets==0.5.2
RPi.GPIO==0.6.3
scandir==1.6
simplegeneric==0.8.1
six==1.11.0
spidev==3.2
subprocess32==3.2.7
traitlets==4.3.2
wcwidth==0.1.7
<file_sep>"""This module toggles the pump"""
from time import sleep
from gpiozero import OutputDevice
# NOTE: the relais uses reverse logic, so on==off
RELAIS_1 = OutputDevice(17)
def toggle_relais(status):
if not status:
RELAIS_1.on()
else:
RELAIS_1.off()
def start_spray():
toggle_relais(True)
def stop_spray():
toggle_relais(False)
if __name__ == "__main__":
start_spray()
sleep(2)
stop_spray()
<file_sep>"""This module enables the cat to shine her eyes"""
from time import sleep
from gpiozero import LED
led = LED(27)
def toggle_light(status):
led.on() if status else led.off()
def open_eyes():
toggle_light(True)
def close_eyes():
toggle_light(False)
if __name__ == "__main__":
open_eyes()
sleep(2)
close_eyes()
| 43acb96aedb05b76c19264e935c0dfb666b88136 | [
"Markdown",
"Python",
"Text"
] | 8 | Python | Q42/caturret | 1211f86a20002161f9633f83733f711389b6f6b9 | c43a4e84ef42c3002f9fbbc7a14fd1588f116e78 |
refs/heads/master | <repo_name>HuygensING/timbuctoo-mappings<file_sep>/execute.js
const opn = require('opn');
const fetch = require('node-fetch')
const FormData = require('form-data');
const fs = require('fs')
const pathLib = require('path');
const stateFileName = __dirname + "/state.json";
const DEBUG = false;
const DraftLog = require('draftlog');
DraftLog(console)
let state = {};
try {
if (fs.existsSync(stateFileName)) {
state = JSON.parse(fs.readFileSync(stateFileName, "utf-8"));
}
} catch (e) {
console.log("Error while reading state file", e);
}
if (!state.input) {
state.input = {};
}
if (!state.mappingInput) {
state.mappingInput = {};
}
const timbuctoo_url = process.env.timbuctooUrl || "https://repository.huygens.knaw.nl"
function graphql(query, authId) {
return fetch(timbuctoo_url + "/v5/graphql", {
method: "POST",
body: JSON.stringify({
query: query
}),
headers: {
"content-type": "application/json",
Authorization: authId
}
})
.then(r => r.json())
.then(json => {
if (json.errors && json.errors.length > 0) {
throw new Error(JSON.stringify(json.errors));
} else {
return json.data
}
});
}
function graphqlDataSet(userInfo, datasetId, query) {
return graphql(`
{
dataSets {
${datasetId} {
${query}
}
}
}
`, userInfo.authorization).then(result => result.dataSets[datasetId])
}
async function executeAndPoll(userInfo, datasetId, promise) {
var draft = console.draft("\n".repeat(14))
const updatePoll = setInterval(function () {
graphql(`{
dataSetMetadata(dataSetId: "${datasetId}") {
currentImportStatus {
messages
}
}
}
`, userInfo.authorization)
.then(data => {
if (data.dataSetMetadata != null) {
const msgs = data.dataSetMetadata.currentImportStatus.messages;
if (msgs.length < 15) {
msgs.length = 15;
}
const width = process.stdout.columns;
draft(msgs.slice(-15).map(x => x.length < width ? x + " ".repeat(width - x.length) : x.substr(0, width)).join("\n"))//.slice(prev.length)
}
})
.catch(function (arguments) { console.log(arguments) });
}, 1000);
try {
return await promise;
} finally {
clearInterval(updatePoll);
}
}
function csvUpload(userInfo, datasetId, fileName, delimiter, quoteChar) {
const form = new FormData();
form.append('file', fs.createReadStream(fileName));
form.append("fileMimeTypeOverride", "text/csv");
form.append("delimiter", delimiter );
form.append("quoteChar", quoteChar);
console.log("Uploading CSV:");
const [userPart, dataSetPart] = datasetId.split("__");
const promise = fetch(timbuctoo_url + `/v5/${userPart}/${dataSetPart}/upload/table?forceCreation=true`, {
method: "POST",
body: form,
headers: {
Authorization: userInfo.authorization
}
})
.catch(function (e) {
console.log("Upload failed?", e);
});
// return promise;
return executeAndPoll(userInfo, datasetId, promise);
}
function getUserInfo(authorization) {
return graphql("{aboutMe{id}}", authorization)
.then(function (data) {
if (data.aboutMe == null) {
return null;
} else {
return data.aboutMe.id;
}
})
.catch(function (e) {
console.log("Error while fetching user info: ", e);
return null;
})
}
function logInUser() {
return new Promise(function (resolve, reject) {
let url = require('url');
var server = require('http').createServer(function (req, resp) {
const path = url.parse(req.url, true);
if (path.pathname === "/" || path.pathname === "" || path.pathname === null) {
resp.end(`
<body onload="document.forms[0].submit()">
Redirecting…
<form style="display:none" method="POST" action="https://secure.huygens.knaw.nl/saml2/login">
<input id="hsurl" name="hsurl" value="http://localhost:${port}/afterLogin">
</form>
</body>`)
} else if (path.pathname === "/afterLogin") {
var hsid = path.query.hsid;
getUserInfo(hsid).then(userId => resolve({authorization: hsid, userId: userId}));
resp.end('<body>You can close this window</body>');
console.log("closing")
server.close(() => "server closed");
} else {
resp.statusCode = 404;
resp.end("Unknown path");
}
});
var port;
server.listen(0, function () {
port = server.address().port;
opn("http://localhost:" + port);
});
});
}
function makeLines(str) {
if (!str) {
return [];
}
const lines = str.split("\n")
let i = lines.length;
while (lines[i - 1] === "") {
i--
}
return lines.slice(0, i)
}
var child_process = require("child_process");
function exec(command, ...args) {
if (DEBUG) {
console.log("CMD: " + command, args)
}
return new Promise(function executor(resolve, reject) {
const result = child_process.spawn(command, args.filter(x => x != null), {
shell: false,
env: {
"LANG": "C.UTF-8"
},
encoding: "utf-8"
});
let stderr = ""
let stdout = "";
result.stdout.on('data', (data) => {
stdout += data;
});
result.stderr.on('data', (data) => {
stderr += data;
});
result.on('close', (code) => {
const retVal = {
success: code == 0,
status: code,
stdout: makeLines(stdout),
stderr: makeLines(stderr)
}
if (DEBUG) {
console.log(" SUC: " + retVal.success)
console.log(" ST: " + retVal.status)
console.log(" OUT: " + JSON.stringify(retVal.stdout, undefined, " ").split("\n").map((x, i) => (i > 0 ? " " : "") + x).join("\n"))
console.log(" ERR: " + JSON.stringify(retVal.stderr, undefined, " ").split("\n").map((x, i) => (i > 0 ? " " : "") + x).join("\n"))
}
resolve(retVal);
});
});
}
function loop(objectOrArray, cb) {
if (Array.isArray(objectOrArray)) {
return objectOrArray.map(cb);
} else {
return [objectOrArray].map(cb);
}
}
async function loopAsync(objectOrArray, cb) {
if (Array.isArray(objectOrArray)) {
for (let i = 0; i < objectOrArray.length; i++) {
await cb(objectOrArray[i], i, objectOrArray);
}
} else {
await cb(objectOrArray, 0, [objectOrArray]);
}
}
function checkColumns(jsonLdDoc, rawCollections) {
let result = true;
const dym = require("didyoumean")
function checkColumn(collectionUri, columnName, customColumns) {
if (!rawCollections[collectionUri][columnName] && !customColumns[columnName]) {
const closeMatch = dym(columnName, Object.keys(rawCollections[collectionUri]));
console.log("Column", columnName, "does not exist." + (closeMatch != null ? " Did you mean " + JSON.stringify(closeMatch) + "?" : ""));
result = false;
}
}
function getTemplates(templ, cb) {
let i = 0;
while (i < templ.length) {
if (templ[i] === "\\") {
i++; //skip next token
} else if (templ[i] === "{" && templ[i+1] !== "}") {
let match = "";
i++
while (i < templ.length) {
if (templ[i] === "\\" && templ[i+1] === "}") {
match += "}";
i += 2;
} else if (templ[i] === "}") {
cb(match);
i++
break;
} else if (templ[i] === "\\") {
i++
match += templ[i];
i++
} else {
match += templ[i];
i++
}
}
}
i++
}
}
function checkSource(source, omap, customColumns) {
if (omap["rr:column"]) {
checkColumn(source, omap["rr:column"], customColumns);
} else if (omap["rr:template"]) {
getTemplates(omap["rr:template"], col => checkColumn(source, col, customColumns));
}
}
// [
// "http://jan/{}",
// "http://jan/{foo}",
// "http://jan/{fo\\}o}",
// "http://jan/{fo\\}o\\\\}",
// "http://jan/{fo\\}o\\\\\\}}",
// "http://jan/{fo\\}o\\\\\\\\}}",
// "http://jan/{foo}/{bar}",
// "http://jan/{foo}/{bar}?really=\\{as}",
// "http://jan/{foo}/{bar}?really=\\\\{as}",
// ].forEach(str => getTemplates(str, match => console.log(str, match)))
loop(jsonLdDoc["@graph"], mapping => {
const customColumns = {};
if (mapping["rml:logicalSource"]["rml:source"]["tim:customField"]) {
loop(mapping["rml:logicalSource"]["rml:source"]["tim:customField"], customField => customColumns[customField["tim:name"]] = true);
}
const source = mapping["rml:logicalSource"]["rml:source"]["tim:rawCollectionUri"]["@id"];
if (!rawCollections[source]) {
console.log("The sheet", JSON.stringify(source), " is not available!");
result = false;
return
}
checkSource(source, mapping["rr:subjectMap"], customColumns);
loop(mapping["rr:predicateObjectMap"], function (pomap) {
checkSource(source, pomap["rr:objectMap"], customColumns)
});
});
return result;
}
async function getCsvFiles(userInfo, datasetId) {
const availableTypes = await graphql(`{
dataSetMetadata(dataSetId: "${datasetId}") {
uri
}
__schema {
types {
name
}
}
}`, state.userInfo.authorization);
if (!availableTypes.__schema.types.some(x => x.name === `${datasetId}_http___timbuctoo_huygens_knaw_nl_static_v5_types_tabularCollection`)) {
return {
dataSetUri: availableTypes.dataSetMetadata != null ? availableTypes.dataSetMetadata.uri : undefined,
uploadedFiles: [],
uploadedFilePickList: [],
mostRecentlyUploadedFile: undefined
}
}
const info = (await graphqlDataSet(state.userInfo, datasetId, `
metadata {
uri
}
http___timbuctoo_huygens_knaw_nl_static_v5_types_tabularFileList {
items {
uri
rdfs_label { value }
prov_atTime { value }
tim_hasCollection {
... on ${datasetId}_http___timbuctoo_huygens_knaw_nl_static_v5_types_tabularCollection {
uri
rdfs_label { value }
tim_hasPropertyList {
items {
rdfs_label { value }
}
}
}
}
}
}`
));
const uploadedFiles = info.http___timbuctoo_huygens_knaw_nl_static_v5_types_tabularFileList.items;
const dataSetUri = info.metadata.uri;
const uploadedFilePickList = {};
for (const file of uploadedFiles) {
const label = file.rdfs_label.value + " ( " + file.prov_atTime.value + " )";
if (label in uploadedFilePickList) {
label = label + " - " + file.uri;
}
uploadedFilePickList[label] = file.uri;
file.label = label
}
uploadedFiles.sort((a,b) => a.prov_atTime.value < b.prov_atTime.value ? -1 : 1)
return {
dataSetUri,
uploadedFiles,
uploadedFilePickList,
mostRecentlyUploadedFile: uploadedFiles[0]
}
}
async function execute() {
console.log("Using timbuctoo server at", timbuctoo_url);
try {
const result = await graphql('{aboutMe{id}}', undefined);
if (!"aboutMe" in result) {
throw new Error("result is not what I expected");
}
} catch (e) {
console.log(e);
console.log(`Could not communicate to the timbuctoo server. Please verify whether ${timbuctoo_url}/v5/graphql?query=${encodeURIComponent("{aboutMe{id}}")}&accept=application/json works in your browser.`)
process.exit(1);
}
let userId = null;
if (state.userInfo && state.userInfo.authorization) {
userId = await getUserInfo(state.userInfo.authorization); //already logged in
}
if (userId === null) {
state.userInfo = await logInUser();
}
var inquirer = require('inquirer');
let PathPrompt = require('inquirer-path').PathPrompt;
inquirer.prompt.registerPrompt('path', PathPrompt);
state.input.dataSetId = (await inquirer.prompt([
{
name: "dataSetId",
message: "What dataSet are we working with?",
type: "input",
default: state.input.dataSetId != null ? state.input.dataSetId.split("__")[1] : undefined
},
])).dataSetId;
if (state.input.dataSetId.indexOf("__") < 0) {
state.input.dataSetId = "u" + state.userInfo.userId + "__" + state.input.dataSetId;
}
let {dataSetUri, mostRecentlyUploadedFile, uploadedFilePickList, uploadedFiles} = await getCsvFiles(state.userInfo, state.input.dataSetId);
let isFinished = false;
while (!isFinished) {
const action = (await inquirer.prompt([
{
name: "action",
message: "What do you want to do?",
type: "list",
choices: [
"Upload a new csv",
"run a mapping file",
"stop this program"
],
default: "run a mapping file",
},
])).action;
if (action === "run a mapping file") {
let prevPickedCsv = undefined;
state.mappingInput = await inquirer.prompt([
{
name: "mappingFile",
message: `where is the mapping file? (You can specify a jsonnet file, or generate a json file yourself. Use \n\njsonnet --ext-str dataseturi=${dataSetUri} <your-file>\n\n to manually run jsonnet)`,
type: "path",
default: state.mappingInput.mappingFile == null ? process.cwd() : pathLib.dirname(state.mappingInput.mappingFile),
},
]);
//if it's jsonnet then try to turn it into json
let jsonnetLocation;
try {
jsonnetLocation = child_process.execSync("which jsonnet", {encoding: "utf-8"}).split("\n")[0];
} catch (e) {
console.log("Jsonnet not found on this system");
}
const generatedFile = JSON.parse((await exec(jsonnetLocation, "--ext-str", `dataseturi=${dataSetUri}`, state.mappingInput.mappingFile)).stdout.join("\n"));
const rawCollections = {};
for (var file of uploadedFiles) {
const collection = file.tim_hasCollection;
const columns = {};
for (var prop of collection.tim_hasPropertyList.items) {
columns[prop.rdfs_label.value] = true;
}
rawCollections[collection.uri] = columns;
}
const jsonld = require("jsonld");
const framedFile = await jsonld.frame(generatedFile, {
"@context": {
"rml": "http://semweb.mmlab.be/ns/rml#",
"rr": "http://www.w3.org/ns/r2rml#",
"tim": "http://timbuctoo.huygens.knaw.nl/mapping#"
},
"@graph": {
"rml:logicalSource": {
},
"rr:predicateObjectMap": {
}
}
});
const pickedCsvFiles = {};
if (!state.csvFiles) {
state.csvFiles = {};
}
await loopAsync(framedFile["@graph"], async function (mapping) {
if (mapping["rml:logicalSource"] && mapping["rml:logicalSource"]["rml:source"] && mapping["rml:logicalSource"]["rml:source"]["tim:rawCollectionUri"]) {
if ("tim:csvFileId" in mapping["rml:logicalSource"]["rml:source"]["tim:rawCollectionUri"]) {
const csvFileId = mapping["rml:logicalSource"]["rml:source"]["tim:rawCollectionUri"]["tim:csvFileId"];
let uri;
if (pickedCsvFiles[csvFileId]) {
uri = pickedCsvFiles[csvFileId]
} else {
const prevUri = state.csvFiles[csvFileId];
const labelOfPrevUri = (uploadedFiles.find(x => x.uri === prevUri) || {label: undefined}).label
const answer = await inquirer.prompt([
{
name: "csvFile",
message: "What csv file should we use for " + csvFileId + "?",
type: "list",
choices: uploadedFiles.map(x => x.label),
default: labelOfPrevUri,
filter: choice => uploadedFilePickList[choice]
},
])
uri = answer.csvFile;
}
state.csvFiles[csvFileId] = uri;
pickedCsvFiles[csvFileId] = uri;
const sourceUri = mapping["rml:logicalSource"]["rml:source"]["tim:rawCollectionUri"];
sourceUri["@id"] = uri + "collections/" + sourceUri["tim:index"]
delete sourceUri["tim:csvFileId"];
delete sourceUri["tim:index"];
}
}
});
if (checkColumns(framedFile, rawCollections)) {
console.log("Executing mapping file...")
const [userPart, dataSetPart] = state.input.dataSetId.split("__");
const promise = fetch(timbuctoo_url + `/v5/${userPart}/${dataSetPart}/rml`, {
method: "POST",
body: JSON.stringify(framedFile, undefined, 2),
headers: {
Authorization: state.userInfo.authorization
}
})
.then(function (r) {
if (r.status > 299) {
console.log("Upload failed")
}
})
.catch(function (e) {
console.log("Upload failed?", e);
});
await executeAndPoll(state.userInfo, state.input.dataSetId, promise);
}
} else if (action === "Upload a new csv") {
const csvUploadData = await inquirer.prompt([
{
name: "csvFile",
message: "What csv file should we upload",
type: "path",
default: state.input.csvFile == null ? process.cwd() : pathLib.dirname(state.input.csvFile),
},
{
name: "delimiter",
message: "What is the character used to separate fields?",
type: "input",
default: state.input.delimiter == null ? ';' : state.input.delimiter,
},
{
name: "quoteChar",
message: "What character is used for quoting fields (if any is used)",
type: "input",
default: state.input.quoteChar == null ? '"' : state.input.quoteChar,
},
]);
state.input.delimiter = csvUploadData.delimiter;
state.input.quoteChar = csvUploadData.quoteChar;
state.input.csvFile = csvUploadData.csvFile;
await csvUpload(state.userInfo, state.input.dataSetId, state.input.csvFile, state.input.delimiter, state.input.quoteChar);
({dataSetUri, mostRecentlyUploadedFile, uploadedFilePickList, uploadedFiles} = await getCsvFiles(state.userInfo, state.input.dataSetId));
} else if (action === "stop this program") {
isFinished = true;
} else {
throw new Error("Unknown action " + action);
}
}
}
execute()
.catch(x => console.log(x))
.then(function () {
fs.writeFileSync(__dirname + "/state.json", JSON.stringify(state), "utf-8")
})
<file_sep>/README.adoc
== Timbuctoo mappings
This repository contains RML mappings to convert tabular data into rdf.
A mapping defines which properties to convert, what predicates they should map to, and how to turn foreign keys into URI's.
The mappings are usually written using http://jsonnet.org/docs/tutorial.html[jsonnet]. Please read the link:./mapping-generator[mapping generator guide] to learn more.
This repo also contains a node.js script that wraps the timbuctoo API calls and makes it easy to upload data and apply the mappings.
To execute the script, you need
- a node.js that's at least 8.4.0
- the `jsonnet` executable somewhere on your $PATH
You can launch the script using
```
timbuctooUrl=http://data.anansi.clariah.nl node ./execute.js
```
You should of course replace the timbuctoo url with whatever you're using.
<file_sep>/mapping-generator/README.adoc
== The problem
We write mapping files by hand for now. These files are RDF files that follow the RML.io spec and that we write as JSON-LD.
- These mapping files get big because rml in json-ld is quite verbose.
- These mapping files refer often to a prefix that changes each time you re-upload the file. Or a predicate that we need to keep consistent accross mapping files.
- These mapping files might contain errors that you only notice because a property is missing or empty in the final result. This is hard and time-consuming to check.
== Expected result
We have an automated script that we feed a less verbose mapping file with less duplication. The script then validates that mapping file (ideally also against the uploaded file) and generates the actual json ld file.
== The approach
- We have achieved good results by using http://jsonnet.org[jsonnet] to generate kubernetes json files. Kubernetes json files suffer from a lot of the same problems (verbosity and variables that are used all over the place).
So to start we'll write a jsonnet file that allows you to write a mapping file in a more succinct manner. This will also make sure that the json-ld is valid (jsonnet functions impose a more strict api then json)
- We can then add a js script that uses the graphql api to validate that all columns that are referred to actually exist
- We can then add a feature that reports back all properties used in a sorted list to quickly lift out typo's.
- we can then also replace all known prefixes so custom predicates stand out more.
=== A note on the examples
In the examples below I will use a very simple uploaded file that contains two collections. Persons and places.
Places looks like this:
[options="header"]
|=======
| id | name | country
| 1 | Amsterdam | The Netherlands
| 2 | Paris | France
|=======
Persons looks like this:
[options="header"]
|=======
| id | firstName | lastname | birthplace
| 1 | Jean | Martin | 2
| 2 | Jan | Jansen | 1
|=======
The number in birthplace refers to the id of the row in place. So <NAME> was born in Paris.
=== mappings
You start by importing the file rml.libsonnet
```jsonnet
local rml = import "./rml.libsonnet";
```
You then call the `mappings` function with an array of `mapping`s
```
rml.mappings([
rml.mapping(...),
rml.mapping(...)
])
```
Each mapping call gets
- the name of the mapping (used for joins)
- the name of the file that you are reading the data from. This file name changes each upload so I suggest acquiring it through `std.extVar` (see example below)
- the number of the collection that it refers to
- a `source` (explained later on) for generating the subject uri
- a `source` for generating the class uri
- a hashmap of predicate uri's and the Fields to generate the properties.
```
rml.mapping("name_of_the_mapping", "filename", 9,
rml.templateSource("http://example.org/things/{ID}"),
rml.constantSource("http://example.org/types/thing),
{
"http://schema.org/name": rml.dataField(rml.types.string, rml.columnSource("label")),
}
),
```
This mapping will then create the config that generates an object whose uri is `http://example.org/things/{ID}`, whose type is `http://example.org/types/thing` and that has a schema:name with the value of the column "label"
If you want to generate the same predicate multiple times (e.g. a thing has multiple schema:name's) then you can specify an array of fields:
```
rml.mapping("name_of_the_mapping", "filename", 9,
rml.templateSource("http://example.org/things/{ID}"),
rml.constantSource("http://example.org/types/thing),
{
"http://schema.org/name": [
rml.dataField(rml.types.string, rml.columnSource("label")),
rml.dataField(rml.types.string, rml.columnSource("alternate_label")),
],
}
),
```
=== sources
In the mapping you can define how to extract data from the uploaded file using sources. A source can be one of four types:
templateSource::
allows you to specify a string that contains column names in in curly braces like `templateSource("Dear {firstName} {lastname},")`
columnSource::
that contains the name of a column: `columnSource("country")`
constantSource::
that contains the string to use in the rdf: `constantSource("male")`
jexlSource::
contains http://commons.apache.org/proper/commons-jexl/reference/syntax.html[jexl] code that has a variable called `v` that contains the columns. E.g. `jexlSource('v.firstName != null ? "Dear " + v.firstName : "Mr. " + v.lastname + ","')`
=== fields
A source is needed for generating the subject and the class value, but all properties require not just a value but also a description of what the value is. Therefore each source is wrapped in a field. The following fields are available:
iriField::
the source should result in some IRI e.g. `rml.iriField(rml.constantSource("http://example.org/foo"))`
dataField::
the source results in some string according the the datatype that is provided as the first argument. e.g. `rml.dataField(rml.types.edtf, rml.constantSource("2018-01-??"))`
joinField::
see joins below
=== joins
To link two entities together, you simple generate an iri that is the same as the subject IRI of the other table. So given our example above we could have the following mapping
```
local rml = import "./rml.libsonnet";
rml.mappings([
rml.mapping("PersonsMapping", "{{filename}}", 1,
rml.templateSource(rml.datasetUri + "collection/Persons/{id}"),
rml.constantSource(rml.datasetUri + "collection/Persons"),
{
"http://schema.org/givenName": rml.columnSource("firstName"),
"http://schema.org/familyName": rml.columnSource("lastname"),
"http://schema.org/birthPlace": rml.iriField(rml.templateSource(rml.datasetUri + "collection/Places/{birthplace}")),
},
),
rml.mapping("PlacesMapping", "{{filename}}", 2,
rml.templateSource(rml.datasetUri + "collection/Places/{id}"),
rml.constantSource(rml.datasetUri + "collection/Places"),
{
"http://schema.org/name": rml.columnSource("name")
},
)
])
```
But this only works if the IRI that we generate for the place happens to contain only the identifiers that we also have at our disposal in the persons collection!
What if we want to generate IRIs for the places that contain the placename? (assuming this results in unique IRI's per row) `rml.templateSource(rml.datasetUri + "collection/Places/{country}/{name}");`
For this usecase the mapping allows you to refer to the subject IRI's as generated by a different mapping using the joinField. The complete mapping would then be:
```
local rml = import "./rml.libsonnet";
rml.mappings([
rml.mapping("PersonsMapping", "{{filename}}", 1,
rml.templateSource(rml.datasetUri + "collection/Persons/{id}"),
rml.constantSource(rml.datasetUri + "collection/Persons"),
{
"http://schema.org/givenName": rml.columnSource("firstName"),
"http://schema.org/familyName": rml.columnSource("lastname"),
"http://schema.org/birthPlace": rml.joinField(
"birthplace", //the column in this collection that contains the value to match on (must be 1 column)
"PlacesMapping", //the name of the mapping whose subject IRI's we're going to use
"id" //the name of the column in the collection that's behind 'PlacesMapping' whose value we should match against
),
},
),
rml.mapping("PlacesMapping", "{{filename}}", 2,
rml.templateSource(rml.datasetUri + "collection/Places/{country}/{name}"),
rml.constantSource(rml.datasetUri + "collection/Places"),
{
"http://schema.org/name": rml.columnSource("name")
},
)
])
```
<file_sep>/soundtoll/convert_table.rb
def header
output =<<EOT
local rml = import "../mapping-generator/rml.libsonnet";
rml.mappings([
EOT
output
end
def footer
"])"
end
def table_header mapping_name,file_name,collection,table_names,number
table_name = table_names.first
output =<<EOT
rml.mapping(
"#{mapping_name}",
"#{file_name}",
#{number},
rml.templateSource(rml.datasetUri + "collection/#{collection}/{persistant_id}"),
rml.constantSource(rml.datasetUri + "collection/#{collection}"),
{
EOT
output
end
def table_content column_names
column_name = column_names.first
output =<<EOT
"http://schema.org/#{column_name}": rml.dataField(rml.types.string, rml.columnSource("#{column_name}")) ,
EOT
output
end
def table_footer
" }),"
end
def handle_columns table_names,columns,tim_id,collection
table_name = table_names.first
res = ""
table_name.split('_').each do |match|
res += match.capitalize
end
mapping_name = "#{res}Mapping"
STDERR.puts res
file_name = "#{table_name}.csv"
puts table_header(mapping_name,file_name,collection,table_names,tim_id)
columns.each_with_index do |column_names,index|
puts table_content(column_names)
end
puts table_footer
end
if __FILE__ == $0
collection = "soundtoll"
file_in = "tabellen.txt"
(0..(ARGV.size-1)).each do |i|
case ARGV[i]
# voeg start en stop tags toe
when '-i' then file_in = ARGV[i+1]
when '-c' then collection = ARGV[i+1]
when '-h' then
begin
STDERR.puts "use: ruby conver_table -i inputfile -c collection"
exit(0)
end
end
end
puts header
table = Array.new
columns = Array.new
tim_id = 1
File.open(file_in) do |file|
begin
while line = file.gets
line.strip!
if !line.empty?
if line.match(/^-/)
columns << line[2..-1].split
else
if !columns.empty?
handle_columns table,columns,tim_id,collection
tim_id += 1
end
table = line.split(' ')
columns = Array.new
end
end
end
rescue => all
STDERR.puts all
end
end
handle_columns table,columns,tim_id,collection if !columns.empty?
puts footer
end
| 8ee1c3a7b62acbd6a14073183ee2a6c9ed7379b9 | [
"JavaScript",
"Ruby",
"AsciiDoc"
] | 4 | JavaScript | HuygensING/timbuctoo-mappings | a0ba4a30f5bd0301c54cba9da5606ad4a5c2c280 | ce35d8c8c8e4048b75cd9cc495d33c88e8c26d3a |
refs/heads/master | <file_sep>/home/blue/github/lightweight-django/node_modules/jquery/dist/jquery.js<file_sep>CMD
===
``` python
python manage migrate
python manage
```
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2017-07-17 15:43
# @Author : Bluethon (<EMAIL>)
# @Link : http://github.com/bluethon
import os
import shutil
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse
from django.test.client import Client
def get_pages():
# 调用一次返回一个文件名
for name in os.listdir(settings.SITE_PAGES_DIRECTORY):
if name.endswith('.html'):
yield name[:-5]
class Command(BaseCommand):
help = 'Build static site output.'
# 设置中的区域设置在执行命令时报错, False时会强制设置为'en-US'
leave_locale_alone = True
# < 1.8, 管理命令基于`optparse`, 位置参数传给`*args`, 可选给`**options`
# >= 1.8, 基于`argparse`, 默认参数都给`**options`
# 命名位置参数为`args`(兼容模式), 不推荐
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
def handle(self, *args, **options):
""" Request pages and build output. """
# python prototypes.py build # build == file name
# python prototypes.py build index # compile a single page
# cd _build
# python -m http.server 9000 # run simple python server
settings.DEBUG = False
settings.COMPRESS_ENABLED = True
# 参数存在, 可为多个
if args:
pages = args
available = list(get_pages())
invalid = []
for page in pages:
if page not in available:
invalid.append(page)
if invalid:
msg = 'Invalid pages: {}'.format(', '.join(invalid))
# 如果没有任何名字存在, 报错
raise CommandError(msg)
else:
pages = get_pages()
# 如果存在文件夹, 删除
if os.path.exists(settings.SITE_OUTPUT_DIRECTORY):
shutil.rmtree(settings.SITE_OUTPUT_DIRECTORY)
os.mkdir(settings.SITE_OUTPUT_DIRECTORY)
os.makedirs(settings.STATIC_ROOT)
# 调用`collectstatic`命令收集static文件
call_command('collectstatic', interactive=False, clear=True, verbosity=0)
call_command('compress', interactive=False, force=True) # 压缩静态文件
client = Client()
# 遍历pages, 收集所有html
for page in pages:
url = reverse('page', kwargs={'slug': page})
# 利用Django的test client, 模拟爬取网页
response = client.get(url)
if page == 'index':
output_dir = settings.SITE_OUTPUT_DIRECTORY
else:
output_dir = os.path.join(settings.SITE_OUTPUT_DIRECTORY, page)
# 文件夹不存在再创建
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(os.path.join(output_dir, 'index.html'), 'wb') as f:
# 写入已经渲染好的静态网页
f.write(response.content)
<file_sep># lightweight-django
For learn <<Lightweight Django>>
> <https://github.com/lightweightdjango/examples>
<file_sep>#!/usr/bin/env python3
# encoding: utf-8
# @Date : 2017-07-24 00:00
# @Author : Bluethon (<EMAIL>)
# @Link : http://github.com/bluethon
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'sprints', views.SprintViewSet)
router.register(r'tasks', views.TaskViewSet)
router.register(r'users', views.UserViewSet)
<file_sep>#!/usr/bin/env python3
# encoding: utf-8
# @Date : 2017-07-26 22:50
# @Author : Bluethon (<EMAIL>)
# @Link : http://github.com/bluethon
import django_filters
from django.contrib.auth import get_user_model
from .models import Task, Sprint
User = get_user_model()
class NullFilter(django_filters.BooleanFilter):
""" Filter on a field set as null or not. """
def filter(self, qs, value):
# qs = query_set
if value:
# 使用Django的filter字段特性
return qs.filter(**{f'{self.name}__isnull': value})
return qs
class TaskFilter(django_filters.FilterSet):
backlog = NullFilter(name='sprint')
class Meta:
model = Task
fields = ('sprint', 'status', 'assigned',) # 不加也自带
# fields = ('sprint', 'status', 'assigned', 'backlog', )
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# 已不需要, 自动转换了(!!! 错误, 自动转换
# Update the assigned filter to use the User.USERNAME_FIELD
# as the field reference rather than the default pk
self.filters['assigned'].extra.update(
{'to_field_name': User.USERNAME_FIELD})
class SprintFilter(django_filters.FilterSet):
end_min = django_filters.DateFilter(name='end', lookup_expr='gte') # greater than or equal to
end_max = django_filters.DateFilter(name='end', lookup_expr='lte')
class Meta:
model = Sprint
fields = ('end_min', 'end_max',)
<file_sep>/home/blue/github/lightweight-django/node_modules/backbone/backbone.js<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2017-07-16 15:28
# @Author : Bluethon (<EMAIL>)
# @Link : http://github.com/bluethon
import os
import sys
from django.conf import settings
BASE_DIR = os.path.dirname(__file__)
settings.configure(
DEBUG=True,
SECRET_KEY='9adr8to-se-pw',
ROOT_URLCONF='sitebuilder.urls',
MIDDLEWARE_CLASSES=(),
INSTALLED_APPS=(
'django.contrib.staticfiles',
# 'django.contrib.webdesign', # deprecated in 1.8, {% lorem %} built in
'sitebuilder',
'compressor', # static file compress
),
TEMPLATES=(
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
),
STATIC_URL='/static/',
SITE_PAGES_DIRECTORY=os.path.join(BASE_DIR, 'pages'),
SITE_OUTPUT_DIRECTORY=os.path.join(BASE_DIR, '_build'),
STATIC_ROOT=os.path.join(BASE_DIR, '_build', 'static'),
# # 文件获得唯一hash(DEBUG=False生效)
# STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
# settings for django-compressor
STATICFILES_FINDERS=(
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
)
if __name__ == '__main__':
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2017-07-16 15:30
# @Author : Bluethon (<EMAIL>)
# @Link : http://github.com/bluethon
from django.conf.urls import url
from .views import page
urlpatterns = (
url(r'^(?P<slug>[\w./-]+)/$', page, name='page'),
url(r'^$', page, name='homepage'),
)
| 65fefabdde6fedf5923af023a4dbf3ffab3de445 | [
"JavaScript",
"Python",
"Markdown"
] | 9 | JavaScript | bluethon/lightweight-django | f6b5ec3b8f3ec901d949343e8712083b4e68c18b | fa203676bcf53d34ee4bee2efc7f2e4322fe941d |
refs/heads/master | <repo_name>trevorharm/recipeapp<file_sep>/README.md
# recipeapp
UNCC Coding Bootcamp Team Project 1
<file_sep>/assets/javascript/logic-firebase.js
// Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "recipe-app-e904e.firebaseapp.com",
databaseURL: "https://recipe-app-e904e.firebaseio.com",
projectId: "recipe-app-e904e",
storageBucket: "",
messagingSenderId: "319710210801"
};
firebase.initializeApp(config);
var database = firebase.database();
var email = "";
var convertedEmail = "";
var ingredients = [];
var recipes = ["How to", "2", "3", "4"];
var videos = ["Vid"];
var newObj;
$("#signUpSubmit").on("click", function(event) {
event.preventDefault();
email = $("#signUpEmail").val().trim();
// console.log(email);
convertedEmail = email.replace(".", ",");
// console.log(convertedEmail);
database.ref("/users").once("value", function(snapshot) {
if (snapshot.child(convertedEmail).exists()) {
alert("That username is taken!");
var stringJSON = JSON.stringify(snapshot.child(convertedEmail));
var parseJSON = JSON.parse(stringJSON);
var newObj = parseJSON;
console.log(newObj);
// console.log(newObj.ingredients);
// console.log(newObj.recipes);
// console.log(newObj.videos);
} else {
alert("There are no users with that email!");
}
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
$("#logInSubmit").on("click", function(event) {
event.preventDefault();
email = $("#inputEmail").val().trim();
// console.log(email);
convertedEmail = email.replace(".", ",");
// console.log(convertedEmail);
database.ref("/users").once("value", function(snapshot) {
if (snapshot.child(convertedEmail).exists()) {
var stringJSON = JSON.stringify(snapshot.child(convertedEmail));
var parseJSON = JSON.parse(stringJSON);
newObj = parseJSON;
console.log(newObj);
var text = " ";
var x;
var recipeArray = newObj.recipes;
var ingredientArray = newObj.ingredients;
var videoArray = newObj.videos;
for (x in recipeArray) {
text += recipeArray[x] + " ";
$("#favorites-display").html("<div>" + text + "</div>");
}
for (x in ingredientArray) {
text += ingredientArray[x] + " ";
$("#favorites-display").html("<div>" + text + "</div>");
}
for (x in videoArray) {
text += videoArray[x] + " ";
$("#favorites-display").html("<div>" + text + "</div>");
}
} else {
alert("There are no users with that email!");
}
}, function(errorObject) {
console.log("The read failed: " + errorObject);
});
});
$("#submitBtn").on("click", function(event) {
event.preventDefault();
var newIngredient = $("#ingredient").val().trim();
ingredients.push(newIngredient);
database.ref("users/" + convertedEmail).set({
ingredients: ingredients,
recipes: recipes,
videos: videos
});
database.ref("/users").once("value", function(snapshot) {
var stringJSON = JSON.stringify(snapshot.child(convertedEmail));
var parseJSON = JSON.parse(stringJSON);
newObj = parseJSON;
console.log(newObj);
// console.log(newObj.ingredients);
// console.log(newObj.recipes);
// console.log(newObj.videos);
})
});
// $("#favoriteBtn").on("click", function(event) {
// event.preventDefault();
// newUser.recipe = results.hits[?]
// database.ref('users').push(newUser);
// });
// database.ref().on("child_added", function(childSnapshot) {
// console.log(childSnapshot.val().newUser);
// }, function(errorObject) {
// console.log("Errors handled: " + errorObject.code);
// });<file_sep>/assets/javascript/trevorFirebase.js
// Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "recipe-app-e904e.firebaseapp.com",
databaseURL: "https://recipe-app-e904e.firebaseio.com",
projectId: "recipe-app-e904e",
storageBucket: "",
messagingSenderId: "319710210801"
};
firebase.initializeApp(config);
var database = firebase.database();
var email = "";
var convertedEmail = "";
var ingredients = [];
var recipes = [];
var videos = [];
var urls = [];
var newObj;
$("#signUpSubmit").on("click", function (event) {
event.preventDefault();
email = $("#signUpEmail").val().trim();
convertedEmail = email.replace(".", ",");
database.ref("/users").once("value", function (snapshot) {
if (snapshot.child(convertedEmail).exists()) {
var stringJSON = JSON.stringify(snapshot.child(convertedEmail));
var parseJSON = JSON.parse(stringJSON);
var newObj = parseJSON;
// console.log(newObj);
swal("That Email Address Is In Use. Please Use Login Option If Returning To Site.");
} else {
$("#mainScreen").slideDown();
$("#searchRow").slideDown();
$("#startBox").hide();
$("#signUpModal").hide();
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
$("#logInSubmit").on("click", function (event) {
event.preventDefault();
email = $("#inputEmail").val().trim();
convertedEmail = email.replace(".", ",");
database.ref("/users").once("value", function (snapshot) {
if (snapshot.child(convertedEmail).exists()) {
var stringJSON = JSON.stringify(snapshot.child(convertedEmail));
var parseJSON = JSON.parse(stringJSON);
newObj = parseJSON;
// console.log(newObj);
var recipeText = " ";
var ingredientText = " ";
var videoText = " ";
var urlText = " ";
var x;
var recipeArray = newObj.recipes;
var ingredientArray = newObj.ingredients;
var videoArray = newObj.videos;
var urlArray = newObj.urls;
for (x in recipeArray) {
recipeText = recipeArray[x] + " ";
recipes.push(recipeArray[x]);
};
for (x in ingredientArray) {
ingredientText = ingredientArray[x] + " ";
ingredients.push(ingredientArray[x]);
};
for (x in urlArray) {
urlText = urlArray[x] + " ";
urls.push(urlArray[x]);
};
$("#mainScreen").slideDown();
$("#searchRow").slideDown();
$("#favorites").slideDown();
$("#videoRow").slideDown();
$("#startBox").hide();
$("#logInModal").hide();
$("#favorites-display").val(" ");
for (i = 0; i < recipes.length; i++) {
var link = urls[i];
var text = recipes[i];
var node = $("<div>");
var favNode = $("<a>");
favNode.append(text);
$(favNode).attr("href", link);
favNode.attr("target", "_blank");
favNode.addClass("favLink");
favNode.css("font-size", "150%");
$(node).append(favNode);
$("#favorites-display").prepend(node);
};
} else {
swal("That Account Does Not Exist. Please Check The Spelling, Or Sign Up If This Is Your First Time!")
$("#logInModal").hide();
$("#startBox").show();
}
}, function (errorObject) {
console.log("The read failed: " + errorObject);
});
});
$("#submitBtn").on("click", function (event) {
event.preventDefault();
var newIngredient = $("#ingredient").val().trim();
ingredients.push(newIngredient);
database.ref("users/" + convertedEmail).set({
ingredients: ingredients,
recipes: recipes,
urls: urls,
videos: videos
});
database.ref("/users").once("value", function (snapshot) {
var stringJSON = JSON.stringify(snapshot.child(convertedEmail));
var parseJSON = JSON.parse(stringJSON);
newObj = parseJSON;
// console.log(newObj);
});
});<file_sep>/assets/javascript/logic.js
//VARIABLES==================================================================================
var substring1 = "@";
var substring2 = ".com";
var substring3 = ".net";
var ingredient = $('#ingredient');
var input = $("#inputEmail");
var signUp = $("#signUpEmail");
//FUNCTIONS==================================================================================
function valid() {
var string = $("#inputEmail").val();
if(string === "") {
$("#logInSubmit").prop("disabled", true);
}
//runs valid function to check input for "@" and ".com" strings before enabling button
if(string.indexOf(substring1) !== -1 && (string.indexOf(substring2) !== -1 || string.indexOf(substring3) !== -1) ) {
$("#logInSubmit").prop("disabled", false);
}else{
$("#logInSubmit").prop("disabled", true);
}
}
function valid2() {
var string2 = $("#signUpEmail").val();
if(string2 === "") {
$("#signUpSubmit").prop("disabled", true);
}
if(string2.indexOf(substring1) !== -1 && (string2.indexOf(substring2) !== -1 || string.indexOf(substring3) !== -1) ) {
$("#signUpSubmit").prop("disabled", false);
}else{
$("#signUpSubmit").prop("disabled", true);
;
}
}
function reset() {
$("#displayRow").hide();
$("#video-display").empty();
$("#video-display").css("height", "100px");
$("#logInModal").hide();
$("#signUpModal").hide();
$("mainScreen").show();
$("#searchRow").show();
}
function slideTime() {
setTimeout(function(){ $("#logInModal").slideDown(); }, 500);
}
function signUpSlide() {
setTimeout(function(){ $("#signUpModal").slideDown(); }, 500);
}
function slideTime2() {
setTimeout(function(){ $("#startBox").slideDown(); }, 500);
}
//MAIN PROCESSES/ ON PAGE LOAD==========================================================
$(document).ready(function() {
//var email;
$("#searchForm").submit(function(e){
e.preventDefault();
});
// $("button").on("click", ".favorite", function(e){
// console.log("button");
// var favLink = $("<button>");
// var favText = e.target.closest("a").text();
// favLink.addClass("btn btn-Default");
// favLink.text(favText);
// $("#favorites-display").append(favLink);
// //find nearest sibling <a>
// });
//log in click event
$("#logInBtn").on("click", function() {
$("#startBox").slideUp();
slideTime();
valid();
});
$("#signUpBtn").on("click", function() {
$("#startBox").slideUp();
signUpSlide();
valid2();
});
//validates text on change and keyup
input.on("change", valid);
input.on("keyup", valid);
signUp.on("change", valid2);
signUp.on("keyup", valid2);
$(".close1").on("click", function() {
$("#logInModal").slideUp();
slideTime2();
});
$(".close2").on("click", function() {
$("#signUpModal").slideUp();
slideTime2();
});
//logging in================================================
// $("#logInSubmit").on("click", function(e) {
// e.preventDefault();
// let email = $("#inputEmail").val().trim();
// console.log("Welcome, " + email + "!");
// $("#mainScreen").slideDown();
// $("#searchRow").slideDown();
// $("#favorites").slideDown();
// //$("#videoRow").slideDown();
// //$("#displayRow").slideDown();
// //$("#videoRow").hide();
// //$("#displayRow").hide();
// $("#startBox").hide();
// $("#logInModal").hide();
// });
// // sign up submission click event <=================================
// $("#signUpSubmit").on("click", function(e) {
// e.preventDefault();
// let email = $("#signUpEmail").val().trim();
// console.log("Welcome, " + email + "!");
// $("#mainScreen").slideDown();
// $("#searchRow").slideDown();
// //$("#videoRow").slideDown();
// //$("#displayRow").slideDown();
// $("#startBox").hide();
// $("#signUpModal").hide();
// });
//LOGGED IN, SEARCH ======================================
$('#submitBtn').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
$("#videoRow").show();
$("#displayRow").show();
//$("#searchRow").hide();
//ajax call
console.log(ingredient.val());
//empties current display
$('#recipe-display').empty();
//div to fill with info from results
var wellDiv = $('<div>');
wellDiv.attr('id', 'favHead');
wellDiv.html("<h2>" + ingredient.val() + " recipes:</h2>");
//append div to display
$('#recipe-display').append(wellDiv);
//append recipe image
$("#reset").on("click", reset);
});
// $(".favorite").on("click", function(e){
// console.log(e.target);
// var favLink = $("<button>");
// var favText = e.target.closest("a").text();
// favLink.addClass("btn btn-Default");
// favLink.text(favText);
// $("#favorites-display").append(favLink);
});
<file_sep>/assets/javascript/logic-ajax.js
// api url
$("#submitBtn").on("click", runSearch);
function runSearch(){
event.preventDefault();
var nut = "";
$('input[class="filter"]:checked').each(function(item) {
var box = $(this);
var f = box.data("f");
var n = box.data("n");
nut += "&"+ f + "=" + n;
});
console.log(nut);
var search = $("#ingredient").val();
getVideo(search);
var api = "https://api.edamam.com/search?q=";
var key = "&app_id=165d9a3a&app_key=13ed1985dcd9cb0a99bedc7ce4a3ef80";
var urlSearch = api + search + key + nut;
console.log(urlSearch);
$.ajax({url: urlSearch, success: function(response){
console.log(response);
var results = response.hits;
var x = results.length;
if (x > 0){
for (var i = 0; i < 9; i++){
var element = results[i];
var dataFood = element.recipe;
var title = dataFood.label;
var img = dataFood.image;
var txt = dataFood.healthLabels;
var link = dataFood.url;
console.log(link);
var column = $("<div>");
column.addClass("col-xs-4");
var textnode = $("<a>");
//favorite button
var favBtn = $("<button>");
favBtn.addClass("btn btn-primary favorite");
favBtn.attr("id", "button-" + i);
favBtn.attr("data-num", i);
favBtn.html("<span class='glyphicon glyphicon-star'></span>");
$(textnode).append(title);
textnode.addClass("entry");
textnode.css('background-image', 'url(' + img + ')');
textnode.attr("href", link);
textnode.attr("target", "_blank");
$(column).append(textnode);
$(column).append(favBtn);
$("#recipe-display").append(column);
txt.forEach(element => {
var contains = $("<p>");
$(contains).addClass("desc");
$(contains).append(element + " " + "<br>");
//$("#recipe-display").append(contains);
});
}
$(".favorite").on("click", function (event) {
event.preventDefault();
database.ref("/users").once("value", function (snapshot) {
if (snapshot.child(convertedEmail).exists()) {
var stringJSON = JSON.stringify(snapshot.child(convertedEmail));
var parseJSON = JSON.parse(stringJSON);
var newObj = parseJSON;
console.log(newObj);
var recipeText = " ";
var ingredientText = " ";
var videoText = " ";
var urlText;
var x;
var recipeArray = newObj.recipes;
var ingredientArray = newObj.ingredients;
var videoArray = newObj.videos;
var urlArray = newObj.urls;
recipes = [];
ingredients = [];
videos = [];
urls = [];
for (x in recipeArray) {
recipeText = recipeArray[x] + " ";
recipes.push(recipeArray[x]);
};
for (x in ingredientArray) {
ingredientText = ingredientArray[x] + " ";
ingredients.push(ingredientArray[x]);
};
for (x in urlArray) {
urlText = urlArray[x] + " ";
urls.push(urlArray[x]);
};
swal("Recipe Added to Favorites!");
}
}, function(errorObject) {
console.log("The read failed: " + errorObject);
});
var y = $(this).data("num");
var iLabel = results[y].recipe.label;
var iUrl = results[y].recipe.url;
recipes.push(iLabel);
urls.push(iUrl);
var faves = $("<div>");
var favNode = $("<a>");
favNode.append(iLabel);
$(favNode).attr("href", iUrl);
favNode.attr("target", "_blank");
favNode.css("font-size", "150%");
favNode.addClass("favLink");
faves.append(favNode);
$("#favorites-display").prepend(faves);
database.ref("users/" + convertedEmail).set({
ingredients: ingredients,
recipes: recipes,
urls: urls,
videos: videos
});
});
}
else {
swal("No recipes found for " + search +"!");
}
}});
function getVideo(term){
var api2="https://api.vimeo.com/videos?query=";
var search2= term + "%20recipe";
var key2 = "&access_token=<KEY>";
var vidSearch = api2 + search2 + key2;
$.ajax({url: vidSearch, success: function(response){
console.log(response);
for (var i =0; i< 9; i++)
{
var y = response.data.length;
// console.log(y);
//var x = Math.floor(Math.random(0, y));
var x = Math.floor(Math.random() * Math.floor(y));
// console.log(x);
var recipex = response.data[x];
var name = recipex.name;
console.log(name);
var vid = recipex.embed.html;
var vidBox = $("<div class='container video'>");
vidBox.html(vid);
$("#video-display").empty();
$("#video-display").css("height", "400px");
$("#video-display").append(vidBox);
}
}});
}
}
//https://api.edamam.com/search?q=chicken&app_id=165d9a3a&app_key=13ed1985dcd9cb0a99bedc7ce4a3ef80&from=0&to=3&calories=gte%20591,%20lte%20722&health=alcohol-free
| ea5b8da52738aaf37cafcdc5e23b9369c3c97b7c | [
"Markdown",
"JavaScript"
] | 5 | Markdown | trevorharm/recipeapp | 8df6683df32e85b47718066a39061ecc478b0f24 | 9ef6bc01b5a4c1b2fd4dc25521192f241ce4d1e7 |
refs/heads/master | <repo_name>abdullahallnaim/qikdaw-client<file_sep>/src/Components/AllLogin/LoginWithFacebook/LoginWithFacebook.js
import React, { useEffect, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import firebase from 'firebase/app'
import "firebase/auth";
import "firebase/firestore";
import firebaseconfig from '../firebaseconfig'
import facebook from '../../../fb.png';
import axios from 'axios';
import { useHistory, useLocation } from 'react-router';
if (!firebase.apps.length) {
firebase.initializeApp(firebaseconfig);
}
const LoginWithFacebook = () => {
const location = useLocation()
const history = useHistory()
const { from } = location.state || { from: { pathname: `/home` } };
const [user, setUser] = useState([])
useEffect(() => {
fetch('http://qikdaw.com:5000/data')
.then(res => res.json())
.then(data => {
setUser(data)
})
}, [])
const facebookLogin = () => {
const providerFb = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(providerFb).then(function (result) {
let randomToken;
randomToken = uuidv4()
var token = result.credential.accessToken;
const { displayName, photoURL, email, b } = result.user;
const signedInWithFb = { name: displayName, email: email, photoURL: photoURL, id: randomToken, type: 'gf' }
user.map(x => {
if (x.email == signedInWithFb.email || x.name == signedInWithFb.name) {
history.replace(from)
localStorage.setItem('loggedIn', x.id)
} else {
axios.post('http://qikdaw.com:5000/users', signedInWithFb)
.then(response => {
if (response) {
history.replace(from)
localStorage.setItem('loggedIn', signedInWithFb.id)
}
})
}
})
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
});
}
return (
<div className='my-3 col-12 col-sm-8 col-lg-8 mx-auto'>
<button className='d-flex flex-wrap col-12' style={{ border: '2px solid #A0A1A1', borderRadius: '30px', backgroundColor: 'white' }} onClick={facebookLogin}>
<div className='col-2'>
<img style={{ width: '30px', height: '30px' }} className='mt-2' src={facebook} alt="" />
</div>
<p className='pt-2' style={{ color: '#ABABAB' }}>Login with Facebook</p>
</button>
</div>
);
};
export default LoginWithFacebook;<file_sep>/src/Components/AllLogin/firebaseconfig.js
const firebaseconfig = {
apiKey: "<KEY>",
authDomain: "book-mark0.firebaseapp.com",
projectId: "book-mark0",
storageBucket: "book-mark0.appspot.com",
messagingSenderId: "135511543951",
appId: "1:135511543951:web:01fbab4f03d5076f0060fa"
};
export default firebaseconfig<file_sep>/src/Components/Privacy/Privacy.js
import React, { useState } from 'react';
import logo from '../../logo.png';
import frame from '../../frame.png';
import Footer from '../Footer/Footer';
import { useHistory } from 'react-router';
import { Link } from 'react-router-dom';
import back from '../../back.png'
const Privacy = () => {
document.title = 'QikDaw | Privacy Polices'
const [status, setStatus] = useState(false)
const history = useHistory()
return (
<>
<div className="d-flex flex-wrap justify-content-between" >
<Link to="/home" className='mt-3 px-4 text-center' style={{ height: '100px' }}>
<img className='img-responsive' style={{ width: '150px' }} src={logo} alt="" />
<h5 style={{ color: '#ABABAB' }}>Quick door to the world</h5>
</Link>
<div className='d-none d-sm-flex'>
<img className='img-responsive' src={frame} alt="" />
</div>
</div>
<div className='d-flex'>
<div className='col-3' style={{ cursor: 'pointer' }} onClick={() => {
history.push('/home')
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
</div>
<div className='container' style={{ color:'grey'}}>
<h4 style={{ color: '#ABABAB' }}>QIKDAW PRIVACY POLICY AGREEMENT</h4>
<div>
<p>
QikDaw is committed to keeping any and all personal information collected of those individuals that visit our website and make use of our on-line facilities and services accurate, confidential, secure and private. Our privacy policy has been designed and created to ensure those affiliated with QikDaw of our commitment and realization of our obligation not only to meet but to exceed most existing privacy standards.
</p>
<span className='font-weight-bold'>THEREFORE,</span> this Privacy Policy Agreement shall apply to and thus it shall govern any and all data collection and usage thereof. Through the use of and you are herein consenting to the following data procedures expressed within this agreement.
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>Collection of Information</h6>
This website collects various types of information, such as:
<ul>
<li>Voluntarily provided information which may include your name and email address - which may be used when you create account to use the services provided by QikDaw.</li>
<li>Information automatically collected when visiting our website, which may include cookies and server logs.</li>
</ul>
<p>
Please rest assured that this site shall only collect personal information that you knowingly and willingly provide by way of surveys, completed membership forms, and emails. It is the intent of this site to use personal information only for the purpose for which it was requested and any additional uses specifically provided on this site.
QikDaw may also have the occasion to collect anonymous demographic information that may not be unique to you and may even gather additional or other personal and/or non-personal information, such as age, gender and email address at a later time.
It is highly recommended and suggested that you review the privacy policies and statements of any website you choose to use or frequent as a means to better understand the way in which other websites garner, make use of and share information collected.
</p>
<h6 className='font-weight-bold text-decoration-underline' style={{fontWeight: 'bold'}}>Use of Information Collected</h6>
<p>QikDaw may collect and may make use of personal information to assist in the operation of our website and to ensure delivery of the services you need and request. At times, we may find it necessary to use personally identifiable information meant to inform you of other possible products and/or services that may be available to you from QikDaw and its subsidiaries. QikDaw may also be in contact with you with regards to completing surveys and/or research questionnaires related to your opinion of current or possible new services that are offered or may be offered.</p>
<p> QikDaw does not now, nor will it in the future, sell, rent or lease any of its customer lists and/or names to any third parties.</p>
<p>QikDaw from time to time, may feel it necessary to make contact with you on behalf of other external business partners with regards to a specific offer which may be of interest to you. If you consent or show interest in presented offers, then, at that time, specific identifiable information, such as name, email address and/or telephone number, may be shared with the third party.</p>
<p>
QikDaw may find it beneficial to share specific data with their trusted partners in an effort to conduct statistical analysis, provide you with email and/or postal mail, deliver support and/or arrange for deliveries to be made. Those third parties shall be strictly prohibited from making use of your personal information, other than to deliver those services which you requested, and as such they are thus required in accordance with this agreement to maintain the confidentiality of all your information.
</p>
<p>
QikDaw may deem it necessary to follow websites and/or pages that their users may frequent in an effort to gleam what types of services and/or products may be the most popular to customers or the general public.
</p>
<p>
QikDaw may disclose your personal information, without prior notice to you, only if required to do so pursuant to applicable laws and/or in a good faith belief that such action is deemed necessary or required to:
</p>
<p>
a) Conform to decrees, laws and/or statutes or in an effort to comply with any process which may be served upon QikDaw and/or its website;
</p>
<p>
b) Safeguard and/or preserve all the rights and/or property of QikDaw; and
</p>
<p>
c) Perform under demanding conditions in an effort to safeguard the personal safety of users of QikDaw and/or the general public.
</p>
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>Children Under Age of 13</h6>
<p>
QikDaw does not knowingly collect personal identifiable information from children under the age of thirteen (13) without verifiable parental consent. If it is determined that such information has been inadvertently collected on anyone under the age of thirteen (13), we shall immediately take the necessary steps to ensure that such information is deleted from our system’s database. Anyone under the age of thirteen (13) must seek and obtain parent or guardian permission to use this website.
</p>
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>Unsubscribe or Opt-Out</h6>
<p>All users and/or visitors to our website have the option to discontinue receiving communication from us and/or reserve the right to discontinue receiving communications by way of email or newsletters. To discontinue or unsubscribe to our website please send an email that you wish to unsubscribe to <EMAIL>. If you wish to unsubscribe or opt-out from any third-party websites, you must go to that specific website to unsubscribe and/or opt-out.</p>
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>Links to Other Web Sites</h6>
<p>
Our website does contain links to affiliate and other websites. QikDaw does not claim nor accept responsibility for any privacy policies, practices and/or procedures of other such websites. Therefore, we encourage all users and visitors to be aware when they leave our website and to read the privacy statements of each and every website that collects personally identifiable information. The aforementioned Privacy Policy Agreement applies only and solely to the information collected by our website.
</p>
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>
Security
</h6>
<p>
QikDaw shall endeavor and shall take every precaution to maintain adequate physical, procedural and technical security with respect to its offices and information storage facilities so as to prevent any loss, misuse, unauthorized access, disclosure or modification of the user’s personal information under our control.
</p>
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>
Changes to Privacy Policy Agreement
</h6>
<p>
QikDaw reserves the right to update and/or change the terms of our privacy policy, and as such we will post those change to our website homepage at QikDaw, so that our users and/or visitors are always aware of the type of information we collect, how it will be used, and under what circumstances, if any, we may disclose such information. If at any point in time QikDaw decides to make use of any personally identifiable information on file, in a manner vastly different from that which was stated when this information was initially collected, the user or users shall be promptly notified by email. Users at that time shall have the option as to whether or not to permit the use of their information in this separate manner.
</p>
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>Acceptance of Terms</h6>
<p>
Through the use of this website, you are hereby accepting the terms and conditions stipulated within the aforementioned Privacy Policy Agreement. If you are not in agreement with our terms and conditions, then you should refrain from further use of our sites. In addition, your continued use of our website following the posting of any updates or changes to our terms and conditions shall mean that you are in agreement and acceptance of such changes.
</p>
<h6 style={{fontWeight: 'bold', textDecoration: 'underline'}}>How to Contact Us</h6>
<p>
If you have any questions or concerns regarding the Privacy Policy Agreement related to our website, please feel free to contact us at the following email, telephone number or mailing address.
</p>
<p>Email: <EMAIL></p>
</div>
</div>
<Footer />
</>
);
};
export default Privacy;<file_sep>/src/Components/AllLogin/Login/Login.js
import React, { useEffect, useState } from 'react';
import { useFormik } from 'formik';
import { Link, useHistory, useLocation } from 'react-router-dom';
import firebase from 'firebase/app'
import "firebase/auth";
import "firebase/firestore";
import firebaseconfig from '../firebaseconfig';
import LoginWIthGoogle from '../LoginWithGoogle/LoginWIthGoogle';
import LoginWithFacebook from '../LoginWithFacebook/LoginWithFacebook';
const Login = () => {
const history = useHistory()
const location = useLocation()
const [user, setUser] = useState([])
const [loading, setLoading] = useState(false)
const [status, setStatus] = useState({
checkbox: ''
})
const { from } = location.state || { from: { pathname: `/home` } };
useEffect(() => {
fetch('http://qikdaw.com:5000/data')
.then(res => res.json())
.then(data => {
setUser(data)
})
}, [])
const [manageError, setManageError] = useState('')
const formik = useFormik({
initialValues: {
email: '',
password: '',
checkbox: false,
},
onSubmit: (values, { resetForm }) => {
setLoading(true)
user.map(x => {
if (x.email == values.email && x.password == values.password) {
// if(values.checkbox){
localStorage.setItem('loggedIn', x.id)
// }else{
// sessionStorage.setItem('loggedIn', x.id)
// }
setLoading(false)
setTimeout(() => {
history.replace(from)
window.location.reload(true);
},1000)
}
else if (x.email == values.email && x.password !== values.password) {
setLoading(false)
setManageError('no password saved for this email. you can use gmail login')
setTimeout(function () {
setManageError('');
}, 5000);
}
// else {
// setLoading(false)
// setManageError('Invalid Email or Password! Please try again.')
// setTimeout(function () {
// setManageError('');
// }, 5000);
// }
})
},
})
return (
<>
<div style={{ padding: '10px 0' }}>
<div className='text-center' id='er'>
{manageError ? <p className='bg-danger text-white px-5'>{manageError}</p> : null}
</div>
<div className='d-flex flex-wrap justify-content-center ' style={{ backgroundColor: 'white', width: '' }}>
<h4 className='mb-3 text-center' style={{ color: '#ABABAB', fontWeight: 'bold' }}>Log In</h4>
<form className='d-flex flex-wrap justify-content-center mb-3' onSubmit={formik.handleSubmit}>
<div className="form-group col-12 col-sm-8 col-lg-8 mb-4">
<input style={{ borderRadius: '40px', border: '2px solid #A0A1A1' }} onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} type="email" className="form-control px-3 py-3" name='email' id='email' placeholder="Email" />
{formik.touched.email && formik.errors.email ? (<div className="text-danger text-left">{formik.errors.email}</div>) : null}
</div>
<div className="form-group col-12 col-sm-8 col-lg-8 mb-4">
<input style={{ borderRadius: '40px', border: '2px solid #A0A1A1' }} onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.password} type="password" className="form-control px-3 py-3" name='password' id='password' placeholder="<PASSWORD>" />
{formik.touched.password && formik.errors.password ? (<div className="text-danger text-left">{formik.errors.password}</div>) : null}
</div>
<div className="form-check col-8">
<input type="checkbox" className="form-check-input" id="checkbox" onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.checkbox} />
<label className="form-check-label" htmlFor="exampleCheck1" style={{ color: '#ABABAB', fontStyle: 'italic' }}>Keep me Logged In</label>
</div>
<Link to='/forget' className='text-center col-md-10 col-8 text-decoration-none mb-3 font-weight-bold pt-3' style={{ color: '#B6E8DA', fontStyle: 'italic' }}>Forgot my password</Link>
<button type="submit" className="btn col-12 col-sm-8 col-lg-8 ml-2 px-3 mt-1 py-2" style={{ borderRadius: '40px', backgroundColor: '#84EBD2', border: '2px solid #A0A1A1' }}><h6 style={{ color: '#A0A1A1', fontWeight: 'bold' }}> Log In</h6></button>
{loading ? <div className="mt-2 ml-5">
<div className="spinner-border text-primary" role="status">
{/* <span className = "sr-only">Loading...</span> */}
</div>
</div> : null}
</form>
<LoginWIthGoogle />
<LoginWithFacebook />
</div>
</div>
</>
);
};
export default Login;<file_sep>/src/Components/BookMarkNow/BookMarkNow.js
import React, { useState } from 'react';
import './BookMarkNow.css'
import { useFormik } from 'formik'
import { Link, useHistory } from 'react-router-dom';
import 'antd/dist/antd.css';
import { Checkbox } from 'antd';
import Footer from '../Footer/Footer';
import back from '../../back.png'
import plus from '../../plus.png'
const BookMarkNow = ({ email, bookmarkdata, category }) => {
const usermail = email
const [status, setStatus] = useState(false)
const [categoryValue, setCategoryValue] = useState([])
const [count, setCount] = useState(false)
const [showCat, setShowCat] = useState(true)
const [newCat, setNewCat] = useState(false)
const [existingCat, setExistingCat] = useState('')
const history = useHistory()
const [loading, setLoading] = useState(true)
const formik = useFormik({
initialValues: {
email: usermail,
category: '',
sitelink: '',
sitename: '',
checkbox: [],
},
onSubmit: (values) => {
setLoading(false)
const newCategory = new FormData()
if (values.category) {
newCategory.append('category', values.category)
} else {
categoryValue.map((value) =>
newCategory.append('category', value)
)
}
console.log(categoryValue)
newCategory.append('email', usermail)
newCategory.append('sitename', values.sitename)
newCategory.append('sitelink', values.sitelink)
fetch('http://qikdaw.com:5000/bookmark', {
method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(newCategory)
body: newCategory
})
.then(response => response.json())
.then(data => {
console.log(data)
if (data) {
console.log('true')
window.location.reload(true);
// window.location.reload(true);
}
})
.catch(error => {
console.error(error)
})
setTimeout(() => {
window.location.reload()
}, 3000)
},
validate: (values) => {
let errors = {};
if (!categoryValue) {
if (!values.category) {
errors.category = 'Required'
}
}
return errors
}
})
const handleClicked = () => {
setNewCat(true)
setCount(true)
}
const CatArr = []
let key = 0
bookmarkdata.map((x, id) => {
CatArr.push(x.category)
key = id
})
const catArr = []
function onChange(checkedValues) {
setCategoryValue(checkedValues)
}
return (
<div style={{ minHeight: '75vh' }}>
{ loading ?
<div >
<div className='px-5'>
<div className='d-flex flex-wrap justify-content-between align-items-center mb-3 text-center px-3 py-2' style={{ cursor: 'pointer', width: '200px', border: '3px solid #C64CE9', borderRadius: '30px' }} >
<h5 className='text-muted text-center'>BOOKMARK</h5>
<div>
<img style={{ width: '40px' }} src={plus} alt="" />
</div>
</div>
<div style={{ borderBottom: '3px solid lightgrey' }}>
</div>
</div>
<form onSubmit={formik.handleSubmit} >
<div>
{newCat == false ?
<div>
<div className='d-flex flex-wrap justify-content-center mt-4'>
<div className='col-12 col-lg-1 mb-5' style={{ cursor: 'pointer' }} onClick={() => {
window.location.reload()
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
<div className='col-12 col-lg-2 text-center'>
<h5 className='text-muted'>Create New Category</h5>
</div>
<div className='col-10 col-md-6 col-lg-3'>
<input type="text" className="form-control p-2" name='category' id='category' placeholder="Enter Category" value={formik.values.category} onChange={formik.handleChange} onBlur={formik.handleBlur} />
{formik.touched.category && formik.errors.category ? (<div className="text-danger text-left">{formik.errors.category}</div>) : null}
</div>
<div className='col-lg-2 col-10'>
<p className='text-muted text-center'>Example : Social Sites <br /> (Max: 25) </p>
</div>
</div>
{showCat ?
<div className='text-center mt-2' style={{ textDecoration: 'underline', cursor: 'pointer', textDecorationColor: '#DFCCF4' }} onClick={() => setShowCat(false)}>
<h4 style={{ color: '#DFCCF4', fontWeight: 'bold' }}>Or Select Exiting Category</h4>
</div>
:
<div className='mt-2'>
<div className='text-center'>
<h4 className='text-muted'>Or Select Exiting Category</h4>
</div>
<div className='d-flex justify-content-center mt-3 ' id='cat'>
<Checkbox.Group className='' options={CatArr} onChange={onChange} />
</div>
</div>}
<div className="text-center">
{(formik.values.category || categoryValue.length > 0) ? <button onClick={() => handleClicked()} type="button" className='btn px-5 py-3 text-muted' style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', fontWeight: 'bold', border: '1px solid #7A7A7A' }} >NEXT</button> : <button type='button' className='btn px-5 py-3 text-muted' style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', fontWeight: 'bold', border: '1px solid #7A7A7A' }} >NEXT</button>}
</div>
</div> : null}
</div>
{count ?
<div className=''>
<div className='d-flex flex-wrap'>
<div onClick={() => {
setCount(false)
setNewCat(false)
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
<h4 className=' mt-2 ml-2'>Category <span className='font-weight-bold'> :
</span>
<span className='mt-4'>
{formik.values.category ? <span className="px-3 mt-3" style={{ borderRadius: '40px', color: '#DFCCF4', border: '1px solid #DFCCF4', fontWeight: 'bold' }} id='cate'>{formik.values.category}</span>
: <span className='pt-5'>
{
categoryValue.map(x => <span className="px-3 mt-4 mx-2" style={{ borderRadius: '40px', color: '#DFCCF4', border: '1px solid #DFCCF4', fontWeight: 'bold' }} id='cate'>{x}</span>)
}
</span>
}
</span></h4>
</div>
<div className='d-flex flex-wrap justify-content-center my-3 align-items-center'>
<div className='col-12 col-lg-2 text-center'>
<h4>Website URL/address</h4>
</div>
<div className='col-10 col-md-6 col-lg-3'>
<input type="text" className="form-control p-2" name='sitelink' id='sitelink' placeholder="" value={formik.values.sitelink} onChange={formik.handleChange} onBlur={formik.handleBlur} />
{formik.touched.sitelink && formik.errors.sitelink ? (<div className="text-danger text-left">{formik.errors.sitelink}</div>) : null}
</div>
<div className='col-12 col-lg-2 text-center'>
<p className='text-muted text-center' style={{ fontStyle: 'italic' }}>Example : www.webname.com</p>
</div>
</div>
<div className='d-flex flex-wrap justify-content-center my-3 align-items-center'>
<div className='col-12 col-lg-2 text-center'>
<h4 className=''>Name</h4>
</div>
<div className='col-10 col-md-6 col-lg-3'>
<input type="text" className="form-control p-2" name='sitename' id='sitename' placeholder="" value={formik.values.sitename} onChange={formik.handleChange} onBlur={formik.handleBlur} />
{formik.touched.sitename && formik.errors.sitename ? (<div className="text-danger text-left">{formik.errors.sitename}</div>) : null}
</div>
<div className='col-12 col-lg-2 text-center'>
<p className='text-muted text-center' style={{ fontStyle: 'italic' }}>Example : FBook</p>
</div>
</div>
<div className='text-center mt-5'>
<button type="submit" className='btn px-5 py-3 text-muted' style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', fontWeight: 'bold', border: '1px solid #7A7A7A' }}>DONE</button>
</div>
</div>
: null}
</form>
</div>
:
<div className='text-center p-5'>
<div className="spinner-border text-primary" role="status">
{/* <span className = "sr-only">Loading...</span> */}
</div>
</div>}
</div>
);
};
export default BookMarkNow;<file_sep>/src/Components/AllLogin/LoginWithEmail/LoginWithEmail.js
import React, { useEffect, useState } from 'react';
import { useFormik } from 'formik';
import { Link, useHistory, useLocation } from 'react-router-dom';
import { v4 as uuidv4 } from 'uuid';
import profile from '../../../profile.png';
import logo from '../../../logo.png';
import frame from '../../../frame.png';
import firebase from 'firebase/app';
import "firebase/auth";
import "firebase/firestore";
import firebaseconfig from '../firebaseconfig'
import Footer from '../../Footer/Footer';
import back from '../../../back.png'
import './LoginWithEmail.css';
if (!firebase.apps.length) {
firebase.initializeApp(firebaseconfig);
}
const LoginWithEmail = () => {
document.title = 'QikDaw | Signup'
const history = useHistory()
const location = useLocation()
const { from } = location.state || { from: { pathname: `/home` } };
const [status, setStatus] = useState({
signup: false,
email: true,
fname: false,
lname: false,
password: <PASSWORD>,
photoURL: false,
haserror: false,
errmessage: '',
id: null
})
const [user, setUser] = useState([])
useEffect(() => {
fetch('http://qikdaw.com:5000/data')
.then((response) => response.json())
.then(data => {
if (data) {
setUser(data)
}
})
}, [])
const [manageError, setManageError] = useState('')
const [handleImg, setHandleImg] = useState(null)
const [handleInput, setHandleInput] = useState(false)
const [loading, setLoading] = useState(true)
const [isMailHere, setIsMailHere] = useState(false)
const handleFileChange = (e) => {
const newImageFile = e.target.files[0];
setHandleImg(newImageFile);
}
const formik = useFormik({
initialValues: {
fname: '',
lname: '',
email: '',
password: '',
photoURL: '',
id: '',
},
onSubmit: (values, { resetForm }) => {
setLoading(false)
firebase.auth().createUserWithEmailAndPassword(values.email, values.password)
.then((userCredential) => {
var user = userCredential.user;
var userT = user.b.a
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage)
// ..
});
let randomToken;
randomToken = uuidv4()
const userData = new FormData()
userData.append('fname', values.fname);
userData.append('lname', values.lname);
userData.append('email', values.email);
userData.append('password', values.password);
userData.append('id', randomToken);
localStorage.setItem('loggedIn', randomToken)
userData.append('type', 'withmail');
if (handleImg) {
userData.append('file', handleImg);
} else {
userData.append('nofile', true);
}
fetch('http://qikdaw.com:5000/users', {
method: 'POST',
// headers: { 'Content-Type': 'application/json' },
body: userData,
})
.then(response => response.json())
.then(data => {
if (data) {
history.replace(from)
window.location.reload(true);
}
})
.catch(error => {
console.error(error)
})
setTimeout(() => {
history.replace(from)
window.location.reload(true);
},3000)
},
validate: (values) => {
let errors = {};
if (!values.email) {
errors.email = 'Required'
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9,-]+\.[A-Z]{2,}$/i.test(values.email)) {
errors.email = 'Invalid Email Address'
}
if (!values.password) {
errors.password = '<PASSWORD>'
} else if (values.password.length < 7) {
errors.password = 'Must be at least 7 characters'
}
if (!values.fname) {
errors.fname = 'Required'
}
return errors
}
})
const manageChange = () => {
setIsMailHere(false)
if (user != []) {
setIsMailHere(true)
user.map(x => {
if (x.email == formik.values.email) {
setManageError('User already exists.')
}
else {
setStatus({ email: false, password: true })
}
})
}
else {
setStatus({ email: false, password: true })
}
}
return (
<div >
{loading ?
<div >
<div className="d-flex flex-wrap justify-content-between">
<Link to="/home" className='mt-3 px-4 text-center' style={{ height: '100px' }}>
<img className='img-responsive' style={{ width: '150px' }} src={logo} alt="" />
<h5 style={{ color: '#ABABAB' }}>Quick door to the world</h5>
</Link>
<div className='d-none d-sm-flex'>
<img className='img-responsive' src={frame} alt="" />
</div>
</div>
<div style={{ padding: ' 0', minHeight : '80vh' }} id='signup'>
<div className='d-flex flex-wrap justify-content-center' style={{ backgroundColor: '', width: '' }}>
<form className='d-flex flex-wrap justify-content-center' onSubmit={formik.handleSubmit}>
{status.email ?
<div className='d-flex flex-wrap justify-content-center'>
<Link to='/login' className='col-lg-12 col-12' style={{ cursor: 'pointer' }} >
<img style={{ width: '80px' }} src={back} alt="" />
</Link>
{/* <div className='col-12 col-sm-8 col-lg-8'> */}
<div className="form-group col-10 col-sm-8 col-lg-8 ">
<h4 className='text-center mx-5 text-muted mb-4'>SIGN UP - Enter your email</h4>
<input onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} type="email" className="form-control" name='email' id='email' placeholder="Email" />
{formik.touched.email && formik.errors.email ? (<div className="text-danger text-left">{formik.errors.email}</div>) : null}
<p className='my-2' style={{ fontStyle: 'italic', fontSize: '12px' }}>By clicking the NEXT button, you are agreeing to <span style={{ color: '#B6E8DA', textDecoration: 'underline' }} onClick={() => history.push('/terms')}>Terms and Conditions</span> governing QikDaw</p>
</div>
<div className="form-group col-8 col-sm-8 col-lg-8 ml-2 px-3 my-4 text-center">
{formik.errors.email || !formik.values.email ?
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }} ><h6 className="text-muted">NEXT</h6></button> :
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }} onClick={() => manageChange()}><h6 className="text-muted">NEXT</h6></button>}
</div>
{/* /* <div className='text-center'>
{isMailHere ? <div className="mt-2 ml-5">
<div className="spinner-border text-primary" role="status">
{/* <span className = "sr-only">Loading...</span> */}
{/* </div>
</div> : null}
</div> */}
</div> : null}
{manageError ?
<p className='text-white bg-danger text-center p-2'>{manageError} <Link className='text-white' to='/login'>Click here to login</Link></p> :
<div>
{
status.password ?
<div className='d-flex flex-wrap justify-content-center'>
<div className='col-lg-12 col-12' style={{ cursor: 'pointer' }} onClick={() => {
setStatus({ password: false })
setStatus({ email: true })
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
<div className='col-md-12 col-10'>
<div className="form-group col-md-12 my-4" >
<h4 className='text-center mx-5 text-muted w-100 mx-auto mb-4'>SIGN UP - Choose your password</h4>
<input onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.password} type="password" className="form-control" name='password' id='password' placeholder="<PASSWORD>" />
{formik.touched.password && formik.errors.password ? (<div className="text-danger text-left">{formik.errors.password}</div>) : null}
</div>
<div className="form-group col-md-12 my-4 text-center">
{formik.errors.password || !formik.values.password ?
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }}><h6 className="text-muted">NEXT</h6></button> :
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }} onClick={(e) => setStatus({ password: false, fname: true, haserror: false })}><h6 className="text-muted">NEXT</h6></button>}
</div>
</div>
</div> : null
}
</div>}
{status.fname ?
<div className='d-flex flex-wrap justify-content-center'>
<div className='col-lg-12 col-10' style={{ cursor: 'pointer' }} onClick={() => {
setStatus({ fname: false })
setStatus({ password: true })
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
<div className='col-md-12 col-10'>
<div className="form-group col-md-12" >
<h4 className='text-center mx-5 text-muted mb-4'>SIGN UP - Name</h4>
<input onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.fname} type="text" className="form-control" name='fname' id='fname' placeholder="Enter Your Name" />
{formik.touched.fname && formik.errors.fname ? (<div className="text-danger text-left">{formik.errors.fname}</div>) : null}
</div>
<div className="form-group col-md-12 my-4 text-center">
{formik.errors.fname || !formik.values.fname ?
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }}><h6 className="text-muted">NEXT</h6></button> :
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }} onClick={(e) => setStatus({ fname: false, photoURL: true })}><h6 className="text-muted">NEXT</h6></button>}
</div>
</div>
</div> : null}
{/* {status.lname ?
<div className='d-flex flex-wrap justify-content-center'>
<div className='col-lg-12 col-12' style={{ cursor: 'pointer' }} onClick={() => {
setStatus({ lname: false })
setStatus({ fname: true })
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
<div className='col-md-12 col-10'>
<div className="form-group col-md-12" >
<h4 className='text-center mx-5 text-muted'>SIGN UP - Name</h4>
<input onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.lname} type="text" className="form-control" name='lname' id='lname' placeholder="<NAME>" />
{formik.touched.lname && formik.errors.lname ? (<div className="text-danger text-left">{formik.errors.lname}</div>) : null}
</div>
<div className="form-group col-md-12 my-4 text-center">
{formik.errors.lname || !formik.values.lname ?
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }}><h6 className="text-muted">NEXT</h6></button> :
<button type="button" className="form-control btn px-3 mt-1 py-2 mb-5" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '2px solid #A0A1A1' }} onClick={(e) => setStatus({ lname: false, photoURL: true })}><h6 className="text-muted">NEXT</h6></button>}
</div>
</div>
</div> : null} */}
{status.photoURL ?
<div className='d-flex flex-wrap justify-content-center'>
<div className='col-lg-12 col-12' style={{ cursor: 'pointer' }} onClick={() => {
setStatus({ photoURL: false })
setStatus({ lname: true })
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
<div className='col-md-12 col-10'>
<div className="form-group col-md-12" >
<h5 className='text-center mx-5 text-muted'>Upload a profile picture</h5>
<div className='text-center' onClick={() => setHandleInput(true)} style={{cursor : 'pointer'}}>
<img style={{ width: '150px' }} src={profile} alt="" />
</div>
{handleInput ? <input onChange={handleFileChange} type="file" className="btn form-control border" name='file' id='file' placeholder="file" /> : null}
</div>
<div className="form-group col-md-12 my-4 text-center">
{handleImg ? <button type='submit' className="form-control btn px-3 mt-1 py-2" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '1px solid #979797' }}><h6 className='text-white' style={{ fontWeight: 'bold' }}>UPLOAD</h6></button> :
<button type='button' className="form-control btn px-3 mt-1 py-2" style={{ borderRadius: '40px', backgroundColor: '#DFCCF4', border: '1px solid #979797' }} onClick={() => setHandleInput(true)}><h6 className='text-white' style={{ fontWeight: 'bold' }}>UPLOAD</h6></button>
}
</div>
<div className="form-group col-md-12 mt-4 text-center">
<button type={handleImg ? 'button' : 'submit'} className="form-control btn px-3 py-2" style={{ borderRadius: '40px', backgroundColor: '#DFDDE0', border: '1px solid #979797' }} ><h6 style={{ color: 'grey' }}>Later</h6></button>
</div>
</div>
</div> : null}
</form>
</div>
</div>
<Footer />
</div> :
<div style={{
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)'
}}>
<div className="spinner-border text-primary" role="status">
{/* <span className = "sr-only">Loading...</span> */}
</div>
</div>
}
</div>
);
};
export default LoginWithEmail;<file_sep>/src/App.js
import React from 'react';
import './App.css';
import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom';
import LoginPage from './Components/AllLogin/LoginPage/LoginPage';
import LoginWithEmail from './Components/AllLogin/LoginWithEmail/LoginWithEmail';
import HomePage from './Components/HomePage/HomePage';
import Footer from './Components/Footer/Footer';
import Contact from './Components/Contact/Contact';
import PrivateRoute from './Components/PrivateRoute/PrivateRoute';
import UserProfile from './Components/UserProfile/UserProfile';
import ForgetPass from './Components/ForgetPass/ForgetPass';
import Privacy from './Components/Privacy/Privacy';
import Terms from './Components/Terms/Terms';
function App() {
return (
<BrowserRouter>
<Switch>
<PrivateRoute exact path ='/home' component ={HomePage} />
<Route exact path ='/login' component ={LoginPage} />
<Route exact path ='/signup' component ={LoginWithEmail} />
<Route exact path ='/contact' component ={Contact} />
<Route exact path ='/privacy' component ={Privacy} />
<Route exact path ='/terms' component ={Terms} />
<Route exact path ='/forget' component ={ForgetPass} />
<PrivateRoute exact path ='/userprofile' component ={UserProfile} />
<Redirect from = '/' to = '/home' />
{/* <Footer/> */}
</Switch>
</BrowserRouter>
);
}
export default App;
<file_sep>/src/Components/Footer/Footer.js
import React from 'react';
import { useHistory } from 'react-router';
import './Footer.css'
const Footer = () => {
const history = useHistory()
return (
<div className='d-flex flex-wrap justify-content-center' style={{ color: '#ABABAB', }} id='foot'>
<p className='col- col-lg-2 mx-2 text-center text-decoration-none'>Copyright QikDaw.com 2021</p>
<p className='col- col-lg-2 mx-2 text-center' style={{ cursor: 'pointer' }} onClick={() => history.push('/contact')}>Contact</p>
<p className='col- col-lg-2 mx-2 text-center' style={{ cursor: 'pointer' }} onClick={() => history.push('/terms')}>Terms of Use/Service</p>
<p className='col- col-lg-2 mx-2 text-center' style={{ cursor: 'pointer' }} onClick={() => history.push('/privacy')}>Privacy Policy</p>
</div>
);
};
export default Footer;<file_sep>/src/Components/Bookmark/Bookmark.js
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import BookMarkNow from '../BookMarkNow/BookMarkNow';
import AddBookMark from '../AddBookMark/AddBookMark';
import 'antd/dist/antd.css';
import { Modal, Button } from 'antd';
import './Bookmark.css';
import plus from '../../plus.png';
import lplus from '../../lplus.png';
import edit from '../../edit.png';
import del from '../../delete.png';
import EditCategory from '../EditCategory/EditCategory';
const Bookmark = ({ email }) => {
const usermail = email
const [isBookMarkOpen, setIsBookMarkOpen] = useState(false)
const [bookdata, setBookData] = useState([])
const [siteId, setSiteId] = useState(0)
const [addCat, setAddCat] = useState('')
let [showBookData, setShowBookData] = useState([])
const [showOptions, setShowOptions] = useState(null)
const [loading, setLoading] = useState(true)
const [editCat, setEditCat] = useState(true)
const [sendData, setSendData] = useState([])
const [isOpen, setIsOpen] = useState(false)
const handleClick = (e) => {
if (isBookMarkOpen == false) {
setIsBookMarkOpen(true)
}
if (isBookMarkOpen == true) {
setIsBookMarkOpen(false)
}
}
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
};
console.log(addCat)
const handleCancel = () => {
setIsModalVisible(false);
};
useEffect(() => {
axios.get('http://qikdaw.com:5000/bookmarkinfo')
.then((response) => response.data)
.then(data => {
if (data) {
setIsOpen(true)
setShowBookData(data)
}
})
}, [])
let showData = []
showBookData.map(x => {
if (x.email == email) {
showData.push(x)
}
})
console.log(showData)
const filteredArr = showData.reduce((acc, current) => {
const x = acc.find(item => item.category === current.category);
console.log(x)
if (!x) {
const newCurr = {
category: current.category,
sitename: [current.sitename],
sitelink: [current.sitelink],
}
console.log(acc)
return acc.concat([newCurr]);
} else {
const currData = x.sitename.filter(d => d === current.sitename);
const slink = x.sitelink.filter(d => d === current.sitelink);
console.log(currData)
console.log(slink)
if (!currData.length && !slink.length) {
const newData = x.sitename.push(current.sitename);
const newLink = x.sitelink.push(current.sitelink);
const newCurr = {
category: current.category,
sitename: newData,
sitelink: newLink
}
return acc;
} else {
return acc;
}
}
}, []);
let site = []
let link = []
let allSiteName = []
let allSiteLink = []
filteredArr.map(x => {
for (var i = 0; i < x.sitename.length; i++) {
if (x.sitename[i] !== undefined && x.sitename[i] != "" && site.indexOf(x.sitename[i]) == -1) {
site.push(x.sitename[i]);
}
}
for (var i = 0; i < x.sitelink.length; i++) {
if (x.sitelink[i] !== undefined && x.sitelink[i] != "" && link.indexOf(x.sitelink[i] === -1)) {
link.push(x.sitelink[i]);
}
}
for (var i = 0; i < x.sitename.length; i++) {
if (x.sitename[i] !== undefined && x.sitename[i] != "") {
allSiteName.push(x.sitename[i]);
}
}
for (var i = 0; i < x.sitelink.length; i++) {
if (x.sitelink[i] !== undefined && x.sitelink[i] != "" ) {
allSiteLink.push(x.sitelink[i]);
}
}
const arry = x.sitename.filter(y => y)
console.log(arry)
})
const handleCategory = (e, id, cat) => {
setBookData(id)
setSiteId(cat)
showModal()
}
const handleOk = (e) => {
setLoading(false)
fetch(`http://qikdaw.com:5000/deletebookmark?email=${email}&&category=${siteId.category}&&sitename=${bookdata}`, {
method: 'DELETE'
})
.then(res => res.json())
.then(data => {
if (!data) {
window.location.reload(true);
} else {
window.location.reload(false);
setLoading(false)
}
})
setTimeout(function () {
window.location.reload()
}, 3000);
};
const handleEdit = (e, y, x, id) => {
setEditCat(false)
setSendData({ category: x.category, sitename: x.sitename.filter(str => /\S/.test(str))[id], sitelink: x.sitelink.filter(str => /\S/.test(str))[id] })
}
filteredArr.reverse()
return (
<div>
{loading ?
<div>
{addCat == '' ? <div>
{editCat ? <div>
{isBookMarkOpen == false ?
<div>
{isOpen ?
<div>
<div className='d-flex flex-wrap justify-content-between align-items-center px-2 mb-3' style={{ cursor: 'pointer', width: '200px' }} onClick={(e) => handleClick()} id='add'>
<h5 className='text-muted text-center' style={{ color: 'grey', fontWeight: 'bold' }}>BOOKMARK</h5>
<div>
<img style={{ width: '50px' }} src={plus} alt="" />
</div>
</div>
<div style={{ borderBottom: '3px solid lightgrey' }}>
</div>
<div className='d-flex flex-wrap justify-content-center justify-content-sm-start' >
<div className='col-12 col-sm-3 col-md-2 col-lg-2' >
<div className="nav flex-column nav-pills me-3 pl-0 ml-0" id="v-pills-tab" role="tablist" aria-orientation="vertical" style={{ textAlign: 'center', minHeight: '70vh', minWidth: '100%', backgroundColor: '#F8EDF7', }}>
<button className="nav-link active text-center mx-auto" id="v-pills-home-tab" data-bs-toggle="pill" data-bs-target="#v-pills-home" type="button" role="tab" aria-controls="v-pills-home" aria-selected="true" style={{ fontWeight: "bold", color: "grey" }}>All</button>
{filteredArr.map((x, id) =>
<button key={id} className="nav-link text-center mx-auto" id={"v-pills-" + x.category.split(' ').join('_') + "-tab"} data-bs-toggle="pill" data-bs-target={"#v-pills-" + x.category.split(' ').join('_')} type="button" role="tab" aria-controls={"v-pills-" + x.category.split(' ').join('_')} aria-selected="false" style={{ fontWeight: "bold", color: "grey" }}>{x.category}</button>)}
</div>
</div>
<div className="tab-content text-center col-md-9 col-6" id="v-pills-tabContent">
<div className="tab-pane fade show active" id="v-pills-home" role="tabpanel" aria-labelledby="v-pills-home-tab" style={{ minHeight: '70vh', minWidth: '100%' }}>
<h5 className='text-center py-2 text-muted'>All</h5>
<div className='d-flex flex-wrap justify-content-md-start justify-content-center'>
{site.map((y, id) =>
<a className='mx-3 px-3 py-2 text-muted mb-2 ' style={{ textDecoration: 'none', color: '#B6B9B9', border: '2px solid #CACACC', borderRadius: '30px', backgroundColor: '#ECEEEE' }} target='_blank' href={"https://" + link[id]} >{y}</a>
)}
</div>
</div>
{filteredArr.map((x, id) =>
<div key={id} className="tab-pane fade" id={"v-pills-" + x.category.split(' ').join('_')} role="tabpanel" aria-labelledby={"v-pills-" + x.category.split(' ').join('_') + "-tab"} style={{ minHeight: '70vh', minWidth: '100%' }}>
<div className='d-flex flex-wrap justify-content-center mx-auto'>
<div className=' col-6'>
<h5 className='py-2 ml-auto' style={{ color: '#D98DEE', textAlign: 'end' }}>{x.category}</h5>
</div>
<div className='col-6'>
<div style={{ textAlign: 'end' }} onClick={() => {
setAddCat(x.category)
setIsBookMarkOpen(true)
}}>
<img src={lplus} alt="" style={{ cursor: 'pointer' }} />
</div>
</div>
</div>
<div className='d-flex flex-wrap justify-content-md-start justify-content-center' style={{ listStyle: 'none', padding: '0' }}>
{x.sitename.filter(str => /\S/.test(str)).map((y, id) =>
<div key={id} className='pl-0' onMouseEnter={() => setShowOptions(id)} onMouseLeave={() => setShowOptions(null)} >
{showOptions == id &&
<div className='d-flex justify-content-center'>
<div style={{ cursor: 'pointer' }} onClick={(e) => handleEdit(e, y, x, id)}>
<img style={{ width: '30px' }} src={edit} alt="" />
</div>
<div style={{ cursor: 'pointer' }} onClick={(e) => handleCategory(e, y, x)}> <img style={{ width: '30px' }} src={del} alt="" />
</div>
</div>}
<div style={{ margin: '0 auto', textAlign: 'center' }}>
<Modal
visible={isModalVisible}
onOk={handleOk}
onCancel={handleCancel}
footer={[
<Button className='text-center' key="back" type="ok" onClick={handleOk}>
Yep
</Button>,
<Button className='text-center' key="one" type="notok" onClick={handleCancel}>
Nah
</Button>,
]}>
<h5 style={{ color: '#ABABAB', textAlign: 'center' }} >Delete '{bookdata}' bookmark?</h5>
</Modal>
</div>
<li className='mx-3 px-3 py-2 text-muted mb-2' style={{ border: '2px solid #CACACC', borderRadius: '30px', backgroundColor: '#ECEEEE' }}> <a style={{ textDecoration: 'none', color: '#B6B9B9' }} target='_blank' href={"https://" + x.sitelink.filter(str => /\S/.test(str))[id]} >{y}</a> </li>
</div>
)}
</div>
</div>
)}
</div>
</div>
</div>
: <div className='text-center p-5'>
<div className="spinner-border text-primary" role="status">
{/* <span className = "sr-only">Loading...</span> */}
</div>
</div>}
</div>
: <BookMarkNow email={email} bookmarkdata={filteredArr} category={addCat} />}
</div> : <EditCategory email={email} data={sendData} />
}
</div > : <AddBookMark email={email} category={addCat} />}
</div >
:
<div className='text-center p-5'>
<div className="spinner-border text-primary" role="status">
{/* <span className = "sr-only">Loading...</span> */}
</div>
</div>
}
</div >
);
};
export default Bookmark;<file_sep>/src/Components/ForgetPass/ForgetPass.js
import React, { useState } from 'react';
import logo from '../../logo.png';
import frame from '../../frame.png';
import Footer from '../Footer/Footer';
import back from '../../back.png'
import { useHistory } from 'react-router';
import firebase from 'firebase/app'
import "firebase/auth";
import "firebase/firestore";
import firebaseconfig from '.././AllLogin/firebaseconfig'
import { Link } from 'react-router-dom';
if (!firebase.apps.length) {
firebase.initializeApp(firebaseconfig);
}
const ForgetPass = () => {
const [status, setStatus] = useState(false)
const [userEmail, setUserEmail] = useState('')
const history = useHistory()
const handleChange = (e) => {
setUserEmail(e.target.value)
}
const handleEmailChange = (e) => {
if (userEmail) {
setStatus(true)
firebase.auth().sendPasswordResetEmail(userEmail)
.then(() => {
console.log('Password Reset Email Sent Successfully!');
})
.catch(error => {
console.error(error);
})
}
}
return (
<>
<div className="d-flex flex-wrap justify-content-between">
<Link to="/home" className='mt-3 px-4 text-center justify-content-center' style={{ height: '100px' }}>
<img className='img-responsive' style={{ width: '150px' }} src={logo} alt="" />
<h5 style={{ color: '#ABABAB' }}>Quick door to the world</h5>
</Link>
<div className='d-none d-sm-flex'>
<img className='img-responsive' src={frame} alt="" />
</div>
</div>
{status == false ?
<div className='d-flex flex-wrap justify-content-center flex-wrap container'>
<div className='col-12 col-lg-1' style={{ cursor: 'pointer' }} onClick={() => {
history.push('/login')
// setStatus({ status: false })
// setStatus({ noedit: true })
}}>
<img style={{ width: '80px' }} src={back} alt="" />
</div>
<form className='d-flex flex-wrap justify-content-center'>
<div className="form-group col-lg-8 col-12 mb-3 mx-5 d-flex flex-wrap">
<h4 className='col-12' style={{ color: '#ABABAB', fontWeight: 'bold' }}>Reset your password</h4>
<input type="email" className="form-control col-12" onBlur={handleChange} id="exampleFormControlInput1" placeholder="Enter your email" />
</div>
<div className="form-group col-12"></div>
<div className="col-5 text-center mt-3">
<button type="button" className="btn col-md-8 col-12 px-3 mt-1 py-2" style={{ borderRadius: '40px', backgroundColor: '#B7F3E5', border: '2px solid #A0A1A1' }}><h6 style={{ color: 'grey', fontWeight: 'bold' }} onClick={handleEmailChange}>Reset my password</h6></button>
</div>
</form>
</div> :
<div className=''>
<h5 className='text-center' style={{ color: '#ABABAB' }}>A link has been sent to the email you provided</h5>
<h5 className='text-center' style={{ color: '#ABABAB' }}>Go to your email and click the link to reset your password</h5>
<div className="col-4 text-center mt-3 mx-auto">
<button type="button" onClick={() => history.push('/login')} className="btn col-md-6 ml-2 px-3 mt-1 py-2" style={{ borderRadius: '40px', backgroundColor: '#B7F3E5', border: '2px solid #A0A1A1' }}><h6 style={{ color: '#ABABAB' }}>GOT IT</h6></button>
</div>
</div>}
<div style={{ position: 'fixed', width: '100%', bottom: '0', }}>
<Footer />
</div>
</>
);
};
export default ForgetPass; | ef21896f46b61bdb0b40be22825d0ab43436c5cf | [
"JavaScript"
] | 10 | JavaScript | abdullahallnaim/qikdaw-client | 6e4d6c068553ac35a39a2540b5b631c817fe93fc | a6957790348465646bc4ae38ec2fc7d675c87b50 |
refs/heads/master | <file_sep><?php
/*
*
* Plugin Name: Common - Events CPT
* Description: Events plugin, for use on big Read.
* Author: <NAME>
*
*/
/* Events Custom Post Type ------------------- */
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
// Set form Enctype
add_action('post_edit_form_tag', 'add_post_enctype');
function add_post_enctype() {
echo ' enctype="multipart/form-data"';
}
// Load our CSS
function camps_load_plugin_css() {
wp_enqueue_style( 'camps-plugin-style', plugin_dir_url(__FILE__) . 'css/style.css');
}
add_action( 'admin_enqueue_scripts', 'camps_load_plugin_css' );
// Add create function to init
add_action('init', 'event_create');
function event_create() {
$args = array(
'label' => 'Events',
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug' => 'event'),
'query_var' => true,
'supports' => array(
'title',
'editor',
'excerpt',
'revisions',
'thumbnail'),
'taxonomies' => array('category')
);
register_post_type( 'event' , $args );
flush_rewrite_rules();
}
add_action("admin_init", "admin_init");
add_action('save_post', 'save_event');
// Add the meta boxes to our CPT page
function admin_init(){
add_meta_box("eventInfo-meta", "Event Options", "event_meta_options", "event", "normal", "low");
add_meta_box("subtitleInfo-meta", "Subtitle", "subtitle_meta_options", "event", "normal", "high");
}
// Meta box functions
function event_meta_options(){
global $post;
$custom = get_post_custom($post->ID);
$location = $custom["location"][0];
$loclink = $custom["loclink"][0];
$sdate = $custom["sdate"][0];
$edate = $custom["edate"][0];
$fcaption = $custom["fcaption"][0];
$fartist = $custom["fartist"][0];
$fmedium = $custom["fmedium"][0];
$aname = $custom["aname"][0];
$adesc = $custom["adesc"][0];
$awebsite = $custom["awebsite"][0];
$stime = $custom["stime"][0];
$etime = $custom["etime"][0];
if($location == "") $location = "";
if($loclink == "") $loclink = "";
include_once('views/events.php');
}
function subtitle_meta_options(){
global $post;
$custom = get_post_custom($post->ID);
$subtitle = $custom["subtitle"][0];
include_once('views/subtitle.php');
}
// Save our variables
function save_event(){
global $post;
update_post_meta($post->ID, "location", $_POST["location"]);
update_post_meta($post->ID, "loclink", $_POST["loclink"]);
update_post_meta($post->ID, "sdate", $_POST["sdate"]);
update_post_meta($post->ID, "edate", $_POST["edate"]);
update_post_meta($post->ID, "fcaption", $_POST["fcaption"]);
update_post_meta($post->ID, "fartist", $_POST["fartist"]);
update_post_meta($post->ID, "fmedium", $_POST["fmedium"]);
update_post_meta($post->ID, "aname", $_POST["aname"]);
update_post_meta($post->ID, "adesc", $_POST["adesc"]);
update_post_meta($post->ID, "awebsite", $_POST["awebsite"]);
update_post_meta($post->ID, "subtitle", $_POST["subtitle"]);
update_post_meta($post->ID, "stime", $_POST["stime"]);
update_post_meta($post->ID, "etime", $_POST["etime"]);
}
?><file_sep><?php
/* Subtitle form */
?>
<textarea name="subtitle" cols="75" rows="1"><?php echo $subtitle; ?></textarea>
<file_sep><?php
/* Events form */
?>
<p>Please fill out as many of these fields as possible in order to make the pages look their best. Ommitted fields will be left blank on the pages.</p>
<h3 class="hndle ui-sortable-handle"><span>General</span></h3>
<br/>
<table>
<tr>
<td style="text-align:center"><label>Location: </label></td>
<td><input type="text" name="location" value="<?php echo $location; ?>" size="50"/></td>
</tr>
<tr>
<td style="text-align:center"><label>Link to Location: </label></td>
<td><input type="text" name="loclink" value="<?php echo $loclink; ?>" size="50"/></td>
</tr>
<tr>
<td style="text-align:center"><label>Start Date: </label></td>
<td><input type="date" name="sdate" value="<?php echo $sdate; ?>" size="50"/></td>
</tr>
<tr>
<td style="text-align:center"><label>End Date: </label></td>
<td><input type="date" name="edate" value="<?php echo $edate; ?>" size="50"/></td>
</tr>
<tr>
<td style="text-align:center"><label>Start Time: </label></td>
<td><input type="time" name="stime" value="<?php echo $stime; ?>" size="50"/></td>
</tr>
<tr>
<td style="text-align:center"><label>End Time: </label></td>
<td><input type="time" name="etime" value="<?php echo $etime; ?>" size="50"/></td>
</tr>
</table><br/>
<div style="display:none">
<h3 class="hndle ui-sortable-handle"><span>Banner Image</span></h3>
<p>Make sure to set The Featured image to a large Image. It will be used as the main image for the front page when this exhibit is the newest, and it will be the banner of the exhibit's page.</p>
<table>
<tr>
<td style="text-align:center"><label>Caption: </label></td>
<td><input name="fcaption" value="<?php echo $fcaption; ?>" type="text" size="50"/></td>
</tr>
<tr>
<td style="text-align:center"><label>Artist: </label></td>
<td><input name="fartist" value="<?php echo $fartist; ?>" type="text" size="50"/></td>
</tr>
<tr>
<td style="text-align:center"><label>Medium: </label></td>
<td><input name="fmedium" value="<?php echo $fmedium; ?>" type="text" size="50"/></td>
</tr>
</table>
<br/>
</div>
<h3 class="hndle ui-sortable-handle"><span>Artist</span></h3>
<p>Make sure to set The Artist image on the right. It will be displayed on the left column of the exhibit page.</p>
<table>
<tr>
<td style="text-align:center"><label>Name(s): </label></td>
<td><input name="aname" value="<?php echo $aname; ?>" type="text" size="50"/></td>
</tr>
<tr>
<td style="text-align:center" valign="top"><label>Description: </label></td>
<td><textarea name="adesc" cols="50" rows="4"><?php echo $adesc; ?></textarea></td>
</tr>
<tr>
<td style="text-align:center"><label>Website: </label></td>
<td><input name="awebsite" value="<?php echo $awebsite; ?>" type="text" size="50"/></td>
</tr>
</table>
| dd4afda63d51c69247f39c852f949576f169e2bb | [
"PHP"
] | 3 | PHP | cahweb/events-cpt | 12a1c90ecc188e9e884e2c9baa25d6f47fa5250c | 29a299e605abdd3315b3258291ca0664c766c27a |
refs/heads/master | <repo_name>Flogac/Algogen<file_sep>/src/pobj/arith/Constante.java
package pobj.arith;
import pobj.arith.Expression;
public final class Constante implements Expression{
final double value;
public Constante(double valeur){
value = valeur;
}
public double eval( EnvEval e){
return value;
}
public double getValue( ) {
return value;
}
public String toString(){
return (value + "\n" );
}
}
<file_sep>/src/pobj/algogen/Individu.java
package pobj.algogen;
import java.util.Random;
/**
*
* Creates an object Individu with properties double valeurPropre and fitness
*/
public class Individu {
private double valeurPropre;
private double fitness = 0.0;
/**
* Creates the Individu by give it a random value between 0 and 1 as valeurPropre
*/
public Individu(){
Random r = new Random();
valeurPropre = r.nextDouble();
}
/**
* Creates the Individu by set parameters
* @param vp double, valeur propre of the object
* @param f double, fitness of the object
*/
public Individu(double vp, double f){
valeurPropre = vp;
fitness = setFitness(f);
// System.out.println(toString());
}
/**
*
* @param double newFit, the new fitness newFit
* @return double fitness
*/
public double setFitness(double newFit){
fitness = newFit;
return fitness;
}
/**
* Creates string with the properties of the Individu
*/
@Override public String toString(){
return "Fitness = " + getFitness() + ", valeurPropre = " + getValeurPropre();
}
/**
*
* @return double valeurPropre
*/
public double getValeurPropre(){
return valeurPropre;
}
/**
*
* @return double fitness
*/
public double getFitness(){
return fitness;
}
public void muter(){
Random r = new Random();
fitness = fitness * ( 0.9 + ( r.nextDouble() % 2000 ) / 1);
}
public Individu croiser( Individu autre ){
Random r = new Random();
return new Individu( r.nextDouble() , (fitness + autre.getFitness()) / 2 );
}
}
<file_sep>/src/pobj/arith/EnvEval.java
package pobj.arith;
public final class EnvEval{
private double[] variables;
private int tailleMax;
private int taille;
public EnvEval(int taillemax){
tailleMax = taillemax;
variables = new double[tailleMax];
taille = 0;
}
public void setVariable(int indexVariable, double val){
variables[indexVariable] = val;
}
public double getValue(int indexVariable){
return variables[indexVariable];
}
public String toString(){
StringBuilder retour = new StringBuilder();
retour.append("Les variables sont:\n");
for( int i = 0 ; i < taille ; i++ ) retour.append( i + " : " + variables[i]);
return retour.toString();
}
}
<file_sep>/src/pobj/algogen/Population.java
package pobj.algogen;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import pobj.algogen.doubles.IndividuDouble;
/**
* Modification of class PopulationArray using dynamic arrays
*/
public class Population{
private static ArrayList<IIndividu> individus;
private static int size = 0;
/**
* Creates population of given size and add to dynamic array
* @param POP_SIZE int, size of population
*/
public Population(int POP_SIZE) {
setIndividus(new ArrayList<IIndividu>());
for (int i = 0; i < POP_SIZE; i++){
IIndividu I = new IndividuDouble();
add(I);
}
size = POP_SIZE;
// System.out.println(individus.toString());
}
public Population() {
setIndividus(new ArrayList<IIndividu>());
// System.out.println(individus.toString());
}
public int getSize() {
return getIndividus().size();
}
/**
* Add the individu to the array
* @param iIndividu Individu
*/
public static void add(IIndividu i) {
getIndividus().add(i);
size++;
}
public String getString(ArrayList<IIndividu> individuList) {
String individuString = " ";
for (IIndividu s : individuList)
individuString += s + "\n";
return individuString;
}
public String getString() {
String individuString = " ";
for (IIndividu s : getIndividus())
individuString += s + "\n";
return individuString;
}
public void evaluer(Environnement cible){
System.out.println("evaluer");
Population oldPop = this;
for (int i=0; i < oldPop.getIndividus().size(); i++){
double newFit = cible.eval(oldPop.getIndividus().get(i));
oldPop.getIndividus().get(i).setFitness(newFit);
}
Collections.sort(oldPop.getIndividus());
//Population.setIndividus(individus);
Population newPop = oldPop.reproduire();
setIndividus(newPop.getIndividus());
this.muter( 0.1 );
}
public void muter(double prob){
Random r = new Random();
for (int i=1; i < getIndividus().size(); i++){
double rand = r.nextDouble();
if( rand < prob ){ getIndividus().get(i).muter();
}
}
}
private Population reproduire(){
System.out.println("reproduire");
int max = getIndividus().size();
int best = (int) (getIndividus().size()*0.2);
int rest = getIndividus().size() - best;
System.out.println(best + " " + rest);
ArrayList<IIndividu> oldList = Population.getIndividus();
Population retour = new Population();
for (int i = max-1; i >= 0; i--){
if (i < best){
retour.add(oldList.get(max - 1 -i).Clone());
}
else{
Random rand = new Random();
IIndividu i1 = oldList.get(max-1-rand.nextInt(best));
IIndividu i2 = oldList.get(max-1-rand.nextInt(best));
retour.add(i1.croiser(i2).Clone());
}
}
return retour;
}
public static ArrayList<IIndividu> getIndividus() {
return individus;
}
public static void setIndividus(ArrayList<IIndividu> individus) {
Population.individus = individus;
}
}<file_sep>/src/pobj/algogen/PopulationFactory.java
package pobj.algogen;
//public class PopulationFactory {
//
// static PopulationArray individus;
//
// public static PopulationArray createRandomPopulation(int size){
// individus = new PopulationArray(size);
// return individus;
// }
// public static String getString(PopulationArray indArr){
//
// return individus.toString();
// }
/**
* Creates a population by calling the class Population
*
*/
public class PopulationFactory {
static Population individus;
/**
* Calls class Population with the population size as argument
* @param size int, size of population
* @return Population individus
*/
public static Population createRandomPopulation(int size){
individus = new Population(size);
return individus;
}
/**
* Calls class Population.getString
* @param indArr Population, Population dynamic array
* @return String
*/
public static String getString(Population indArr){
return individus.getString();
}
}
<file_sep>/src/pobj/algogen/doubles/IndividuDouble.java
package pobj.algogen.doubles;
import java.util.Random;
import pobj.algogen.IIndividu;
import java.lang.*;
/**
*
* Creates an object Individu with properties double valeurPropre and fitness
*/
public class IndividuDouble implements IIndividu{
private double valeurPropre;
private double fitness = 0.0;
/**
* Creates the Individu by give it a random value as valeurPropre
*/
public IndividuDouble(){
Random r = new Random();
valeurPropre = r.nextDouble();
}
/**
* Creates the Individu by set parameters
* @param vp double, valeur propre of the object
* @param f double, fitness of the object
*/
public IndividuDouble(double vp, double f){
valeurPropre = vp;
setFitness(f);
// System.out.println(toString());
}
/**
*
* @param double newFit, the new fitness newFit
* @return double fitness
*/
public void setFitness(double newFit){
fitness = newFit;
}
/**
* Creates string with the properties of the Individu
*/
@Override public String toString(){
return "Fitness = " + getFitness() + ", valeurPropre = " + getValeurPropre();
}
/**
*
* @return double valeurPropre
*/
public Object getValeurPropre(){
return valeurPropre;
}
/**
*
* @return double fitness
*/
public double getFitness(){
return fitness;
}
public int compareTo( IIndividu o){
return Double.compare(fitness, o.getFitness() );
}
public IIndividu Clone(){
return new IndividuDouble( valeurPropre , fitness );
}
public void muter(){
double vp = (double) getValeurPropre();
valeurPropre = 0.9*vp;
}
public IIndividu croiser(IIndividu autre){
double vp = (double) autre.getValeurPropre();
double newVP = (valeurPropre + vp)/2;
IIndividu newIndividu = new IndividuDouble(newVP, fitness);
return newIndividu;
}
}<file_sep>/src/pobj/algogen/PopulationMain.java
package pobj.algogen;
import java.util.Arrays;
import pobj.algogen.doubles.IndividuDouble;
import pobj.algogen.doubles.ValeurCible;
/**
*
* @author Tilde
*
*The main class which takes the size of the population as argument.
*Calls PopulationFactory
*
*/
public class PopulationMain {
static int taille;
static Population popArr;
public static void main(String[] args) {
//taille = Integer.parseInt(args[0]);
taille = 8;
PopulationFactory popFact = new PopulationFactory();
popArr = popFact.createRandomPopulation(taille);
ValeurCible environnement = new ValeurCible(0.6);
popArr.evaluer( environnement );
//System.out.println(Population.getString());
//Testing the method muter() and croiser(Individu autre)
IIndividu I = new IndividuDouble();
System.out.println(I.toString());
I.muter();
System.out.println("Mutated: " + I.toString());
IIndividu autre = new IndividuDouble();
IIndividu newIndv = I.croiser(autre);
System.out.println("Parent 1: " + I.toString());
System.out.println("Parent 2: " + autre.toString());
System.out.println("Child: " + newIndv.toString());
}
} | 3ac3edc60759a0ffbc65be38f3c06f3b5f8c1821 | [
"Java"
] | 7 | Java | Flogac/Algogen | 6ff2083e5a5606a3255bfad7159dfc2dff7775ff | 8bdb2f2b9f9037efac0e6a6b11a061c6a9d25bbb |
refs/heads/master | <file_sep>import os
consumer_key = os.environ.get("consumer_key", None)
consumer_secret = os.environ.get("consumer_secret", None)
access_token = os.environ.get("access_token", None)
access_token_secret = os.environ.get("access_token_secret", None)
account = os.environ.get("account", None)
<file_sep>from env_vars import *
from keywords import keywords
from time import sleep
import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
def check_tweets():
tweets = api.user_timeline(account, count=1)
text = tweets[0].text
found = False
for i in keywords:
if i in text.lower():
api.retweet(tweets[0].id)
print("RT:\n%s" % text)
found = True
if not found:
print("No keywords found:\n%s" % text)
try:
print("Tweet URL: %s" % tweets[0].entities["urls"][0]["url"])
except:
pass
sleep(90)
check_tweets()
check_tweets()
print("Running...")
<file_sep>keywords = ["cancel", "close"]
<file_sep># jeffco-closures-bot
A simple python bot to retweet any tweets relating to school closures or cancellations from a given Twitter account
| 3edc1d2ae89836a7894b667d669e6ac46cbc7e81 | [
"Markdown",
"Python"
] | 4 | Python | jackdalton/jeffco-closures-bot | 725fc88e0498062b2f8252bc1180ec45b7799058 | cafc4f34aa8dcc3f68414aa43b20cfb26e743e3e |
refs/heads/master | <repo_name>StevenAtkinson/Mamoru-Complete<file_sep>/IP Games DEV/Assets/Scripts/Ships.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Ships : MonoBehaviour
{
public int Score = 0;
public ShieldHealthBar ShieldBar;
public Shield playerShield;
public Transform SheildIcon;
public Transform HealthIcon;
public int PowerUp;
public shipType shipType;
protected float health;
protected Vector2 acceleration;
protected float bulletSpeed;
protected float lazerSpeed;
protected float bulletCoolDown;
protected float lazerCoolDown;
protected float bulletLastFired;
protected float lazerLastFired;
protected float bulletDamage;
protected float lazerDamage;
public Rigidbody2D RB;
public GameObject bulletPrefab;
public GameObject lazerPrefab;
public BossHealthBar bossHealthBar;
public HealthBar playerHealthBar;
public enum Direction
{
up,
down,
}
[HideInInspector]
public Direction direction = Direction.up;
// Start is called before the first frame update
protected virtual void Start()
{
initialiseShip();
}
// Update is called once per frame
void Update()
{
TakeInput();
}
private void initialiseShip()
{
shipData data = GameManager.shipDataDictionary[shipType];
health = data.health;
acceleration = data.acceleration;
bulletSpeed = data.bulletSpeed;
lazerSpeed = data.lazerSpeed;
bulletCoolDown = data.bulletCoolDown;
lazerCoolDown = data.lazerCoolDown;
bulletDamage = data.bulletDamage;
lazerDamage = data.lazerDamage;
}
protected virtual void TakeInput()
{
}
protected virtual void Shoot()
{
}
protected virtual void Shoot2()
{
}
protected void TakeDamagePlayer(float damage)
{
FindObjectOfType<AudioManager>().Play("ShipHit");
playerShield.shieldOff();
ShieldBar.setInActive();
health -= damage;
playerHealthBar.playerHealth = health;
if (health <= 0)
{
Kill();
}
}
public void TakeDamageBoss(float damage)
{
health -= damage;
bossHealthBar.bossHealth = health;
if (health <= 0)
{
Kill();
}
}
protected void TakeDamageEnemy(float damage)
{
health -= damage;
if (health <= 0)
{
Kill();
}
}
protected void Kill()
{
Destroy(this.gameObject);
FindObjectOfType<AudioManager>().Play("ShipExplosion");
{
PowerUp = Random.Range(1, 10);
if (PowerUp == 3)
{
Instantiate(SheildIcon, transform.position, SheildIcon.rotation);
}
if (PowerUp == 2)
{
Instantiate(HealthIcon, transform.position, HealthIcon.rotation);
}
}
}
}
<file_sep>/IP Games DEV/Assets/Scripts/HealthBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
// This controls the player health bar
public class HealthBar : MonoBehaviour
{
public Slider PHSlider;
public Text Health;
public float playerHealth;
// Start is called before the first frame update
private void Start()
{
playerHealth = GameManager.shipDataDictionary[shipType.Player].health;
}
public void Update()
{
PHSlider.value = playerHealth;
Health.text = "Health: " + playerHealth;
}
}<file_sep>/IP Games DEV/Assets/Scripts/BGController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// this script controls the scroll of the background
public class BGController : MonoBehaviour
{
private float speed = 2.5f;
public GameObject BackGroundPrefab;
public static BGController singleton;
private void Awake()
{
singleton = this;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
scrollBG();
}
void scrollBG()
{
foreach(Transform t in this.transform)
{
Vector2 pos = t.transform.position;
pos.y -= speed * Time.deltaTime;
t.transform.position = pos;
}
}
public void spawnBG()
{
GameObject go = this.transform.GetChild(0).gameObject;
BG b = go.GetComponent<BG>();
Transform t = b.spawnPoint;
Instantiate(BackGroundPrefab, t.position, Quaternion.identity, this.transform);
Destroy(go);
}
}
<file_sep>/IP Games DEV/Assets/Scripts/SpawnerAztec.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
// This is where the enemies are spawned from for the Aztec level
public class SpawnerAztec : MonoBehaviour
{
public GameObject enemy1;
public GameObject enemy2;
public GameObject enemy3;
public GameObject enemy4;
public GameObject boss;
public GameObject LevelComplete;
public GameObject GameOverText;
int spawnActionIndex;
float randX;
public float spawnRate = 5f;
Vector2 spawnPoint;
float nextSpawn = 0.0f;
int enemyCounter = 0;
bool hasAllSpawned = false;
bool hasBossSpawned = false;
bool BossDestroyed = false;
// Start is called before the first frame update
void Awake()
{
boss.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
// this ends the game is the player has been destroyed
if (GameObject.FindWithTag("Player") == null)
{
gameOver();
}
// this loads the next level if the boss has been spawned and destroyed
if (hasBossSpawned && BossDestroyed)
{
LevelComplete.SetActive(true);
Invoke("loadNextLevel", 4);
}
// this checks if the boss has been destroyed after it has spawned
if (hasBossSpawned)
{
if (GameObject.FindWithTag("Boss") == null)
{
BossDestroyed = true;
}
}
if (hasAllSpawned)
{
return;
}
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
randX = Random.Range(-1.5f, 1.5f);
spawnPoint = new Vector2(randX, transform.position.y);
Instantiate(enemy1, spawnPoint, Quaternion.identity);
enemyCounter++;
Instantiate(enemy2, spawnPoint, Quaternion.identity);
enemyCounter++;
if (enemyCounter > 28)
{
Instantiate(enemy3, spawnPoint, Quaternion.identity);
enemyCounter++;
Instantiate(enemy4, spawnPoint, Quaternion.identity);
enemyCounter++;
}
// if the enemy counter is greater than 30 then stop spawning enemies and spawn the boss
if (enemyCounter > 38 )
{
Invoke ("spawnBoss", 6);
hasAllSpawned = true;
}
}
}
// this function spawns the boss
private void spawnBoss()
{
boss.gameObject.SetActive(true);
hasBossSpawned = true;
}
// this function loads the next level and is called once the boss has been spawned and destroyed
private void loadNextLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
// this displays the game over text and returns to the main menu if the player has been destroyed
void gameOver()
{
GameOverText.SetActive(true);
Invoke("mainMenu", 5);
}
// this loads the main menu
void mainMenu()
{
SceneManager.LoadScene("Start Screen");
}
}<file_sep>/IP Games DEV/Assets/Scripts/ShieldHealthBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class ShieldHealthBar : MonoBehaviour
{
public Slider ShieldSlider;
public Text shieldText;
// Start is called before the first frame update
private void Start()
{
ShieldSlider.value = 0;
}
public void setActive()
{
ShieldSlider.value = 4;
shieldText.text = "Shield:ON";
}
public void setInActive()
{
ShieldSlider.value = 0;
shieldText.text = "Shield:OFF";
}
public void Update()
{
}
}<file_sep>/IP Games DEV/Assets/Scripts/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
//this is a dictionary for all the ship types which includes the ships acceleration, bulletSpeed, lazerSpeed,
//bulletCoolDown, lazerCoolDown, bulletLastFired, lazerLastFired, bulletDamage, lazerDamage, and health
public static Dictionary<shipType, shipData> shipDataDictionary = new Dictionary<shipType, shipData>()
{
//acceleration, bulletSpeed, lazerSpeed, bulletCoolDown, lazerCoolDown, bulletLastFired, lazerLastFired, bulletDamage, lazerDamage, health
//
{shipType.Player, new shipData(new Vector2(10,10), 20f, 25f, 0.2f, 0.8f, 1f, 1f, 10f, 25f, 600f)},
{shipType.Enemy1, new shipData(new Vector2(8 ,8), 10f, 25f, 2f, 3f, 1f, 1f, 10f, 5f, 20f)},
{shipType.Enemy2, new shipData(new Vector2(9,9), 10f, 25f, 1f, 3f, 1f, 1f, 10f, 5f, 40f)},
{shipType.Enemy3, new shipData(new Vector2(10,10), 10f, 25f, 0.8f, 3f, 1f, 1f, 10f, 5f, 60f)},
{shipType.Enemy4, new shipData(new Vector2(10,10), 10f, 25f, 0.5f, 2f, 1f, 1f, 10f, 5f, 100f)},
{shipType.Boss, new shipData(new Vector2(10, 10), 20f, 25f, 0.4f, 1.5f, 1f, 1f, 10f, 15f, 1000f)},
};
public static GameManager singleton;
private void Awake()
{
singleton = this;
}
// this is the move list for the enemy ships
public static Dictionary<shipType, List<Move>> moveSetDictionary = new Dictionary<shipType, List<Move>>
{
{shipType.Enemy1, new List<Move>(){
new Move(KeyCode.D, 1),
new Move(KeyCode.S, 1),
new Move(KeyCode.D, 1),
new Move(KeyCode.A, 1),
}},
{shipType.Enemy2, new List<Move>(){
new Move(KeyCode.S, 1),
new Move(KeyCode.A, 1),
new Move(KeyCode.D, 1),
new Move(KeyCode.A, 1),
}},
{shipType.Enemy3, new List<Move>(){
new Move(KeyCode.D, 1),
new Move(KeyCode.S, 1),
new Move(KeyCode.W, 1),
new Move(KeyCode.A, 1),
}},
{shipType.Enemy4, new List<Move>(){
new Move(KeyCode.D, 1),
new Move(KeyCode.A, 1),
new Move(KeyCode.S, 1),
new Move(KeyCode.A, 1),
}},
{shipType.Boss, new List<Move>(){
new Move(KeyCode.S, 1),
new Move(KeyCode.A, 1),
new Move(KeyCode.W, 1),
new Move(KeyCode.D, 1),
}},
};
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
// this is the ship types which can then be assigned to the ship objects in unity
public enum shipType
{
Player,
Enemy1,
Enemy2,
Enemy3,
Enemy4,
Boss,
}
// this is the data that makes up the ship types
public class shipData
{
public Vector2 acceleration;
public float bulletSpeed;
public float lazerSpeed;
public float bulletCoolDown;
public float lazerCoolDown;
public float bulletLastFired;
public float lazerLastFired;
public float bulletDamage;
public float lazerDamage;
public float health;
public shipData(Vector2 acceleration, float bulletSpeed, float lazerSpeed, float bulletCoolDown, float lazerCoolDown, float bulletLastFired,
float lazerLastFired, float bulletDamage, float lazerDamage, float health)
{
this.acceleration = acceleration;
this.bulletSpeed = bulletSpeed;
this.lazerSpeed = lazerSpeed;
this.bulletCoolDown = bulletCoolDown;
this.lazerCoolDown = lazerCoolDown;
this.bulletLastFired = bulletLastFired;
this.lazerLastFired = lazerLastFired;
this.bulletDamage = bulletDamage;
this.lazerDamage = lazerDamage;
this.health = health;
}
}
public class Move
{
public KeyCode whichKey;
public float duration;
public Move(KeyCode whichKey, float duration)
{
this.whichKey = whichKey;
this.duration = duration;
}
}
<file_sep>/IP Games DEV/Assets/Scripts/AudioManager.cs
using UnityEngine.Audio;
using System;
using UnityEngine;
// the audio manager
public class AudioManager : MonoBehaviour
{
// Declaring the variable
public Sound[] sounds;
void Awake()
{
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
// adding volume, pitch and loop controllers
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
// Play sound function
public void Play(string name)
{
Sound s = Array.Find(sounds, sound => sound.name == name);
s.source.Play();
if (PauseMenu.GameIsPaused)
{
s.source.pitch *= .5f;
}
}
}<file_sep>/IP Games DEV/Assets/Scripts/BossHealthBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
// this script controls the boss health bar
public class BossHealthBar : MonoBehaviour
{
public Slider BossSlider;
public float bossHealth;
public Text Health;
// Start is called before the first frame update
private void Start()
{
GetComponent<Text>();
bossHealth = GameManager.shipDataDictionary[shipType.Boss].health;
}
public void Update()
{
BossSlider.value = bossHealth;
Health.text = "Boss Health: " + bossHealth;
}
}<file_sep>/IP Games DEV/Assets/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : Ships
{
public Transform BulletSpawn;
public Transform LazerSpawn;
public Transform BulletSpawn2;
public Transform LazerSpawn2;
// Start is called before the first frame update
protected override void Start()
{
base.Start();
}
// this is the code to define the keys for the player to use to contol the ship.
// WASD keys move up down left and right and K and L keys fire
protected override void TakeInput()
{
Vector2 velocity = RB.velocity;
Vector2 direction = transform.up;
if (Input.GetKey(KeyCode.W))
{
velocity.y += acceleration.y * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.S))
{
velocity.y -= acceleration.y * Time.deltaTime;
}
if (Input.GetKey(KeyCode.A))
{
velocity.x -= acceleration.x * Time.deltaTime;
}
else if (Input.GetKey(KeyCode.D))
{
velocity.x += acceleration.x * Time.deltaTime;
}
RB.velocity = velocity;
if (Input.GetKey(KeyCode.K))
{
Shoot();
}
if (Input.GetKey(KeyCode.L))
{
Shoot2();
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
// this is the code to take damage when the player collides with either boss or enemy bullets
if (collision.gameObject.tag == "EnemyBullet")
{
TakeDamagePlayer(collision.GetComponent<Bullet1>().damage);
Destroy(collision.gameObject);
}
else if (collision.gameObject.tag == "BossBullet")
{
TakeDamagePlayer(collision.GetComponent<BossBullet>().damage);
}
else if (collision.gameObject.tag == "EnemyLazer")
{
TakeDamagePlayer(collision.GetComponent<EnemyLazer>().damage);
}
// this turns on the shield when the power up is picked up
else if (collision.gameObject.tag == "ShieldIcon")
{
playerShield.shieldOn();
ShieldBar.setActive();
}
// this adds health to the player when the health power up is picked up
else if (collision.gameObject.tag == "HealthIcon")
{
health += 25;
playerHealthBar.playerHealth = health;
}
}
// this is the cannon fire code
protected override void Shoot()
{
if (Time.time > bulletLastFired + bulletCoolDown)
{
bulletLastFired = Time.time;
GameObject Bullet = Instantiate(bulletPrefab, BulletSpawn.position, Quaternion.identity);
Bullet1 b = Bullet.GetComponent<Bullet1>();
b.damage = bulletDamage;
b.speed = bulletSpeed;
FindObjectOfType<AudioManager>().Play("BulletFire");
StartCoroutine(timer());
bulletLastFired = Time.time;
GameObject Bullet2 = Instantiate(bulletPrefab, BulletSpawn2.position, Quaternion.identity);
Bullet1 c = Bullet.GetComponent<Bullet1>();
c.damage = bulletDamage;
c.speed = bulletSpeed;
FindObjectOfType<AudioManager>().Play("BulletFire");
StartCoroutine(timer());
IEnumerator timer()
{
yield return new WaitForSeconds(6);
Destroy(Bullet);
}
}
}
// this is the lazer fire control
protected override void Shoot2()
{
if (Time.time > lazerLastFired + lazerCoolDown)
{
lazerLastFired = Time.time;
GameObject Lazer = Instantiate(lazerPrefab, LazerSpawn.position, Quaternion.identity);
Lazer l = Lazer.GetComponent<Lazer>();
l.damage = lazerDamage;
l.speed = lazerSpeed;
FindObjectOfType<AudioManager>().Play("LazerFire");
StartCoroutine(timer());
lazerLastFired = Time.time;
GameObject Lazer2 = Instantiate(lazerPrefab, LazerSpawn2.position, Quaternion.identity);
Lazer m = Lazer.GetComponent<Lazer>();
m.damage = lazerDamage;
m.speed = lazerSpeed;
FindObjectOfType<AudioManager>().Play("LazerFire");
StartCoroutine(timer());
IEnumerator timer()
{
yield return new WaitForSeconds(3);
Destroy(Lazer);
}
}
}
}
<file_sep>/IP Games DEV/Assets/Scripts/Enemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// this script controls the enemy ships
public class Enemy : Ships
{
List<Move> moveSet;
Move currentMove;
int moveIndex;
float moveStartTime;
// Start is called before the first frame update
protected override void Start()
{
base.Start();
moveSet = GameManager.moveSetDictionary[shipType];
currentMove = moveSet[0];
if(direction == Direction.down)
{
acceleration.x *= -1;
acceleration.y *= -1;
}
}
private void DecideMove()
{
if (Time.time > moveStartTime + currentMove.duration)
{
moveIndex++;
if (moveIndex == moveSet.Count)
{
moveIndex = 0;
}
currentMove = moveSet[moveIndex];
moveStartTime = Time.time;
}
}
protected override void TakeInput()
{
DecideMove();
Vector2 velocity = RB.velocity;
if (currentMove.whichKey == KeyCode.W)
{
velocity.y += acceleration.y * Time.deltaTime;
}
else if (currentMove.whichKey == KeyCode.S)
{
velocity.y -= acceleration.y * Time.deltaTime;
}
if (currentMove.whichKey == KeyCode.A)
{
velocity.x -= acceleration.x * Time.deltaTime;
}
else if (currentMove.whichKey == KeyCode.D)
{
velocity.x += acceleration.x * Time.deltaTime;
}
RB.velocity = velocity;
Shoot();
Shoot2();
}
// this code makes the enemy ships take damage
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Bullet")
{
TakeDamageEnemy(collision.GetComponent<Bullet1>().damage);
ScoreCounter.scoreValue += 10;
Destroy(collision.gameObject);
}
if (collision.gameObject.tag == "Lazer")
{
TakeDamageEnemy(collision.GetComponent<Lazer>().damage);
ScoreCounter.scoreValue += 10;
}
}
// this controls the shoot function for the enemy ships
protected override void Shoot()
{
if (Time.time > bulletLastFired + bulletCoolDown)
{
bulletLastFired = Time.time;
Vector3 to = GameObject.FindGameObjectWithTag("Player").gameObject.transform.position;
GameObject Bullet = Instantiate(bulletPrefab, this.transform.position, Quaternion.identity);
Bullet.transform.rotation = Pointer.LookAt2D(this.transform.position, to);
Bullet1 b = Bullet.GetComponent<Bullet1>();
b.damage = bulletDamage;
b.speed = bulletSpeed;
StartCoroutine(timer());
FindObjectOfType<AudioManager>().Play("BulletFire");
IEnumerator timer()
{
yield return new WaitForSeconds(3);
Destroy(Bullet);
}
}
}
}
<file_sep>/IP Games DEV/Assets/Scripts/FirePattern.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// this controls the fire pattern for the boss bullets
public class FirePattern : MonoBehaviour
{
private float angle = 0f;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("Shoot", 0f, 0.1f);
}
// Update is called once per frame
private void Shoot()
{
float bulDirX = transform.position.x + Mathf.Sin((angle * Mathf.PI) / 180f);
float bulDirY = transform.position.x + Mathf.Cos((angle * Mathf.PI) / 180f);
Vector3 bulMoveVector = new Vector3(bulDirX, bulDirY, 0f);
Vector2 bulDir = (bulMoveVector - transform.position).normalized;
angle += 10f;
}
}
<file_sep>/IP Games DEV/Assets/Scripts/MainMenu.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public void Play()
{
SceneManager.LoadScene("Level Select");
}
public void Help()
{
SceneManager.LoadScene("Help");
}
public void Quit()
{
Application.Quit();
}
public void Highscore()
{
SceneManager.LoadScene("High Score Table");
}
public void mainMenu()
{
SceneManager.LoadScene("Start Screen");
}
}
<file_sep>/IP Games DEV/Assets/Scripts/Shield.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// this script controls the shield
public class Shield : MonoBehaviour
{
public GameObject shield;
public bool shieldActive;
// Start is called before the first frame update
void Start()
{
shieldActive = false;
shield.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
// if hit by an enemy bullet shield is turned off
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "EnemyBullet")
{
Destroy(collision.gameObject);
shieldOff();
}
else if (collision.gameObject.tag == "BossBullet")
{
Destroy(collision.gameObject);
shieldOff();
}
}
public void shieldOn()
{
shield.SetActive(true);
shieldActive = true;
}
public void shieldOff()
{
FindObjectOfType<AudioManager>().Play("ShieldOff");
shield.SetActive(false);
shieldActive = false;
}
public bool ShieldActive
{
get
{
return shieldActive;
}
set
{
shieldActive = value;
}
}
}
<file_sep>/IP Games DEV/Assets/Scripts/Pointer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pointer
{
public static Quaternion LookAt2D(Vector2 from, Vector2 to)
{
Vector3 diff = to - from;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
return Quaternion.Euler(0f, 0f, rot_z - 90);
}
}
<file_sep>/IP Games DEV/Assets/Scripts/LevelSelect.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
// level select script
public class LevelSelect : MonoBehaviour
{
public void Level1 ()
{
SceneManager.LoadScene("CyberSP");
}
public void Level2()
{
SceneManager.LoadScene("NordicSP");
}
public void Level3()
{
SceneManager.LoadScene("AztecSP");
}
public void Level4()
{
SceneManager.LoadScene("AtlantisSP");
}
public void Level5()
{
SceneManager.LoadScene("EgyptianSP");
}
public void Level6()
{
SceneManager.LoadScene("MarsSP");
}
public void startButton()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
| f4f2868a5a153fed245880c9511a3de76fb3ef6c | [
"C#"
] | 15 | C# | StevenAtkinson/Mamoru-Complete | a9e18f14f7755bdf5ff46da46345e18eeef0d295 | 44c78a06a495a8443137e6031e581ccff17cf465 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import os.path as path
class objeto():
def menu(self):
print "\n"
print "BIENVENIDO \n"
print "1. Agregar \n"
print "2. Mostrar \n"
print "3. Editar \n"
print "4. Eliminar \n"
print "5. Salir \n"
menu = int(raw_input("Que opcion quieres:"))
print "\n"
while menu > 5 or menu == 0:
menu = int(raw_input("Por favor marque como se le indica arriba:"))
print "\n"
return menu
def entra(self, menu):
if path.exists("texto2.txt"):
cantidad = int(raw_input("cantidad de empleados:"))
else:
open("texto2.txt", "a")
cantidad = int(raw_input("cantidad de empleados:"))
lista = [cantidad]
return lista
def procesa(self, lista):
cantidad = lista[0]
archivo = open("texto2.txt", "a")
finalArchivo = archivo.tell()
# contenido = archivo.read()
# print contenido
for i in range(cantidad):
archivo.seek(finalArchivo)
nombre = str(raw_input("Nombre:"))
apellido = str(raw_input("Apellido:"))
cedula = str(raw_input("Cedula:"))
edad = str(raw_input("Edad:"))
codigo = str(raw_input("Codigo del empleado:"))
estado = int(raw_input("si esta activo marque 1 si no masrque 0:"))
while estado > 1:
estado = int(raw_input("por favor marque como se le indico arriba necio:"))
estado = str(estado)
datos = [cedula, " , ", nombre," , ",apellido," , ", edad," , ", codigo," , ", estado, "\n"]
archivo.writelines(datos)
archivo.seek(finalArchivo)
menu = data.menu()
data.opcciones(menu)
# newContent = archivo.read()
# print newContent
def mostrar(self):
total = []
empleaActivo = []
empleaInactivo = []
archivo = open("texto2.txt", "r")
for line in archivo.readlines():
base = line.split(',')
activo = base[5]
cedula = base[0]
nombre = base[1]
apellido = base[2]
edad = base[3]
codigo = base[4]
activo = int(activo)
if activo == 1:
array = [cedula, nombre, apellido, edad, codigo]
empleaActivo.append(array)
else:
array = [cedula, nombre, apellido, edad, codigo]
empleaInactivo.append(array)
for x in empleaActivo:
print ".ACTIVO."
print "\n"
print "Cedula:", x[0]
print "\n"
print "Nombre:", x[1]
print "\n"
print "Apellido:", x[2]
print "\n"
print "Edad:", x[3]
print "\n"
print "Codigo:", x[4]
print "\n"
print "_____________________________"
print "\n"
for x in empleaInactivo:
print ".INACTIVO."
print "\n"
print "Cedula:", x[0]
print "\n"
print "Nombre:", x[1]
print "\n"
print "Apellido:", x[2]
print "\n"
print "Edad:", x[3]
print "\n"
print "Codigo:", x[4]
print "\n"
menu = data.menu()
data.opcciones(menu)
def editar(self):
archivo1 = open("texto2.txt", "r")
archivo = open("texto2.txt", "r")
print "Estos son los empleados que existen."
print "\n"
for line in archivo1.readlines():
array1 = line.split(',')
base = array1[0]
cedula1 = array1[0]
nombre = array1[1]
apellido = array1[2]
edad = array1[3]
codigo = array1[4]
print "Cedula", cedula1 , "Nombre:", nombre , "Apellido:", apellido , "Edad:", edad , "Codigo", codigo
print "\n"
print "Inglesa el numero de cedula para editar datos del empleado."
print "\n"
cedula = int(raw_input("Numero De Cedula:"))
archivo = open("texto2.txt", "r")
for line in archivo.readlines():
array = line.split(',')
arrayCedula = array[0]
arrayCedula = int(arrayCedula)
if cedula == arrayCedula:
c = arrayCedula
archivo.close()
break
else:
c = 0
if c > 1:
archivo = open("texto2.txt", "r")
i = 0;
masEmpleados = []
for line in archivo.readlines():
array = line.split(',')
arrayCedula = array[0]
arrayCedula = int(arrayCedula)
if cedula == arrayCedula:
print "paso cedula"
print "\n"
print "Que quiere modificar:"
print "Nombre = 1."
print "Apellido = 2."
print "Edad = 3."
print "Codigo = 4."
print "\n"
mini = int(raw_input("Que quieres modificar:"))
while mini == 0 or mini > 4:
mini = int(raw_input("Por favor marque como se le indica arriba:"))
if mini == 1:
nombre = str(raw_input("Nombre:"))
newCedula = str(array[0])
datos = [newCedula, " , ", nombre," , ",array[2]," , ", array[3]," , ", array[4]," , ", array[5]]
masEmpleados.append(datos)
print "\n"
print "Se modifico el nombre de la persona."
print "\n"
#return masEmpleados
if mini == 2:
apellido = str(raw_input("Apellido:"))
newCedula = str(array[0])
datos = [newCedula, " , ", array[1]," , ",apellido," , ", array[3]," , ", array[4]," , ", array[5]]
masEmpleados.append(datos)
print "\n"
print "Se modifico el apellido de la persona."
print "\n"
if mini == 3:
edad= str(raw_input("Edad:"))
newCedula = str(array[0])
datos = [newCedula, " , ", array[1]," , ",array[2]," , ", edad," , ", array[4]," , ", array[5]]
masEmpleados.append(datos)
print "\n"
print "Se modifico la edad de la persona."
print "\n"
if mini == 4:
codigo = str(raw_input("Codigo:"))
newCedula = str(array[0])
datos = [newCedula, " , ", array[1]," , ",array[2]," , ", array[3]," , ", codigo," , ", array[5]]
masEmpleados.append(datos)
#return masEmpleados
print "\n"
print "Se modifico el codigo de la persona."
print "\n"
else:
datos = [array[0], " , ", array[1]," , ",array[2]," , ", array[3]," , ", array[4]," , ", array[5]]
masEmpleados.append(datos)
else:
print "No exixte ese numero de cedula."
print "\n"
if c > 1:
c = 0
for datos in masEmpleados:
if c != 1:
file = open("texto2.txt", "w")
finalArchivo = file.tell()
file.seek(finalArchivo)
file.writelines(datos)
file.seek(finalArchivo)
c = 1
else:
fali = open("texto2.txt", "a")
finalArchivo = fali.tell()
fali.seek(finalArchivo)
fali.writelines(datos)
fali.seek(finalArchivo)
menu = data.menu()
data.opcciones(menu)
def eliminar(self):
contador = 0
archivo1 = open("texto2.txt", "r")
archivo = open("texto2.txt", "r")
print "Estos son los empleados que existen"
print "\n"
for line in archivo1.readlines():
array1 = line.split(',')
base = array1[0]
cedula1 = array1[0]
nombre = array1[1]
apellido = array1[2]
edad = array1[3]
codigo = array1[4]
print "Cedula", cedula1 , "Nombre:", nombre , "Apellido:", apellido , "Edad:", edad , "Codigo", codigo
print "\n"
print "Escriba el numero de cedula del empleado que quiera eliminar."
print "\n"
cedula = int(raw_input("Cedula:"))
for line in archivo.readlines():
array = line.split(',')
arrayCedula = array[0]
arrayCedula = int(arrayCedula)
if cedula == arrayCedula:
c = arrayCedula
archivo.close()
break
else:
c = 0
if c > 1:
print "\n"
print "_______________________________________________________________________________________________"
print "\n"
print "Si deseas eliminar este empleado marque 1 si no marque 0."
print "\n"
negar = int(raw_input("Deseas eliminar este empleado:"))
print ("\n")
while negar > 1:
negar = int(raw_input("Idiota marque bien:"))
print "\n"
if negar == 1:
negar1 = int(raw_input("Esta completamente seguro que quiere eliminarlo:"))
print "_____________________________________________________________"
print "\n"
while negar1 > 1:
negar1 = int(raw_input("Idiota marque bien:"))
print "\n"
if negar1 == 1:
archivo = open("texto2.txt", "r")
i = 0;
masEmpleados = []
for line in archivo.readlines():
contador = contador + 1
array = line.split(',')
arrayCedula = array[0]
arrayCedula = int(arrayCedula)
if cedula == arrayCedula:
base = array[0]
cedula1 = array[0]
nombre = array[1]
apellido = array[2]
edad = array[3]
codigo = array1[4]
print "Cedula:", cedula1 , "Nombre:", nombre , "Apellido:", apellido , "Edad:", edad , "Codigo", codigo
print "\n"
print "________________________________________________________________________________________________"
print "\n"
else:
datos = [array[0], " , ", array[1]," , ",array[2]," , ", array[3]," , ", array[4]," , ", array[5]]
masEmpleados.append(datos)
else:
pass
else:
pass
else:
print "No exixte ese numero de cedula."
print "\n"
if contador > 0:
if c > 1 and negar1 == 1:
c = 0
for datos in masEmpleados:
if c != 1:
file = open("texto2.txt", "w")
finalArchivo = file.tell()
file.seek(finalArchivo)
file.writelines(datos)
file.seek(finalArchivo)
c = 1
else:
fali = open("texto2.txt", "a")
finalArchivo = fali.tell()
fali.seek(finalArchivo)
fali.writelines(datos)
fali.seek(finalArchivo)
else:
print "_______________________________"
print "\n"
print "No se elimino ningun empleado."
print "\n"
print "_______________________________"
pass
menu = data.menu()
data.opcciones(menu)
def opcciones(self, menu):
if menu == 1:
data1 = data.entra(menu)
procesa1 = data.procesa(data1)
if menu == 2:
data.mostrar()
if menu == 5:
repetir = 1
while repetir != 0:
print "Si en verdad deseas salir marque 0 si deseas volver a las opcciones marque 1:\n"
repetir = int(raw_input("1 o 0:"))
if repetir == 1:
data.menu()
print "\n"
while repetir > 1:
print "Por favor marque como se le indica arriba gracias.\n"
repetir = int(raw_input("1 o 0:\n"))
if repetir == 1:
data.menu()
if menu == 3:
data.editar()
if menu == 4:
data.eliminar()
data = objeto()
#menu = data.menu()
def mein():
menu = data.menu()
data.opcciones(menu)
| c8e82d9902ed9b1294a8891c154d7fb09016a8aa | [
"Python"
] | 1 | Python | johnsi15/EvaluacionPytohn | cb266e7b432dd762f4a986f730b4a1dc3e9628f3 | 57d896cef59540692ef92ea8a41f82dc08c3134f |
refs/heads/master | <repo_name>sumit-mundra/mac-battery-export<file_sep>/README.md
# mac-battery-export
Script to export battery statistics to a csv.
Sample cron entry can be like
0/1 * * * * /Users/xxx/checkBattery.sh /Users/xxx/checkBatteryResults.csv
<file_sep>/checkBattery.sh
#!/bin/sh
#value=`pmset -g rawbatt | grep 'FCC' | awk -F ';' '{print $4}' | awk -F ':' '{print $1; print $2}' | awk -F '=' '{print $2}' | paste -sd "," -`
final=`pmset -g rawbatt | grep 'FCC' |sed 's/:/;/g' | cut -d ";" -f 4,5,6,10 |sed 's/ //g' | tr ';' '\n' | cut -d '=' -f 2 | tr '\n' ',' | sed 's/.$//' `
i=`perl -MTime::HiRes=gettimeofday -MPOSIX=strftime -e '($s,$us) = gettimeofday(); printf "%d.%06d\n", $s, $us'`
echo "$i,$final" >> $1
| 62a0858192c8be91f593b77b362cadcb9859f4c1 | [
"Markdown",
"Shell"
] | 2 | Markdown | sumit-mundra/mac-battery-export | 7309878cb07071b8dbd4ac4c83242189a4df46c8 | 44cede33182b46f6b28eb37118423455d901c524 |
refs/heads/master | <repo_name>alexyang21/etsydemo<file_sep>/app/views/listings/seller.html.erb
<table class="table table-striped table-bordered">
<tr>
<th class="center">Image</th>
<th class="center">Name</th>
<th class="center">Description</th>
<th class="center">Price</th>
<th class="center">Action</th>
</tr>
<% @listings.each do |listing| %>
<tr>
<td>
<%= image_tag listing.image.url(:thumb) %>
</td>
<td><%= listing.name %></td>
<td><%= listing.description %></td>
<td><%= number_to_currency(listing.price) %></td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li><%= link_to "View", listing, class: "btn btn-link" %></li>
<li><%= link_to "Edit", edit_listing_path(listing), class: "btn btn-link" %></li>
<li><%= link_to 'Destroy', listing, method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-link" %></li>
</ul>
</div>
</td>
</tr>
<% end %>
</table>
<br>
<% if user_signed_in? %>
<%= link_to 'New Listing', new_listing_path, class: "btn btn-link", data: { no_turbolink: true } %>
<% end %> | 846896ca257402a48383c2c2685ce59d1f709974 | [
"Ruby"
] | 1 | Ruby | alexyang21/etsydemo | 4590398f445767193c4bd94aa00675201c9294fb | bb8a93cb08e6fe871d472ae263498152ebca2538 |
refs/heads/master | <file_sep># learn_python
python newbie, try a web project with flask, sqlite and so on
<file_sep>#! python3
# 测试sqlite3
import sqlite3
db=sqlite3.connect('d:\\sqlite3\\db\\testdb.db')
cursor=db.cursor()
cursor.execute('select * from user where score>30')
result_all=cursor.fetchall()
print(result_all)
#result1=cursor.fetchone()
#print(result1)
#cursor.execute(r"insert into user (id, name, score) values ('5', 'Tom', '69' )")
#cursor.close()
#db.commit()
#db.close()
<file_sep>#! python3
import sqlite3
print "Content-Type: text/html\n"
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>test BC</h1>"
print "<ul>"
db = sqlite3.connect('d:\\sqlite3\\db\\bctest.db')
cursor = db.cursor()
cursor.execute("SELECT * FROM bc")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()
<file_sep><html>
<head>
<title>BusinessCase查询界面</title>
</head>
<body>
<p>请输入要查询的BusinessCase的装备名称</p>
<button type="button" onclick="alert('输入装备名称,查询BC数据')">点我获取帮助</button>
<form action="/bc_result.html" method="post">
<p>请输入装备的外文或中文名称:<input name="item_id"></p>
<p><button type="submit">Check it out</button></p>
</form>
<p>{{nutzer_info.is_authenticated}}</p>
<p>hallo, dear User {{nutzer_info.id}} ! </p>
<p>powered by Python3+Flask+SQLite3, Coding by JiangZaoyun</p>
</body>
</html>
<file_sep># 先安装mysql官方驱动库 pip install mysql-connector-python
import mysql.connector
conn=mysql.connector.connect(user='root', password='<PASSWORD>', database='world')
cursor=conn.cursor()
land='North Korea'
continent='Asia'
sql_cmd="SELECT * FROM country WHERE name='%s'" %land
sql_cmd_conti="SELECT * FROM country WHERE continent='%s'" %continent
cursor.execute(sql_cmd)
result=cursor.fetchall()
for element in result:
print(element)
<file_sep>#! python3
# 测试sqlite3
import sqlite3
db=sqlite3.connect('d:\\sqlite3\\db\\tvc_box_dev.db')
cursor=db.cursor()
modell_kennnr='VW216'
projekt='SOP'
sql_cmd="SELECT * FROM fahrzeugbedarf WHERE Modell LIKE '%s' OR KennNr='%s' AND Projekt LIKE '%s' "%(modell_kennnr,modell_kennnr,projekt) # LIKE忽视大小写
cursor.execute(sql_cmd)
result_all=cursor.fetchall()
print(result_all)
#result1=cursor.fetchone()
#print(result1)
#cursor.execute(r"insert into user (id, name, score) values ('5', 'Tom', '69' )")
#cursor.close()
#db.commit()
#db.close()
<file_sep><html>
<head>
<title>车辆需求对标查询</title>
</head>
<body>
<p>请选择项目类型</p>
<button type="button" onclick="alert('请输入项目类型,获取同类型项目车辆数对标')">点我获取帮助</button>
</p>
<div></div>
<p>选择查询的项目类型,对同类型项目开展对标</p>
<form action="/fahrzeug_result.html" method="post">
<select name="projekt_typ">
<option>New</option>
<option>NF</option>
<option>PA</option>
<option>MP</option>
<option>Derivate</option>
<option>Sondermodell</option>
<option>Aggregate</option>
</select>
<button type="submit">查询对标</button></p>
</form>
</div>
<p>powered by Python3+Flask+SQLite3</p>
</body>
</html>
<file_sep># 先安装mysql官方驱动库 pip install mysql-connector-python
import mysql.connector
conn=mysql.connector.connect(user='root', password='<PASSWORD>', database='fahrzeug')
cs=conn.cursor()
sql_cmd_create='''create table fahrzeugbedarf (Nr Integer(5) primary key,
Modell VARCHAR(20),
KennNr VARCHAR(20),
Projekt VARCHAR(20),
Projekt_Art VARCHAR(15),
MGV INTEGER(2) ,
Carlines INTEGER(2))
'''
cs.execute(sql_cmd_create)
| d73d64e2b522b4576ca53c471bcbb515b9b29302 | [
"Markdown",
"Python",
"HTML"
] | 8 | Markdown | aekojiang/box_with_flask | aea0328a06c82e798d35865d041f6decb919394a | e1e8bbde7537722c7c41e6f6d6a2bae9bd168c28 |
refs/heads/master | <repo_name>vuotnguyen/full_story<file_sep>/app/src/main/java/com/example/mvp_funystory/View/Fragment/SignInFragment.java
package com.example.mvp_funystory.View.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.mvp_funystory.CallBackPresenter.CallSignIn;
import com.example.mvp_funystory.Presenter.SignInPresenter;
import com.example.mvp_funystory.R;
public class SignInFragment extends BaseFragment<SignInPresenter> implements CallSignIn {
public static final String KEY_SHOW_HOME = "KEY_SHOW_HOME" ;
private EditText edt_name,edt_pass;
public static final String TAG = SignInFragment.class.getName();
public static final String KEY_SHOW_SIGNUP = "SIGN_UP";
@Override
public SignInPresenter getMpresenter() {
return new SignInPresenter(this);
}
@Override
protected void initView() {
edt_name = findViewById(R.id.edtUser);
edt_pass = findViewById(R.id.edtPass);
findViewById(R.id.btSignIn,this);
findViewById(R.id.tvSignUp,this);
}
@Override
protected int getLayoutID() {
return R.layout.sign_in_fragment;
}
@Override
public void showRS(String rs,boolean kq) {
Toast.makeText(context,rs,Toast.LENGTH_SHORT).show();
if(kq == true){
even.callBack(KEY_SHOW_HOME,null);
}
else {
}
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.btSignIn){
mpresenter.signIn(edt_name.getText().toString(),edt_pass.getText().toString());
even.callBack(MenuDrawerFragment.KEY_SHOW_HOME,null);
}
else if(v.getId() == R.id.tvSignUp){
even.callBack(KEY_SHOW_SIGNUP,null);
}
}
}
<file_sep>/app/src/main/java/com/example/mvp_funystory/View/CallBack/CallBack.java
package com.example.mvp_funystory.View.CallBack;
public interface CallBack {
default void callBack(String key, Object data){
}
}
<file_sep>/app/src/main/java/com/example/mvp_funystory/View/activity/App.java
package com.example.mvp_funystory.View.activity;
import android.app.Application;
import androidx.room.Room;
import com.example.mvp_funystory.database.AppDB;
public class App extends Application {
protected AppDB appDB;
private static App instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
initDB();
}
private void initDB() {
appDB = Room.databaseBuilder(getApplicationContext(),AppDB.class,"database2").createFromAsset("fullstory.db").build();
}
public AppDB getAppDB() {
return appDB;
}
public static App getInstance() {
return instance;
}
}
<file_sep>/app/src/main/java/com/example/mvp_funystory/CallBackPresenter/CallSignIn.java
package com.example.mvp_funystory.CallBackPresenter;
import com.example.mvp_funystory.View.CallBack.CallBack;
public interface CallSignIn extends CallBack {
void showRS(String rs,boolean kq);
}
<file_sep>/app/src/main/java/com/example/mvp_funystory/Model/User.java
package com.example.mvp_funystory.Model;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
@Entity (primaryKeys = {"id"})
public class User {
@NonNull
@ColumnInfo(name = "id")
public int id;
@NonNull
@ColumnInfo(name = "username")
public String username;
@NonNull
@ColumnInfo(name = "password")
public String password;
@NonNull
@ColumnInfo(name = "email")
public String email;
@NonNull
@ColumnInfo(name = "status")
public int status;
}
<file_sep>/app/src/main/java/com/example/mvp_funystory/Presenter/CategoryPresenter.java
package com.example.mvp_funystory.Presenter;
import com.example.mvp_funystory.CallBackPresenter.CallCategory;
import com.example.mvp_funystory.Model.Categories;
import java.util.List;
public class CategoryPresenter extends BasePresenter<CallCategory> {
public CategoryPresenter(CallCategory callBack) {
super(callBack);
}
public List<Categories> getAllCategory(){
return null;
}
public boolean deleteCategory(int id){
return false;
}
public boolean upDateCategory(String name,String des){
return false;
}
}
<file_sep>/app/src/main/java/com/example/mvp_funystory/Presenter/SignInPresenter.java
package com.example.mvp_funystory.Presenter;
import com.example.mvp_funystory.CallBackPresenter.CallSignIn;
public class SignInPresenter extends BasePresenter<CallSignIn> {
private String rs;
private boolean kq;
public SignInPresenter(CallSignIn callBack) {
super(callBack);
}
public void signIn(String name,String pass){
if(name.equals("admin") && pass.equals("<PASSWORD>")){
rs = "Login success";
kq = true;
viewFragment.showRS(rs,kq);
}else{
rs = "sai pass or name";
kq = false;
viewFragment.showRS(rs,kq);
}
}
}
<file_sep>/app/src/main/java/com/example/mvp_funystory/View/activity/MainActivity.java
package com.example.mvp_funystory.View.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.mvp_funystory.R;
import com.example.mvp_funystory.View.CallBack.CallBack;
import com.example.mvp_funystory.View.Fragment.BaseFragment;
import com.example.mvp_funystory.View.Fragment.CommunityFragment;
import com.example.mvp_funystory.View.Fragment.HomeFragment;
import com.example.mvp_funystory.View.Fragment.LibraryFragment;
import com.example.mvp_funystory.View.Fragment.MenuDrawerFragment;
import com.example.mvp_funystory.View.Fragment.PersonalFragment;
import com.example.mvp_funystory.View.Fragment.SignInFragment;
import com.example.mvp_funystory.View.Fragment.SignUpFragment;
import com.example.mvp_funystory.View.Fragment.SplashFragment;
import com.example.mvp_funystory.View.Fragment.CategoryFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements CallBack {
private String currenTag;
private BottomNavigationView botomMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
botomMenu = findViewById(R.id.menu_bot);
botomMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.navigation_home:
showFragment(HomeFragment.TAG);
return true;
case R.id.navigation_theLoai:
showFragment(CategoryFragment.TAG);
return true;
case R.id.navigation_library:
showFragment(LibraryFragment.TAG);
return true;
case R.id.navigation_congDong:
showFragment(CommunityFragment.TAG);
return true;
case R.id.navigation_caNhan:
showFragment(PersonalFragment.TAG);
return true;
}
return false;
}
});
showFragment(SplashFragment.TAG);
}
public void showFragment(String tag) {
try {
Class<?> clazz = Class.forName(tag);
BaseFragment baseFragment = (BaseFragment) clazz.newInstance();
baseFragment.setCallBack(this);
currenTag = tag;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.ln_main,baseFragment,tag).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void callBack(String key, Object data) {
switch (key){
case SplashFragment.KEY_SHOW_SIGNIN:
showFragment(SignInFragment.TAG);
//botomMenu.setVisibility(View.GONE);
break;
case SignInFragment.KEY_SHOW_SIGNUP:
showFragment(SignUpFragment.TAG);
botomMenu.setVisibility(View.GONE);
break;
case MenuDrawerFragment.KEY_SHOW_HOME:
showFragment(HomeFragment.TAG);
Toast.makeText(MainActivity.this,"Home",Toast.LENGTH_SHORT).show();
break;
}
}
}<file_sep>/app/src/main/java/com/example/mvp_funystory/Model/category_stories.java
package com.example.mvp_funystory.Model;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.util.Date;
@Entity(tableName = "category_stories")
public class category_stories {
@PrimaryKey
private int id;
@NonNull
@ColumnInfo(name = "category_id")
private int category_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
}
| 7cf8a880c2e2412b07fb6a334874a0d949a7dbd0 | [
"Java"
] | 9 | Java | vuotnguyen/full_story | f92859197caccee2aa336c984c5a1f1468769c8d | 579dd5faef3e5e754b0f9b50bdfd209f6f7fdd02 |
refs/heads/master | <file_sep>"""
dadjokes.py
~~~~~~~~~~~
Get and return jokes from icanhazdadjoke.com
:copyright: (c) 2017 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
import requests
import json
def get_joke():
"""Returns a joke from the WebKnox one liner API.
Returns None if unable to retrieve a joke.
"""
headers = {'Accept' : 'application/json'}
page = requests.get("https://icanhazdadjoke.com", headers=headers)
if page.status_code == 200:
joke = json.loads(page.content.decode("UTF-8"))
return joke["joke"]
return None
<file_sep>"""
catfacts.py
~~~~~~~~~~~
Get and return facts from catfact.ninja
:copyright: (c) 2017 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
import requests
import json
def get_joke():
"""Returns a joke from the WebKnox one liner API.
Returns None if unable to retrieve a joke.
"""
page = requests.get("https://catfact.ninja/fact")
if page.status_code == 200:
joke = json.loads(page.content.decode("UTF-8"))
return joke["fact"]
return None
<file_sep>"""
laughs.py
~~~~~~~~~
Functions that return jokes.
:copyright: (c) 2017 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
from random import randint
from .services import ronswanson, chucknorris, catfacts, dadjokes
NUM_SERVICES = 4
def get_joke():
"""Return a jokes from one of the random services."""
joke = None
while joke is None:
service_num = randint(1, NUM_SERVICES)
joke = load_joke(service_num)
return joke
def load_joke(service_num=1):
"""Pulls the joke from the service based on the argument.
It is expected that all services used will return a string
when successful or None otherwise.
"""
result = {
1 : ronswanson.get_joke(),
2 : chucknorris.get_joke(),
3 : catfacts.get_joke(),
4 : dadjokes.get_joke(),
}.get(service_num)
return result
<file_sep># laughs
> A python package that pulls jokes from various APIs.
[![PyPI Version][pypi-image]][pypi-url]
[![Build Status][travis-image]][travis-url]
[![Downloads Stats][pypi-downloads]][pypi-url]
[![Release Status][release-status]][pypi-url]
laughs provides a python package for generating pulling jokes from various unauthenticated
APIs around the Internet. Jokes are provided by the `get_joke()` function. The package works
with python 2 and 3.
Pull requests are welcome!
## Installation
OS X & Linux:
```sh
pip install laughs
```
or
```sh
pip3 install laughs
```
Windows:
```sh
python3 -m pip install laughs
```
## Development setup
Using laughs in your projects:
```python
import laughs
joke = laughs.get_joke() # returns a string containing a joke/quote
```
## Release History
* 0.1.0
* The first proper release
## Meta
<NAME> – [@smcallaway](https://twitter.com/smcallaway) – <EMAIL>
Distributed under the MIT license. See ``LICENSE`` for more information.
[https://github.com/seancallaway/laughs](https://github.com/seancallaway/laughs)
## Contributing
1. Fork it (<https://github.com/seancallaway/laughs/fork>)
2. Create your feature branch (`git checkout -b feature/fooBar`)
3. Commit your changes (`git commit -am 'Add some fooBar'`)
4. Push to the branch (`git push origin feature/fooBar`)
5. Create a new Pull Request
<!-- Markdown link & img dfn's -->
[pypi-image]: https://img.shields.io/pypi/v/laughs.svg
[pypi-url]: https://pypi.python.org/pypi/laughs
[travis-image]: https://api.travis-ci.org/seancallaway/laughs.svg?branch=master
[travis-url]: https://travis-ci.org/seancallaway/laughs
[pypi-downloads]: https://img.shields.io/pypi/dm/laughs.svg
[release-status]: https://img.shields.io/pypi/status/laughs.svg
<file_sep>"""
laughs.services
~~~~~~~~~~~~~~~
Functions that expose the various APIs.
:copyright: (c) 2017 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
<file_sep>"""
ronswanson.py
~~~~~~~~~~~~~
Get and return jokes from ron-swanson-quotes
:copyright: (c) 2017 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
import requests
import json
def get_joke():
"""Return a Ron Swanson quote.
Returns None if unable to retrieve a quote.
"""
page = requests.get("http://ron-swanson-quotes.herokuapp.com/v2/quotes")
if page.status_code == 200:
jokes = []
jokes = json.loads(page.content.decode(page.encoding))
return '"' + jokes[0] + '" - Ron Swanson'
return None
<file_sep>"""
laughs
~~~~~~
Pulls jokes from various APIs.
:copyright: (c) 2017 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
from .laughs import get_joke
| 88d635c5b5a5c9d7fbe2d5cd8dda597f52295265 | [
"Markdown",
"Python"
] | 7 | Python | seancallaway/laughs | e13ca6f16b12401b0384bbf1fea86c081e52143d | 53805c6ba8482b4bfb52fafaa38f0d2e6079f0da |
refs/heads/master | <repo_name>sdgdsffdsfff/monitor_for_websocket<file_sep>/app/websocket.py
# coding: utf-8
import json
import redis
def handle_websocket(ws, group):
channel = 'pps-'+group
r = redis.StrictRedis(host='localhost', port=6379, db=0)
conn_pool = redis.client.ConnectionPool()
sub = redis.client.PubSub(conn_pool)
sub.subscribe(channel)
import time
t = int(time.time())
for msg in sub.listen():
j = int(time.time()) - t
if msg['type'] == 'message' and msg['channel'] == channel:
c = json.loads(msg['data'])
for i in c:
ws.send("%s %s %s \n" % (i, j, c[i]))
<file_sep>/app/__init__.py
# coding: utf-8
import os
from cgi import parse_qs, escape
from flask import Flask
from websocket import handle_websocket
app = Flask(__name__)
app.debug = True
def my_app(environ, start_response):
path = environ["PATH_INFO"]
if path == "/data":
handle_websocket(environ["wsgi.websocket"], parse_qs(environ['QUERY_STRING']).get('group',[''])[0])
else:
return app(environ, start_response)
import views
<file_sep>/test.py
#!/usr/bin/python
#coding=utf-8
import config
import socket
import traceback
import struct
#import utils
import time
import redis
from redis.exception import ConnectionError
from logger import logger
#r = redis.StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB)
r = redis.StrictRedis(host="127.0.0.1", port=6379)
for i in xrange(1, 10000):
import random
import json
#result.append('%s|%s' % (ip, pps))
x = {}
for i in config.group1:
x[i] = random.random() * random.random() * 10000
r.publish('pps-group1', json.dumps(x))
for i in config.group2:
x[i] = random.random() * random.random() * 10000
r.publish('pps-group2', json.dumps(x))
for i in config.group3:
x[i] = random.random() * random.random() * 10000
r.publish('pps-group3', json.dumps(x))
time.sleep(1)
<file_sep>/config.py
# -*- coding: utf-8 -*-
#xiaorui.cc
group1 = ['group1-1','group1-2','group1-3','group1-4','group1-5','group1-6']
group2 = ['group2-1','group2-2','group2-3','group2-4','group2-5','group2-6','group2-7','group2-8']
group3 = ['group3-1','group3-2','group3-3','group3-4','group3-5','group3-6']
<file_sep>/README.md
## 一个flask gevent实现的websocket监控
### 这是我做过的一个全网实时监控的核心部分代码,大家可以借鉴下
* 抓取全网的交换机流量
* 调用公司的黑洞防护接口,针对攻击进行封杀或者分流攻击
* 抓到的数据,不仅入库,而且用jqplot实时绘图
* 对于超过阀值的监控类型,会进行高亮显示
```python
yum -y install redis-server
yum -y install python-dev
pip install gevent
pip install redis
end
```
作者 [@小芮][1]
[1]: https://xiaorui.cc
<file_sep>/app/views.py
# coding: utf-8
from flask import render_template
from app import app
import sys
sys.path.append("..")
import config
@app.route('/')
def index():
return render_template('index.html')
@app.route('/group1')
def group1():
return render_template('swflow.html', groupname="group1",group=config.group1)
@app.route('/group2')
def group2():
return render_template('swflow.html', groupname="group2",group=config.group2)
@app.route('/group3')
def group3():
return render_template('swflow.html', groupname="group3",group=config.group3)
| b42930dbb993157601dadbfd3c44dd5fa05c365c | [
"Markdown",
"Python"
] | 6 | Python | sdgdsffdsfff/monitor_for_websocket | f8a1bf047764086b02953e083513779dba3d7188 | ec47fadd02bc111537e5a5a578b72c5526283947 |
refs/heads/master | <file_sep># set working directory
setwd("C:/RStudio")
data <- read.table("household_power_consumption.txt", header=TRUE, sep=";", na.strings = "?", colClasses = c('character','character','numeric','numeric','numeric','numeric','numeric','numeric','numeric'))
# Transform format
data$Date <- as.Date(data$Date, "%d/%m/%Y")
# Filter data set to two days
data <- subset(t,Date >= as.Date("2007-2-1") & Date <= as.Date("2007-2-2"))
## Create the histogram
png(filename='plot1.png', width=480, height=480, units='px')
hist(data$Global_active_power, main="Global Active Power", xlab = "Global Active Power (kilowatts)", col="red")
dev.off()
| 405ac5cba367062e61d52067463e3ff23cf073c2 | [
"R"
] | 1 | R | Ronlaan/ExData_Plotting1 | a3cf27de4be1d71b1405ee4086fdefd167e02f3f | 8e49740b6882fea2bb07e9ad63d98cab31369cad |
refs/heads/master | <repo_name>preacharush/arcabolig<file_sep>/app/Http/Controllers/insertCompanyController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\company;
use App\address;
use App\city;
use App\country;
use DB;
use Auth;
class insertCompanyController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$countries = country::all();
$cities = city::all();
// dd($countries);
return view('pages/create-company', compact('countries','cities'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
// grap post and create variables
$comp_name = $request->comp_name;
$address = $request->address;
$address2 = $request->address2;
$zipcode = $request->zipcode;
$city = $request->city;
$country = $request->country;
$phone = $request->phone;
$mobil = $request->mobil;
$contactPerson = $request->contactPerson;
$contactEmail = $request->contactEmail;
$website = $request->website;
$comp_reg_nr = $request->comp_reg_nr;
// Create address
$addressData = [
'address' => $address,
'address2' => $address2,
'address2' => $address2,
'city_id' => $city
];
// Create in table and grab address ID
$address_id = DB::table('address')->insertGetId( $addressData );
// Create company with address ID
$companyData = [
'comp_reg_nr' => $comp_reg_nr,
'comp_name' => $comp_name,
'phone' => $phone,
'email' => $contactEmail,
'address_id' => $address_id
];
// Create company in table and grab company ID
$companyId = DB::table('company')->insertGetId( $companyData );
//Get user id
$userId = Auth::user()->id;
// Update user with company ID
DB::table('users')
->where('id', $userId )
->update(['company_id' => $companyId]);
// FINISH TRANSACTION
//set Company id as session variable
session(['company_id' => $companyId, 'comp_name'=>$comp_name]);
// Redirect to Settings to view the information
return redirect()->route('settings.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/app/Http/Controllers/overviewController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\company;
use App\address;
use App\city;
use DB;
use Auth;
class overviewController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
// $company = address::all();
// return $company;
// $see = $request->session()->all();
// $request->session()->put('user', 'Preacher');
// dd(Auth::user()->id);
//if get() is used ,one gets an collection which have to selected based on index or iterate throug it to get properties
// if first() is used, one gets an element, where one can point directly to the property
// return $data;
// dd($data);
return view('pages/property/property-overview');
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
// THIS WORKS--->
// $ins = DB::insert('insert into company (comp_reg_nr, comp_name, address_id)
// values (?, ?, ?)
// on duplicate key update
// comp_name = values(comp_name),
// address_id = values(address_id)'
// , ['123456','beast', 2]
// );
// dd($ins);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate(request(), [
'comp_name'=> 'required',
'address'=> 'required',
'zipcode'=> 'required',
'city'=> 'required',
'country'=> 'required',
'phone'=> 'required'
]);
// company::create(request(['comp_name', 'address']));
// DB::table('address')->insert(
// ['email' => '<EMAIL>', 'votes' => 0]
// );
$ins = DB::insert('insert into company (comp_name) values (?)', [$request->indput('comp_name')]);
dd($ins);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/database/migrations/2018_12_08_140142_create_countries_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->string('continent_a2', 2)->nullable();
$table->string('country_iso_a2', 3)->primary();
$table->string('country_iso_a3', 3)->nullable();
$table->string('fips', 4)->nullable();
$table->string('nuts', 3)->nullable();
$table->string('hasc', 2)->nullable();
$table->string('name_english', 45)->nullable();
$table->string('language', 3)->nullable();
$table->string('language_pc', 10)->nullable();
$table->boolean('has_zip_codes')->nullable();
$table->string('phone_code', 6)->nullable();
$table->string('tld', 10)->nullable();
$table->string('latitude', 10)->nullable();
$table->string('longitude', 10)->nullable();
$table->integer('altitude')->nullable();
$table->string('territory_of',3)->nullable();
$table->string('updates',1)->nullable();
$table->timestamps()->nullable();
$table->engine = 'InnoDB';
$table->collation = 'utf8_unicode_ci';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('countries');
}
}
<file_sep>/app/company.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class company extends Model
{
protected $table = 'company';
protected $fillable = ['comp_reg_nr', 'comp_name','email','phone'];
public function address() {
return $this->belongsTo(address::class, 'id', 'address_id');
}
public function users() {
return $this->hasMany(users::class);
}
public function clients() {
return $this->belongsToMany(Client::class,'company_has_clients','id','company_id');
}
}
<file_sep>/database/migrations/2018_10_06_124057_create_city_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateCityTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('city', function(Blueprint $table)
{
$table->increments('id');
$table->string('City', 100)->nullable();
$table->string('zipcode', 45)->nullable();
$table->integer('Country_id');
$table->timestamps();
$table->foreign('country_id')->references('id')->on('country')->onUpdate('CASCADE')->onDelete('CASCADE');
$table->engine = 'InnoDB';
$table->collation = 'utf8_unicode_ci';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('city');
}
}
<file_sep>/database/migrations/2018_12_08_204528_create_postal_codes_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostalCodesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('postal_codes', function (Blueprint $table) {
$table->string('country_a2', 3);
$table->string('denomination', 30)->nullable();
$table->string('format', 10)->nullable();
$table->string('Regex', 150)->nullable();
$table->boolean('fixedcode')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
$table->foreign('country_a2')->references('country_iso_a2')->on('countries')->onUpdate('CASCADE')->onDelete('CASCADE');
$table->engine = 'InnoDB';
$table->collation = 'utf8_unicode_ci';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('postal_codes');
}
}
<file_sep>/app/Http/Controllers/PagesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\company;
use App\User;
use DB;
use Auth;
class PagesController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
public function userdashboard(Request $request)
{
// dd(session());
//tjekk iff company id is null (new users only)
if ((Auth::user()->company_id) == null) {
//if company id null redirect to create company
return redirect()->route('create-company');
}
//Check if User company is set - Get compoany ID to set the session variable
if (!session()->get('company_id')) {
$companyId = DB::table('company')
->join('users','users.company_id', '=', 'company.id') // join USERS with COMPANY
->where('users.id', '=', Auth::id())
->select('company_id', 'comp_name')
->first();
//set Company id as session variable
session(['company_id' => $companyId->company_id, 'comp_name'=>$companyId->comp_name]);
}
//Get Klient company/property details to set the session variable
if (!session()->get('comp_info')) {
$properties = DB::table('clients')
->join('address', 'address.id','=', 'clients.address_id')
->join('company_has_clients','clients.id','=','company_has_clients.client_id')
->join('company','company.id','=','company_has_clients.company_id')
->join('client_has_property','clients.id', '=','client_has_property.client_id')
->join('properties','properties.id', '=', 'client_has_property.property_id')
->where('company.id', '=', session()->get('company_id'))
->select('properties.id','properties.property_unique_id','property_name')
->get();
// set properties data in array object
$properties = ['comp_info'=>$properties];
// dd($properties['comp_info']);
// dd(session()->get('comp_info'));
// dd(session()->get('comp_info')[0]);
//Set session variables
session($properties);
// dd(session());
}
return view('pages/user-dashboard',compact('companyId','comp_data'));
// stdClass Object ( [id] => 1 [property_unique_id] => 42414988 [property_name] => <NAME> Larson )
// foreach ($comp_data as $keys){
// echo $keys->property_name;
// // print_r($keys);
// echo"<br>";
// }
}
public function setActievProperty(Request $request, $id, $property_name)
{
// Check IF session Active_property is set
if (!session()->get('active_property')) {
// Set Session Active company
session(['active_property' =>[
'id'=> $id,
'comp_name'=> $property_name
]]);
}
if (session()->get('active_property')) {
//delete old active property from session
session()->forget('active_property');
//set new active_property value
session(['active_property' =>[
'id'=> $id,
'comp_name'=> $property_name
]]);
}
// dd(session('active_property')['comp_name']);
return redirect()->route('user.dashboard');
}
}
<file_sep>/app/Http/Controllers/settingsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\company;
use App\address;
use App\city;
use App\country;
use DB;
use Auth;
class settingsController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
// $company = address::all();
// return $company;
// dd($request->session()->all());
// $request->session()->put('user', 'Preacher');
// dd(Auth::user()->company_id);
$countries = country::all();
$cities = city::all();
$id = Auth::id();
$data = DB::table('address')
->join('company','company.address_id','=','address.id') //join COMPANY with ADDRESS
->join('city', 'address.city_id', '=', 'city.id') //join ADDRESS with CITY
->join('country','city.country_id','=','country.id') //join CITY with COUNTRY
->join('users','users.company_id', '=', 'company.id') // join USERS with COMPANY
->where('users.id', '=', $id)
->select('company.Comp_reg_nr','company.comp_name','company.email', 'company.phone',
'address.address','address.address2','address.district',
'city.city','city.zipcode',
'country.country','country_id',
'users.name', 'users.email as user_mail','users.id')
->first();
//if get() is used ,one gets an collection which have to selected based on index or iterate throug it to get properties
// if first() is used, one gets an element, where one can point directly to the property
// return $data;
// dd($data);
return view('pages/master-info/master-information', compact('data','cities', 'countries'));
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// company::create(request(['comp_name', 'address']));
// DB::table('address')->insert(
// ['email' => '<EMAIL>', 'votes' => 0]
// );
$ins = DB::insert('insert into company (comp_name) values (?)', [$request->indput('comp_name')]);
dd($ins);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//create variables from the request
$comp_name = $request->comp_name;
$address = $request->address;
$address2 = $request->address2;
$zipcode = $request->zipcode;
$cityId = $request->city;
$countryId = $request->country;
$phone = $request->phone;
$mobil = $request->mobil;
$contactPerson = $request->contactPerson;
$contactEmail = $request->contactEmail;
$website = $request->website;
$comp_reg_nr = $request->comp_reg_nr;
//validate
//Update statement
//this works perfectly
$update = DB::table('address')
->join('company','company.address_id','=','address.id') //join COMPANY with ADDRESS
->join('city', 'address.city_id', '=', 'city.id') //join ADDRESS with CITY
->join('country','city.country_id','=','country.id') //join CITY with COUNTRY
->join('users','users.company_id', '=', 'company.id') // join USERS with COMPANY
->where('users.id', '=', $id)
->update(['company.comp_name'=> $comp_name, 'address.address' => $address,'address.address2' =>$address2,
'company.Comp_reg_nr'=> $comp_reg_nr, 'address.city_id'=>$cityId]);
// dd($request->all());
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/app/Http/Controllers/UsersController.php
<?php
namespace App\Http\Controllers;
use DB;
use Auth;
use App\User;
use App\company;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
//get users data - company id = session company_id
if (session()->get('company_id')) {
$users = User::with('company')
->where('company_id', session()->get('company_id'))
->get();
return view('pages/users/users-show', compact('users'));
} else {
$flash = session()->flash('message', 'You need to fill company information to proceed');
return redirect('create-company');
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('pages/users/users-create', compact(''));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$id = Auth::id();
//create request variables
$name = $request->name;
$email = $request->email;
$password = $request->password;
$company_id = DB::table('company')
->join('users','users.company_id', '=', 'company.id') // join USERS with COMPANY
->where('users.id', '=', $id)
->select('users.company_id')
->first();
// User data in one array
$userData = [
'name' => $name,
'email' => $email,
'password' => <PASSWORD>($<PASSWORD>),
'company_id'=> $company_id->company_id
];
//User gets createt
$createUser = user::create($userData);
return redirect()->route('users.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::findOrfail($id);
return view('pages/users/users-edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = User::findOrfail($id);
//validate form indput
$request->validate([
'name' => 'required',
'email' => 'required|email|max:150',
'password' => '<PASSWORD>',
]);
//create variables from the request
$name = $request->name;
$email = $request->email;
$password = $request->password;
$company_id = DB::table('company')
->join('users','users.company_id', '=', 'company.id') // join USERS with COMPANY
->where('users.id', '=', $id)
->select('users.company_id')
->first();
// User data in one array
$userData = [
'name' => $name,
'email' => $email,
'password' => <PASSWORD>($<PASSWORD>),
'company_id'=> $company_id->company_id
];
// dd($userData);
// Update Data
$update = DB::table('users')
->where('users.id', '=', $user->id)
->update($userData);
return redirect()->route('users.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = User::findOrfail($id);
$update = DB::table('users')
->where('users.id', '=', $user->id)
->delete();
return redirect()->route('users.index');
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard','Pagescontroller@userdashboard')->name('user.dashboard');
Route::get('property/overview','overviewController@index')->name('user.overview');
//Settings cotrollers
Route::get('/settings','settingsController@index')->name('company.settings');
Route::resource('admin/settings','settingsController');
Auth::routes();
Route::get('/home', 'HomeController@index');
Route::get('/users/logout','Auth\Logincontroller@userlogout')->name('user.logout');
Route::prefix('admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
Route::get('/', 'AdminController@index')->name('admin.dashboard');
Route::get('/logout','Auth\AdminLoginController@logout')->name('admin.logout');
});
//create companys
Route::get('/create-company', 'insertCompanyController@index')->name('create-company');
Route::post('/create-company.create', 'insertCompanyController@create')->name('create-company.create');;
// Route::resource('/create-company','insertCompanyController');
// USERS - show - Create - Edit - Delete
Route::resource('admin/users','UsersController');
// Client - show - Create - Edit - Delete
Route::resource('admin/client','ClientController');
//property - show - Create - Edit - Delete
Route::resource('admin/properties','PropertyController');
//set active client property in session - When chossen in dropdown
Route::get('company-dashboard/{id}/{comp_name}', 'Pagescontroller@setActievProperty')->name('set-active-property');
<file_sep>/config/settings-sidebar.php
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'menu' => [[
'icon' => 'fas fa-users',
'title' => 'Brugere',
'url' => '/users',
],[
'icon' => 'fa fa-th-large',
'title' => 'XXXXXXXXXXX',
'url' => 'javascript:;',
'caret' => true,
'sub_menu' => [[
'url' => '/dashboard/v1',
'title' => 'XXXXXXXXX v1'
],[
'url' => '/dashboard/v2',
'title' => 'Dashboard v2'
]]
]
]
];
<file_sep>/app/Property.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Property extends Model
{
protected $table = 'properties';
public function client()
{
return $this->belongsToMany('App\client','client_has_property','property_id','client_id');
}
public function address()
{
return $this->belongsToMany('App\address','property_has_address','property_id','address_id');
// return $this->belongsToMany('App\address','property_has_address');
}
}
<file_sep>/app/postal_codes.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class postalcodes extends Model
{
protected $table = 'postal_codes';
protected $fillable = ['country_a2','denomination','format','Regex','fixedcode','created_at', 'updated_at'];
public function postal_code() {
return $this->belongsTo('App\countries');
}
}
<file_sep>/database/factories/UserFactory.php
<?php
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(App\country::class, function (Faker $faker) {
return [
'country' =>$faker->country,
];
});
$factory->define(App\city::class, function (Faker $faker) {
return [
'city' =>$faker->city,
'zipcode' =>$faker->postcode,
'country_id' =>$faker->numberBetween($min = 1, $max = 10)
];
});
$factory->define(App\address::class, function (Faker $faker) {
return [
'address' =>$faker->streetAddress,
'address2' =>$faker->streetAddress,
'district' =>$faker->stateAbbr,
'city_id' =>$faker->numberBetween($min = 1, $max = 10),
];
});
$factory->define(App\company::class, function (Faker $faker) {
return [
'Comp_reg_nr' =>$faker->ean8,
'Comp_name' =>$faker->unique()->company,
'email' =>$faker->unique()->safeEmail,
'phone' =>$faker->phoneNumber,
'address_id' =>$faker->numberBetween($min = 1, $max = 10),
];
});
$factory->define(app\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => <PASSWORD>', // secret
'remember_token' => str_random(10),
];
});
$factory->define(app\Client::class, function (Faker $faker) {
return [
'client_reg_nr' =>$faker->ean8,
'client_name'=>$faker->unique()->company,
'client_contact' => $faker->firstNameMale,
'email' => $faker->unique()->safeEmail,
];
});
$factory->define(app\Property::class, function (Faker $faker) {
return [
'property_unique_id' =>$faker->unique()->ean8,
'property_name'=>$faker->unique()->company,
];
});
<file_sep>/database/migrations/2018_10_06_124057_create_company_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateCompanyTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('company', function(Blueprint $table)
{
$table->increments('id');
$table->string('comp_reg_nr', 100)->unique();
$table->string('comp_name')->nullable();
$table->string('email', 100)->nullable();
$table->string('phone', 45)->nullable();
$table->integer('address_id')->nullable();
$table->timestamps();
$table->foreign('address_id')->references('id')->on('address')->onUpdate('CASCADE')->onDelete('CASCADE');
$table->engine = 'InnoDB';
$table->collation = 'utf8_unicode_ci';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('company');
}
}
<file_sep>/config/sidebar.php
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'menu' => [[
'icon' => 'fa fa-th-large',
'title' => 'Dashboard',
'url' => 'javascript:;',
],[
'icon' => 'fa fa-align-left',
'title' => 'Ejendom',
'url' => 'javascript:;',
'caret' => true,
'sub_menu' => [[
'url' => '/property/overview',
'title' => 'Oversigt'
],[
'url' => '/property/lease',
'title' => 'Lejemål'
],[
'url' => '/property/resident',
'title' => 'Beboer'
]]
],[
'icon' => 'fa fa-align-left',
'title' => 'Opkrævninger',
'url' => 'javascript:;',
'caret' => true,
'sub_menu' => [[
'url' => 'javascript:;',
'title' => 'Oversigt'
],[
'url' => 'javascript:;',
'title' => 'Reguleringer'
],[
'url' => 'javascript:;',
'title' => 'Rapporter'
]]
],[
'icon' => 'fa fa-align-left',
'title' => 'Drift',
'url' => 'javascript:;',
'caret' => true,
'sub_menu' => [[
'url' => 'javascript:;',
'title' => 'Oversigt'
],[
'url' => 'javascript:;',
'title' => 'Indflytninger'
],[
'url' => 'javascript:;',
'title' => 'Udflytninger'
]]
]
]
];
<file_sep>/app/Http/Controllers/ClientController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Client;
use DB;
use App\address;
use App\city;
use App\country;
class ClientController extends Controller
{
public function index(Request $request)
{
// dd(session()->get('company_id'));
//get client data - company id = session company_id
$clients = DB::table('clients')
->join('address', 'address.id','=', 'clients.address_id')
->join('company_has_clients','clients.id','=','company_has_clients.client_id')
->join('company','company.id','=','company_has_clients.company_id')
->where('company.id', '=', session()->get('company_id'))
->select('clients.client_reg_nr', 'clients.client_name','address.address', 'clients.client_contact', 'clients.client_phone1', 'clients.client_email',
'clients.created_at','clients.id' )
->get();
// dd($clients);
return view('pages/clients/clients-show',compact('clients'));
}
public function create()
{
//
$countries = country::all();
$cities = city::all();
return view('pages/clients/clients-create', compact('countries', 'cities'));
}
public function store(Request $request)
{
//
// grap post and create variables
$client_reg_nr = $request->client_reg_nr;
$client_name = $request->client_name;
$address = $request->address;
$country = $request->country;
$city = $request->city;
$client_contact = $request->client_contact;
$client_email = $request->client_email;
$client_phone1 = $request->client_phone1;
$mobil = $request->mobil;
$website = $request->website;
$client_phone1 = $request->client_phone1;
// Create address
$addressData = [
'address' => $address,
'city_id' => $city
];
// insert in address table and grab address ID
$address_id = DB::table('address')->insertGetId( $addressData );
// create client
$clientData = [
'client_reg_nr'=> $client_reg_nr,
'client_name'=> $client_name,
'client_contact'=> $client_contact,
'client_phone1'=> $client_phone1,
'client_email'=> $client_email,
'address_id'=> $address_id
];
// insert in client table and grab client ID
$clientId = DB::table('clients')->insertGetId( $clientData );
//insert client ID into company table
$companyClientId =[
'client_id'=> $clientId,
'company_id'=> session()->get('company_id')
];
DB::table('company_has_clients')->insertGetId( $companyClientId );
// Redirect to Settings to view the information
return redirect()->route('client.index');
}
public function show($id)
{
//
}
public function edit($id)
{
$countries = country::all();
$cities = city::all();
$clients = Client::findOrfail($id);
$address = DB::table('address')
->where('address.id', '=', $clients->address_id)
->select('address')
->first();
// dd($address);
return view('pages/clients/clients-edit',compact('clients','cities','countries','address'));
}
public function update(Request $request, $id)
{
// dd($request->request);
$client = Client::findOrfail($id);
//validate form indput
$request->validate([
'client_reg_nr' => 'required',
'client_name' => 'required',
'client_contact' => 'required',
'address' => 'required',
]);
//create variables from the request
$client_reg_nr = $request->client_reg_nr;
$client_name = $request->client_name;
$address = $request->address;
$country = $request->country;
$city = $request->city;
$client_contact = $request->client_contact;
$client_email = $request->client_email;
// client data in one array
$clientData = [
'client_reg_nr'=> $client_reg_nr,
'client_name'=> $client_name,
'client_contact'=> $client_contact,
'client_email'=> $client_email,
];
$addressData = [
'address'=> $address
];
// Update Client table
$updateClient = DB::table('clients')
->where('clients.id', '=', $id)
->update($clientData);
// Update address table
$updateAddress = DB::table('address')
->where('address.id', '=', $client->address_id)
->update($addressData);
return redirect()->route('client.index');
}
public function destroy($id, Request $request)
{
$clients = Client::findOrfail($id);
DB::table('address')
->where('address.id', '=', $clients->address_id)
->delete();
DB::table('company_has_clients')
->where('company_has_clients.client_id', '=', $clients->id)
->delete();
DB::table('clients')
->where('clients.id', '=', $clients->id)
->delete();
return redirect()->route('client.index');
}
}
<file_sep>/database/migrations/2018_11_06_220914_create_properties_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePropertiesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('properties', function (Blueprint $table) {
$table->increments('id');
$table->integer('property_unique_id')->unique();
$table->string('property_name', 250);
$table->timestamps();
$table->engine = 'InnoDB';
$table->collation = 'utf8_unicode_ci';
//Property has a many 2 many relation with address "property_has_address"
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('properties');
}
}
<file_sep>/app/address.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class address extends Model
{
protected $table = 'address';
protected $fillable = ['address', 'address2','district',];
public function company() {
return $this->belongsTo(company::class);
}
public function city() {
return $this->hasOne(city::class, 'id', 'city_id');
}
public function property()
{
return $this->belongsToMany('App\Property','property_has_address','address_id','property_id');
// return $this->belongsToMany('App\Property','property_has_address');
}
public function client() {
return $this->hasMany(Client::class, 'address_id','id');
}
}
<file_sep>/app/Http/Controllers/PropertyController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\address;
use App\city;
use App\country;
use App\Client;
use App\company;
class PropertyController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$properties = DB::table('clients')
->join('address', 'address.id','=', 'clients.address_id')
->join('company_has_clients','clients.id','=','company_has_clients.client_id')
->join('company','company.id','=','company_has_clients.company_id')
->join('client_has_property','clients.id', '=','client_has_property.client_id')
->join('properties','properties.id', '=', 'client_has_property.property_id')
->leftjoin('property_has_addresses','property_has_addresses.properties_id','=','properties.id')
->leftjoin('address AS prop','property_has_addresses.address_id','=', 'prop.address')
->where('company.id', '=', session()->get('company_id'))
->select('properties.property_unique_id','property_name','properties.id', 'address.address')
->get();
// dd($properties);
// return $properties[0];
return view('pages/admin/property/property-overview',compact('properties'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$countries = country::all();
$cities = city::all();
// for select options - get client data - company id = session company_id
$clients = DB::table('clients')
->join('address', 'address.id','=', 'clients.address_id')
->join('company_has_clients','clients.id','=','company_has_clients.client_id')
->join('company','company.id','=','company_has_clients.company_id')
->where('company.id', '=', session()->get('company_id'))
->select('clients.client_reg_nr', 'clients.client_name','address.address', 'clients.client_contact', 'clients.client_phone1', 'clients.client_email',
'clients.created_at','clients.id' )
->get();
return view('pages/admin/property/property-create', compact('countries', 'cities', 'clients'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$client_id = $request->client_id;
$property_name = $request->property_name;
$address = $request->address;
$address2 = $request->address2;
$country = $request->country;
$city = $request->city;
// find the highest property nr and add +1 to keep the uniqueness Remember to make it as an transaktion
$highestCompNr = DB::table('properties')->max('property_unique_id');
$highestCompNr += 1;
//prepare property data in one variable
$propertyData = [
'property_name'=> $property_name,
'property_unique_id'=> $highestCompNr
];
// Insert property data and get last ID
$propertyId = DB::table('properties')->insertGetId( $propertyData );
//Prepare client hast property data in one variable
$client_has_propertyData = [
'client_id'=> $client_id,
'property_id'=> $propertyId
];
DB::table('client_has_property')->insert( $client_has_propertyData );
// Create address
$addressData = [
'address' => $address,
'address2' => $address2,
'city_id' => $city
];
// insert in address table and grab address ID
$address_id = DB::table('address')->insertGetId( $addressData );
//prepare property has address data
$property_has_addressesData = [
'address_id' => $address_id,
'properties_id' => $propertyId
];
DB::table('property_has_addresses')->insert( $property_has_addressesData );
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//Delete property
DB::table('properties')
->where('properties.id', '=', $id)
->delete();
//Dele Client property connection
DB::table('client_has_property')
->where('client_has_property.property_id', '=', $id)
->delete();
//Get Klient company/property details to set the new session variable
if (session()->get('comp_info')) {
//Clear session
session()->forget('comp_info');
// Get ID, property unique ID and property name
$properties = DB::table('clients')
->join('address', 'address.id','=', 'clients.address_id')
->join('company_has_clients','clients.id','=','company_has_clients.client_id')
->join('company','company.id','=','company_has_clients.company_id')
->join('client_has_property','clients.id', '=','client_has_property.client_id')
->join('properties','properties.id', '=', 'client_has_property.property_id')
->where('company.id', '=', session()->get('company_id'))
->select('properties.id','properties.property_unique_id','property_name')
->get();
// dd($properties['comp_info']);
// set properties data in array object
$properties = ['comp_info'=>$properties];
// dd(session()->get('comp_info'));
// dd(session()->get('comp_info')[0]);
//Set session variables
session($properties);
// dd(session());
}
return redirect()->route('properties.index');
}
}
<file_sep>/app/Client.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
protected $table = 'clients';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'client_reg_nr', 'client_name', 'client_contact','client_phone1','client_phone2','client_email'
];
public function properties()
{
return $this->belongsToMany('App\Property','client_has_property','client_id','property_id');
}
public function address() {
return $this->belongsTo(address::class,'address_id','id' );
}
public function company() {
return $this->belongsToMany(company::class,'company_has_clients');
}
}
| 293524e28cfa0d278076e1861dbc441f4ee810d6 | [
"PHP"
] | 21 | PHP | preacharush/arcabolig | 22823eba4e8e1fcde1d66b1ae739e466864ba7a6 | 5a202dc9b15268cf4f4923823616dbd1bfd95d8b |
refs/heads/master | <repo_name>extratone/iOSKeyboardSupport.js<file_sep>/iOSKeyboardSupport.js
// eslint-disable-next-line no-unused-vars, prefer-const
let keyboardSupportManager = false
document.addEventListener("keyup", mapKeyEvent)
document.addEventListener("keydown", mapKeyEvent)
document.addEventListener("keypress", mapKeyEvent)
const supportKeymap = { // event.key -> { new KeyboardEvent overrides }
"UIKeyInputLeftArrow": {
code: "ArrowLeft",
key: "ArrowLeft",
keyCode: 37,
keyIdentifier: "Left",
which: 37
},
"UIKeyInputUpArrow": {
code: "ArrowUp",
key: "ArrowUp",
keyCode: 38,
keyIdentifier: "Up",
which: 38
},
"UIKeyInputRightArrow": {
code: "ArrowRight",
key: "ArrowRight",
keyCode: 39,
keyIdentifier: "Right",
which: 39
},
"UIKeyInputDownArrow": {
code: "ArrowDown",
key: "ArrowDown",
keyCode: 40,
keyIdentifier: "Down",
which: 40
}
}
function mapKeyEvent(event) {
if (!keyboardSupportManager) return
const keymapEntry = supportKeymap[event.key]
if (keymapEntry) {
const { charCode, code, key, keyCode, keyIdentifier, which } = keymapEntry
// revoke key event
event.preventDefault()
event.stopImmediatePropagation()
// fire mapped event
document.dispatchEvent(new KeyboardEvent(event.type, {
...event,
charCode,
code,
key,
keyCode,
keyIdentifier,
which
}))
}
}
<file_sep>/.eslintrc.js
module.exports = {
"extends": "airbnb-base",
"env": {
"browser": true,
"node": true
},
"rules": {
"object-curly-newline": 0,
"comma-dangle": ["error", "never"],
"quote-props": ["error", "consistent"],
"prefer-destructuring": 0,
"dot-notation": 0,
"no-param-reassign": 0,
"radix": 0,
"no-restricted-globals": 0,
"no-use-before-define": ["error", {
"functions": false,
"classes": true
}],
"max-len": ["error", {
"code": 200
}],
"arrow-body-style": 0,
"no-return-assign": 0,
"no-plusplus": 0,
"quotes": 0,
"no-console": 0,
"semi": 0,
"indent": ["error", 4],
}
};<file_sep>/README.md
# 🍨 iOSKeyboardSupport.js
## NOTE: APPLE FIXED THIS ISSUE WITH iOS 13.1
Vanilla workaround for the problem that arrow keys from the iPad keyboard aren't recognized in web events.
## Problem Domain
Somehow Safari Mobile for iOS seems to have big problems to translate some keyboard keys like e.g. arrow keys to a javascript `KeyboardEvent`.
Some keys are mentioned as `Unidentified` others as `Dead`. The problem reproduces on bluetooth keyboards as also on the newest _SmartKeyboard_ from Apple.
As it is really sad to have such an expensive device without the ability to work professionally in modern web apps, I created a mapping for some keys.
Everytime an iOS keyboard event is being fired the propagation of this event is immediately stopped and an artificial event (being the one you actually want) is getting fired.
**However, this is just a workaround. A clean and sustainable solution has to come from Apple.**
## Usage
Simply add the script to your head import. Done.
```
<html>
<head>
<script src="iOSKeyboardSupport.js"></script>
...
</head>
...
</html>
```
## Key Support
This script currently maps the arrow keys. Feel free to reach in a pull request if you'd add more mappings to the script.
| iOS Keyboard event.key | Real event.key | Real event.keyCode |
| ---------------------- | -------------- | ------------------- |
| UIKeyInputLeftArrow | ArrowLeft | 37 |
| UIKeyInputUpArrow | ArrowUp | 38 |
| UIKeyInputRightArrow | ArrowRight | 39 |
| UIKeyInputDownArrow | ArrowDown | 40 |
## Test it
Visit the demo site at [https://hendriku.github.io/iOSKeyboardSupport.js/](https://hendriku.github.io/iOSKeyboardSupport.js/).
## Notice
I don't want to put any license here because I want the barrier to use this in every domain to be as tiny as possible.
Nevertheless don't hold me liable for anything but I'd be feeling honored if you mention my name when you use the script.
| 94a8bd0751e1ce2e6504ed8a26431e63a0a5b460 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | extratone/iOSKeyboardSupport.js | 77b175eb1f27913153afd535819840e99def88bf | 94855cbce994f18149cb3975cd9a248f8e252853 |
refs/heads/master | <repo_name>GonzaloAlvarez/ldap-utils<file_sep>/addschema.sh
#!/bin/bash
#
# Add new schema to the LDAP installation
#
# Usage: addschema.sh schema_file
#
# (C) <NAME>, 2013
#
SLAPCAT="/usr/sbin/slapcat"
LDAPADD="/usr/bin/ldapadd"
if [ -z "$1" ]; then
cat <<EOF
LDAP Schema installer
Usage: $0 schema_file
EOF
exit 1
fi
SCHEMA_FILE="$(dirname $(readlink -f $1))/$(basename $(readlink -f $1))"
if [ ! -r "$SCHEMA_FILE" ]; then
cat <<EOF
The file does not exists or it is not readable.
EOF
exit 1
fi
if [ ! -x "$SLAPCAT" ]; then
cat <<EOF
slapcat is not installed, but it is needed. Please consider installing it.
EOF
exit 1
fi
if [ ! -x "$SLAPADD" ]; then
cat <<EOF
ldapadd is required. Please consider installing.
EOF
exit 1;
fi
CONF_FILE="$(mktemp)"
SCHEMA_DIR="$(mktemp -d)"
LDIF_FILE="$(mktemp)"
echo "include $SCHEMA_FILE" > $CONF_FILE
DN_OUTPUT="$($SLAPCAT -f $CONF_FILE -F $SCHEMA_DIR -n 0 | grep ,cn=schema | cut -d ':' -f 2 | sed 's/^ *//g')"
$SLAPCAT -f "$CONF_FILE" -F "$SCHEMA_DIR" -n0 -H ldap:///${DN_OUTPUT} -l "$LDIF_FILE"
sed -i '1,3s/{[0-9]}//' "$LDIF_FILE"
sed -i '/entryUUID:/d' "$LDIF_FILE"
sed -i '/creatorsName:/d' "$LDIF_FILE"
sed -i '/structuralObjectClass:/d' "$LDIF_FILE"
sed -i '/createTimestamp:/d' "$LDIF_FILE"
sed -i '/entryCSN:/d' "$LDIF_FILE"
sed -i '/modifiersName:/d' "$LDIF_FILE"
sed -i '/modifyTimestamp:/d' "$LDIF_FILE"
$LDAPADD -Q -Y EXTERNAL -H ldapi:/// -f "$LDIF_FILE"
rm -Rf "$CONF_FILE" "$SCHEMA_DIR" "$LDIF_FILE"
<file_sep>/README.md
LDAP Helper Scripts
===================
The following scripts are intended to ease the administration of a OpenLDAP installation.
Most scripts have the following requirements
* SLAP utils
* LDAP utils
LDAP Add Schema
---------------
This script is intended to easily allow you to add a new schema to your OpenLDAP installation.
Example of usage:
# addschema.sh /usr/share/doc/isc-dhcp-server-ldap/dhcp.schema
It requires the schema file to be uncompressed.
| 85e3fed75266f212fc411bdcbb8f43373eae377b | [
"Markdown",
"Shell"
] | 2 | Shell | GonzaloAlvarez/ldap-utils | a9d33ee7c0047779f7f89e3a158979e885166233 | e39202b01172c8d1da353ae3bdd244ec35789f78 |
refs/heads/master | <repo_name>magicbill/zeno<file_sep>/src/main/java/io/s4/zeno/protocol/helper/Sender.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.protocol.helper;
import io.s4.zeno.Part;
import io.s4.zeno.Resource;
import io.s4.zeno.protocol.Command;
import io.s4.zeno.protocol.Connection;
import io.s4.zeno.resource.TimeSliceResource;
import java.io.IOException;
import org.apache.log4j.Logger;
// TODO: Auto-generated Javadoc
/**
* The Class Sender.
*/
public class Sender {
/** The Constant logger. */
private static final Logger logger = Logger.getLogger(Sender.class);
/** The conn. */
private Connection conn;
/**
* Instantiates a new sender.
*
* @param conn
* the conn
*/
public Sender(Connection conn) {
this.conn = conn;
}
public boolean hello(String name) {
try {
conn.out.println(name);
String response = conn.in.readLine();
logger.debug("handshake response: " + response);
if (response.equals("OK")) return true;
} catch (IOException e) {
logger.error("error during handshake" + e);
}
return false;
}
/**
* Goodbye.
*/
public void goodbye() {
conn.out.println(Command.Bye);
conn.close();
}
/**
* Gets the free resource.
*
* @return the free resource
*/
public Resource getFreeResource() {
try {
conn.out.println(Command.GetFree);
Resource r = TimeSliceResource.fromString(conn.in.readLine());
logger.debug("free resource: " + r);
return r;
} catch (IOException e) {
logger.error("error while getting free resources from taker: " + e);
return new TimeSliceResource(0);
}
}
/**
* Send part to a receiver.
*
* @param part
* the part
* @return true, if successful
*/
public boolean sendPart(Part part) {
try {
// first pause the part. It may already be paused, but that's OK
part.pause();
// then send it over
byte[] data = part.getData();
logger.debug("sending part " + part.id());
String command = Command.TakePart.toString() + '\n' + part.id()
+ '\n' + data.length;
conn.out.println(command);
logger.debug(command);
// conn.dataOut.write(data);
// conn.dataOut.flush();
String response = conn.in.readLine();
logger.debug("got response: " + response);
return (response != null && response.equals("OK"));
} catch (IOException e) {
logger.error("error while sending part data: " + e);
return false;
}
}
}<file_sep>/src/main/java/io/s4/zeno/service/SimpleEventReceiver.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.service;
import io.s4.zeno.Part;
import io.s4.zeno.Service;
import io.s4.zeno.Site;
import io.s4.zeno.route.Hasher;
import io.s4.zeno.util.ZenoError;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import org.apache.log4j.Logger;
/**
* Receive events and update load monitor.
*/
public class SimpleEventReceiver extends Service {
private static final Logger logger = Logger.getLogger(SimpleEventReceiver.class);
public SimpleEventReceiver(Site site, Hasher hasher) {
super("simple-event-receiver");
this.site = site;
this.hasher = hasher;
}
private final Site site;
private final Hasher hasher;
private DatagramSocket dsock;
protected void initialize() {
int p = site.spec().getInt("port.event", -1);
if (p <= 0) {
throw new ZenoError("mising or invalid property port.event in site spec.");
}
site.info().set("port.event", String.valueOf(p));
site.info().save();
try {
dsock = new DatagramSocket(p);
logger.info("initialized with datagram sock: " + dsock.toString());
} catch (IOException e) {
logger.error("exception while creating datagram sock", e);
dsock = null;
}
setInitialDelay(5000);
setDelay(1000);
}
@Override
public int share() {
return 1;
}
@Override
protected void action() {
if (dsock == null) return;
while (dsock.isBound()) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, 1024);
try {
dsock.receive(packet);
} catch (Exception e) {
System.out.println("error: " + e);
continue;
}
String command = new String(packet.getData(), 0, packet.getLength());
// System.out.println("packet data: '" + command + "'");
if (command.equals("pause") || command.equals("pause\n")) {
site.job().pause();
logger.info("STATE: " + site.state());
continue;
} else if (command.equals("resume") || command.equals("resume\n")) {
site.job().unpause();
logger.info("STATE: " + site.state());
continue;
}
String line = new String(packet.getData(),
0,
packet.getLength() - 1);
boolean isQueued = (packet.getData()[packet.getLength() - 1] == (byte) 1);
String[] parts = line.split(" ");
if (parts.length < 3) continue;
try {
int group = Integer.parseInt(parts[0]);
int key = Integer.parseInt(parts[1]);
Part.Id id = hasher.hash(group, key);
double t = Double.parseDouble(parts[2]);
if (id == null) {
logger.warn("malformed event identifiers: " + parts[0]
+ "," + parts[1]);
continue;
}
Part part = site.job().partMap().get(id);
// make sure this event belongs to a part in this site.
if (part == null) {
logger.error("received an event for a part that is not owned by this site. partid: "
+ id);
continue;
}
// Do not count events that are played from queue for the
// purposes of monitoring
if (!isQueued) {
logger.debug("GOT event: " + id);
site.eventMonitor().putEvent(t);
part.eventMonitor().putEvent(t);
// System.out.println("rate:"
// + site.eventMonitor().getEventRate()
// + " length:"
// + site.eventMonitor().getEventLength());
// System.out.println("load:"
// + site.loadMonitor().getLevel());
// System.out.println("free:" +
// site.loadMonitor().getFreeResource());
} else {
logger.info("RECEIVED QUEUED EVENT FOR PARTID: " + id);
}
} catch (NumberFormatException e) {
logger.error("malformed numbers in data: " + e);
}
}
}
}
<file_sep>/src/main/java/io/s4/zeno/EventMonitor.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno;
import java.util.concurrent.TimeoutException;
// TODO: Auto-generated Javadoc
/**
* The Interface EventMonitor.
*/
public interface EventMonitor {
public interface Factory {
public EventMonitor getInstance();
}
/**
* Put event.
*
* @param length
* the length
*/
void putEvent(double length);
/**
* Gets the millis since last event.
*
* @return the millis since last event
*/
long getMillisSinceLastEvent();
/**
* Wait for a period of silence. Blocks till a period of time passes without
* any events. Times out after a specified period.
*
* @param silentMs
* period of time for which silence should be observed
* (milliseconds).
*
* @param timeoutMs
* timeout (milliseconds).
*
* @throws TimeoutException
* if timeout expired.
* @throws InterruptedException
* if interrupted while waiting.
*/
void waitForSilence(long silentMs, long timeoutMs) throws TimeoutException, InterruptedException;
/**
* Gets the event rate.
*
* @return the event rate
*/
double getEventRate();
/**
* Gets the event length.
*
* @return the event length
*/
double getEventLength();
/**
* Checks if is valid.
*
* @return true, if is valid
*/
boolean isValid();
/**
* Reset.
*/
void reset();
}
<file_sep>/src/main/java/io/s4/zeno/Cluster.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno;
import io.s4.zeno.config.ConfigMap;
import io.s4.zeno.config.WritableConfigMap;
import io.s4.zeno.config.ZKConfigMap;
import java.util.List;
/**
* Abstraction of a collection of Sites. Provides access to a list of names of
* all sites in the cluster, and access to a read-only copy of the information
* from all sites in the cluster.
*/
public interface Cluster {
/**
* Gets the information for a named node. The ConfigMap is backed by
* ZooKeeper. Updates are applied to it asynchronously.
*
* @see ZKConfigMap
*
* @param name
* node's name
*
* @return information for the node.
*/
Cluster.Site getSite(String name);
/**
* Get names of all active sites in the cluster.
*
* @return list of all active site names.
*/
List<String> getAllSiteNames();
/**
* Get a list of all active sites in this cluster.
*
* @return all active sites.
*/
List<Site> getAllSites();
/**
* Add a Site to a cluster. The name of the site is obtained from
* {@code site.name()}. A Writable config map is created for the site and
* returned. Writes to this config map become visible to other Sites in the
* cluster.
*
* @param site
* @return
*/
WritableConfigMap addSite(Cluster.Site site);
/**
* Remove a site from the cluster.
*
* @param site
*/
void removeSite(Cluster.Site site);
public interface Site {
String name();
ConfigMap info();
}
}<file_sep>/src/main/java/io/s4/zeno/console/Main.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.console;
import io.s4.zeno.config.ZKConfigMap;
import io.s4.zeno.config.ZKPaths;
import io.s4.zeno.route.RouterTest;
import io.s4.zeno.util.ZooKeeperHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
/**
* A Console for monitoring a Zeno cluster.
*/
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
// node configuration
HashMap<String, ZKConfigMap> nodeConf = new HashMap<String, ZKConfigMap>();
ZooKeeper zookeeper = null;
RouterTest router = null;
ZKPaths zkpath = null;
public static void main(String[] argv) throws IOException, KeeperException {
PropertyConfigurator.configure("log4j.properties");
String zkserver = argv[0];
String base = argv[1];
logger.info("connecting to zookeeper: " + zkserver);
int timeout = 1000;
ZooKeeper zookeeper = new ZooKeeper(zkserver, timeout, new Watcher() {
public void process(WatchedEvent e) {
logger.info("Got Notification: " + e);
}
});
logger.info("connected to zookeeper");
Main cli = new Main(zookeeper, base);
cli.run();
}
Main(ZooKeeper zookeeper, String base) {
this.zookeeper = zookeeper;
this.zkpath = new ZKPaths(base);
this.router = new RouterTest(zookeeper, base);
}
/** The data socket. */
DatagramSocket dataSocket = null;
void run() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
ZooKeeperHelper zookeeperHelper = new ZooKeeperHelper(zookeeper,
3,
5000);
String line;
try {
this.dataSocket = new DatagramSocket();
} catch (SocketException e) {
logger.error("error creating emission socket: " + e);
this.dataSocket = null;
return;
}
while (true) {
// command loop
System.out.print("> ");
if ((line = in.readLine()) == null) break;
String[] parts = line.split(" +", 2);
if (parts.length == 0) continue;
String cmd = parts[0];
if (cmd.equals("routes")) {
// dump routing information
router.dump();
} else if (cmd.equals("exit")) {
// The End.
break;
} else if (cmd.equals("loadgen")) {
// start load generation using arg as filename.
if (parts.length != 2) continue;
router.loadGen(parts[1]);
} else if (cmd.equals("loadstop")) {
// stop load generation
router.stopLoad();
} else if (cmd.equals("info")) {
// print status of a site.
if (parts.length != 2) continue;
String node = parts[1];
ZKConfigMap conf = nodeConf.get(node);
if (conf == null) {
nodeConf.put(node,
(conf = new ZKConfigMap(zookeeperHelper,
zkpath.node(node))));
}
System.out.println("nodeinfo for " + node + ": "
+ conf.toString());
} else {
// Send a message to a site.
if (parts.length != 2) continue;
String node = parts[0];
byte[] data = parts[1].getBytes();
ZKConfigMap conf = nodeConf.get(node);
if (conf == null) {
nodeConf.put(node,
(conf = new ZKConfigMap(zookeeperHelper,
zkpath.node(node))));
}
String host = conf.get("IPAddress");
int port = conf.getInt("port.event", -1);
if (host == null || port < 0) {
logger.error("missing host/port information for node "
+ node + " at " + zkpath.node(node));
continue;
}
DatagramPacket packet = new DatagramPacket(data,
data.length,
new InetSocketAddress(host,
port));
try {
logger.debug("sending command to " + node + " at " + host
+ ":" + port);
dataSocket.send(packet);
logger.debug("sent");
} catch (Exception e) {
logger.error("SEND failed: " + e);
continue;
}
}
}
router.stopLoad();
dataSocket.close();
}
}
<file_sep>/src/main/java/io/s4/zeno/coop/DistributedSequence.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.coop;
import io.s4.zeno.util.ZenoDefs;
import io.s4.zeno.util.ZenoError;
import io.s4.zeno.util.ZooKeeperHelper;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
/**
* Distributed sequence of items.
*
* Allows Items to be added to the tail of a sequence. When an item reaches the
* head of the sequence, the doHeadAction() method is called. The item is
* removed from the sequence when this callback returns.
*
* The sequence is implemented as a directory in ZooKeeper with sequential
* files.
*/
public class DistributedSequence {
// Maintain a sequence of items.
// An element is notified when it is at the head of the sequence.
private final ZooKeeperHelper zookeeper;
private final String dir;
private final String prefix;
private final String path;
private static final char pSep = '/';
private static final Logger logger = Logger.getLogger(DistributedSequence.class);
/**
* Instantiates a new distributed sequence.
*
* @param zookeeper
* zookeeper
* @param dir
* the directory within which the sequence exists.
*/
public DistributedSequence(ZooKeeperHelper zookeeper, String dir) {
this.zookeeper = zookeeper;
this.dir = dir;
this.prefix = "q-";
this.path = this.dir + pSep + this.prefix;
}
/**
* Instantiates a new distributed sequence.
*
* @param zookeeper
* zookeeper
* @param dir
* the directory within which the sequence exists.
* @param prefix
* the prefix to use for queue znodes. Default is "q-"
*/
public DistributedSequence(ZooKeeperHelper zookeeper, String dir,
String prefix) {
this.zookeeper = zookeeper;
this.dir = dir;
this.prefix = prefix;
this.path = this.dir + this.prefix;
}
/**
* Add an Item to the sequence.
*
* @param item
* the item
* @return the sequenced item
*/
public DistributedSequence.SequencedItem add(DistributedSequence.Item item) {
while (true) {
try {
// create a sequential znode.
String fullName = zookeeper.create(path,
item.getSequenceData(),
ZenoDefs.zkACL,
CreateMode.EPHEMERAL_SEQUENTIAL);
logger.debug("Created sequence znode: " + fullName);
// extract the node name from the full name
String nodeName = fullName.substring(fullName.lastIndexOf(pSep) + 1);
Node node = new Node(nodeName, item); // create a new Node for
// this item
(new Thread(node)).start(); // start a thread to let that node
// complete the insertion process.
return new DistributedSequence.SequencedItem(node);
} catch (KeeperException.NoNodeException e) {
logger.debug("Parent directory does not exist: " + dir);
try {
zookeeper.create(dir,
new byte[0],
ZenoDefs.zkACL,
CreateMode.PERSISTENT);
logger.info("Parent directory created: " + dir);
logger.debug("Retrying creating znode for item.");
} catch (InterruptedException ee) {
} catch (KeeperException.NodeExistsException ee) {
logger.debug("Someone else created parent directory");
} catch (KeeperException ee) {
logger.error("Failed to create sequence directory: " + ee);
throw (new ZenoError("error creating sequence directory: "
+ dir, ee));
// return null; // can't even create the parent dir!
}
} catch (InterruptedException e) {
} catch (KeeperException e) {
logger.error("Failed to create znode for item: " + e);
throw (new ZenoError("error creating znode for sequened item in "
+ dir,
e));
// return null;
}
}
}
/**
* An Item which can be added to the sequence.
*/
public interface Item {
/**
* Gets the data that is written into the znode.
*
* @return the sequence data
*/
public byte[] getSequenceData();
/**
* Action to perform when this item reaches the head of the sequence.
*/
public void doHeadAction();
}
/**
* An item after it has been added to the sequence.
*/
public static class SequencedItem implements Item {
/** The node in the queue */
private final Node node;
/**
* Instantiates a new sequenced item.
*
* @param node
* the node
*/
SequencedItem(Node node) {
this.node = node;
}
public byte[] getSequenceData() {
return node.getItem().getSequenceData();
}
public void doHeadAction() {
node.getItem().doHeadAction();
}
/**
* Removes the item from the queue.
*
* @return true, if successful
*/
public boolean remove() {
return node.remove();
}
/**
* Checks if item is active.
*
* @return true, if is active
*/
public boolean isActive() {
return node.isActive();
}
/**
* Checks if action is done.
*
* @return true, if is done
*/
public boolean isDone() {
return node.isDone();
}
/**
* Try to wait for the node to be done and return true if the action is
* done. It is possible that the caller's thread may be interrupted
* before the action is done. In this case, false is returned.
*
* @return true if and only if the action has been completed.
*/
public boolean awaitDone() {
try {
synchronized (node) {
node.wait();
}
} catch (InterruptedException e) {
logger.info("interrupted while waiting for sequenced item to finish.");
}
return this.isDone();
}
}
/**
* A node in the sequence.
*
* This object handles notifications when the predecessor node completes
* processing.
*/
private class Node implements Runnable, Watcher {
/** The node name. */
private final String nodeName;
/** The item. */
private final DistributedSequence.Item item;
private volatile boolean active = false;
private volatile boolean done = false;
/**
* Instantiates a new node.
*
* @param nodeName
* the node name
* @param item
* the item
*/
public Node(String nodeName, DistributedSequence.Item item) {
this.nodeName = nodeName;
this.item = item;
}
/**
* A node is active when it is watching its predecessor or is at
* the head and performing its head action.
*
* @return true, if is active
*/
public boolean isActive() {
return active;
}
/**
* A node is done when it reaches the head and completes
* performing its head action.
*
* @return true, if is done
*/
public boolean isDone() {
return done;
}
/**
* Gets the item.
*
* @return the item
*/
public Item getItem() {
return item;
}
/**
* Complete insertion of the node into the sequence.
*/
public void run() {
try {
active = true;
locate();
} catch (KeeperException e) {
throw (new ZenoError("error inserting node into distributed sequence: "
+ nodeName,
e));
} catch (Exception e) {
logger.error(nodeName + ": " + e);
e.printStackTrace();
}
}
/**
* Handle notification when the predecessor changes.
*
* @param w
* the w
*/
public void process(WatchedEvent w) {
// Something changed.
logger.debug(nodeName + ": notified with " + w);
// If a node went away, relocate in the sequence.
try {
if (w.getType() == Watcher.Event.EventType.NodeDeleted)
locate();
} catch (KeeperException e) {
throw (new ZenoError("error processing notification for node="
+ nodeName + " event=" + w, e));
} catch (Exception e) {
logger.error(nodeName + ": " + e);
e.printStackTrace();
}
// Otherwise, do nothing.
}
/**
* Remove a sequenced node.
*
* @return true, if successful
*/
public boolean remove() {
if (!active) return true;
try {
active = false;
logger.debug("Deleting " + dir + pSep + nodeName);
zookeeper.delete((dir + pSep + nodeName), -1);
logger.debug("Deleted " + dir + pSep + nodeName);
return true;
} catch (KeeperException e) {
throw (new ZenoError("error deleting node from distributed sequence: "
+ nodeName,
e));
} catch (Exception e) {
logger.error("Exception while deleting " + dir + pSep
+ nodeName + ": " + e);
return false;
} finally {
// let all threads waiting for this node know that it is not
// going to run.
synchronized (this) {
this.notifyAll();
}
}
}
// SYNCHRONIZE?
/**
* Check the siblings of this node to to find location in
* sequence. If at head, call item.doHeadAction()
*
* @throws KeeperException
* the keeper exception
* @throws InterruptedException
* the interrupted exception
*/
private void locate() throws KeeperException, InterruptedException {
if (active) {
String predecessor = findAndWatchPredecessor(); // get my
// predecessor.
if (predecessor == null) { // I am at the head of the sequence.
logger.debug("Reached head of sequence: " + nodeName);
item.doHeadAction();
logger.debug("Done processing: " + nodeName);
remove();
done = true;
}
}
}
/**
* Find predecessor in sequence.
*
* @return the string
* @throws KeeperException
* the keeper exception
* @throws InterruptedException
* the interrupted exception
*/
private String findPredecessor() throws KeeperException,
InterruptedException {
// if the znode corresponding to this exists, find a predecessor.
// null if this is the head, or this znode does not exist.
List<String> siblings = zookeeper.getChildren(dir, false);
String p = null;
boolean foundSelf = false;
logger.debug("Finding predecessor of " + nodeName + " [" + siblings
+ "]");
for (String s : siblings) {
if (s.compareTo(nodeName) < 0
&& (p == null || s.compareTo(p) > 0))
p = s;
else if (s.equals(nodeName)) foundSelf = true;
}
logger.debug("FoundSelf:" + foundSelf + " p:" + p);
return foundSelf ? p : null;
}
/**
* Watch the predecessor for changes.
*
* @return the string
* @throws KeeperException
* the keeper exception
* @throws InterruptedException
* the interrupted exception
*/
private String findAndWatchPredecessor() throws KeeperException,
InterruptedException {
String predecessor = null;
// make sure the predecessor exists and set a watch on it
do {
predecessor = findPredecessor();
} while (predecessor != null
&& zookeeper.exists(dir + pSep + predecessor, this) == null);
logger.debug("Watching predecessor: " + predecessor);
// at this point, predecessor is either null or exists and is being
// watched.
return predecessor;
}
}
}<file_sep>/src/main/java/io/s4/zeno/resource/FlexibleTimeSliceResource.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.resource;
import io.s4.zeno.Resource;
// TODO: Auto-generated Javadoc
/**
* The Class FlexibleTimeSliceResource.
*/
public class FlexibleTimeSliceResource extends TimeSliceResource implements
FlexibleResource {
/** The expand count. */
protected final int expandCount;
/** The margin hi. */
protected final double marginHi;
/** The margin lo. */
protected final double marginLo;
/** The expand hi. */
protected final double expandHi;
/** The expand lo. */
protected final double expandLo;
/**
* Instantiates a new flexible time slice resource.
*
* @param r
* the r
* @param marginLo
* the margin lo
* @param marginHi
* the margin hi
* @param expandLo
* the expand lo
* @param expandHi
* the expand hi
* @param expandCount
* the expand count
*/
public FlexibleTimeSliceResource(Resource r, double marginLo,
double marginHi, double expandLo, double expandHi, int expandCount) {
this(new TimeSliceResource(r),
marginLo,
marginHi,
expandLo,
expandHi,
expandCount);
}
/**
* Instantiates a new flexible time slice resource.
*
* @param r
* the r
* @param marginLo
* the margin lo
* @param marginHi
* the margin hi
* @param expandLo
* the expand lo
* @param expandHi
* the expand hi
* @param expandCount
* the expand count
*/
public FlexibleTimeSliceResource(TimeSliceResource r, double marginLo,
double marginHi, double expandLo, double expandHi, int expandCount) {
this(r.getTimeSlice(),
marginLo,
marginHi,
expandLo,
expandHi,
expandCount);
}
/**
* Instantiates a new flexible time slice resource.
*
* @param timeSlice
* the time slice
* @param marginLo
* the margin lo
* @param marginHi
* the margin hi
* @param expandLo
* the expand lo
* @param expandHi
* the expand hi
* @param expandCount
* the expand count
*/
public FlexibleTimeSliceResource(double timeSlice, double marginLo,
double marginHi, double expandLo, double expandHi, int expandCount) {
this(timeSlice,
marginLo,
marginHi,
expandLo,
expandHi,
expandCount,
false);
}
/**
* Instantiates a new flexible time slice resource.
*
* @param timeSlice
* the time slice
* @param marginLo
* the margin lo
* @param marginHi
* the margin hi
* @param expandLo
* the expand lo
* @param expandHi
* the expand hi
* @param expandCount
* the expand count
* @param absolute
* the absolute
*/
public FlexibleTimeSliceResource(double timeSlice, double marginLo,
double marginHi, double expandLo, double expandHi, int expandCount,
boolean absolute) {
super(timeSlice);
this.marginHi = (absolute ? marginHi : (marginHi * timeSlice));
this.marginLo = (absolute ? marginLo : (marginLo * timeSlice));
this.expandHi = expandHi;
this.expandLo = expandLo;
this.expandCount = expandCount;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.resource.FlexibleResource#canExpand()
*/
public boolean canExpand() {
return (expandCount > 0);
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.resource.FlexibleResource#expand()
*/
public FlexibleResource expand() {
if (canExpand()) {
return new FlexibleTimeSliceResource(((TimeSliceResource) this).getTimeSlice(),
marginLo * expandLo,
marginHi * expandHi,
expandLo,
expandHi,
(expandCount - 1),
true);
}
return this.duplicate();
}
// create a duplicate
/*
* (non-Javadoc)
*
* @see io.s4.zeno.resource.FlexibleResource#duplicate()
*/
public FlexibleResource duplicate() {
return new FlexibleTimeSliceResource(((TimeSliceResource) this).getTimeSlice(),
marginLo,
marginHi,
expandLo,
expandHi,
expandCount,
true);
}
/**
* Lo.
*
* @return the double
*/
private double lo() {
return timeSlice - marginLo;
}
/**
* Hi.
*
* @return the double
*/
private double hi() {
return timeSlice + marginHi;
}
/*
* (non-Javadoc)
*
* @see
* io.s4.zeno.resource.TimeSliceResource#canAcceptPartial(com.yahoo.
* zeno.Resource)
*/
public boolean canAcceptPartial(Resource demand) {
// TimeSliceResource r = (TimeSliceResource)demand;
return this.hi() > 0.0;
}
/*
* (non-Javadoc)
*
* @see
* io.s4.zeno.resource.TimeSliceResource#canAccept(io.s4.zeno.Resource
* )
*/
public boolean canAccept(Resource demand) {
TimeSliceResource r = (TimeSliceResource) demand;
return this.hi() > r.timeSlice;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.resource.TimeSliceResource#isEmpty()
*/
public boolean isEmpty() {
return this.hi() <= 0.0;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.resource.FlexibleResource#almostEmpty()
*/
public boolean almostEmpty() {
return this.lo() <= 0.0;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.resource.TimeSliceResource#toString()
*/
public String toString() {
return super.toString() + ":[-" + marginLo + "(x" + expandLo + "), +"
+ marginHi + "(x" + expandHi + "); " + expandCount + "X]";
}
}
<file_sep>/src/main/java/io/s4/zeno/config/ZKConfigTest.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.config;
import io.s4.zeno.util.ZooKeeperHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.log4j.PropertyConfigurator;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
// TODO: Auto-generated Javadoc
/**
* The Class ZKConfigTest.
*/
public class ZKConfigTest {
/**
* The main method.
*
* @param arg
* the arguments
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void main(String[] arg) throws IOException {
PropertyConfigurator.configure("log4j.properties");
String connect = "localhost:2181";
int timeout = 1000;
ZooKeeper zk = new ZooKeeper(connect, timeout, new Watcher() {
public void process(WatchedEvent e) {
System.out.println("Got Notification: " + e);
}
});
ZooKeeperHelper zookeeper = new ZooKeeperHelper(zk, 3, 5000);
ZKWritableConfigMap conf = new ZKWritableConfigMap(zookeeper,
"/tmp/test-config");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String cmd;
while ((cmd = in.readLine()) != null) {
if (cmd.equals("get")) {
String key = in.readLine();
System.out.println("got '" + key + "': " + conf.get(key));
} else {
String key = in.readLine();
String val = in.readLine();
conf.set(key, val);
}
}
}
}
<file_sep>/src/main/java/io/s4/zeno/service/LoadDetection.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.service;
import io.s4.zeno.LoadLevel;
import io.s4.zeno.Service;
import io.s4.zeno.Site;
import org.apache.log4j.Logger;
/**
* Detect load level at site.
*/
public class LoadDetection extends Service {
private static final Logger logger = Logger.getLogger(LoadDetection.class);
Site site;
public LoadDetection(Site site) {
this.site = site;
}
protected void initialize() {
setInitialDelay(0, 5000);
setDelay(5000);
}
@Override
protected void action() {
LoadLevel level = site.loadMonitor().detectLevel();
logger.debug(level);
}
}
<file_sep>/src/main/java/io/s4/zeno/route/ZKRouter.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.route;
import io.s4.zeno.Part;
import io.s4.zeno.config.ZKPaths;
import io.s4.zeno.util.ZenoError;
import io.s4.zeno.util.ZooKeeperHelper;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;
// TODO: Auto-generated Javadoc
/**
* The Class ZKRouter.
*/
public class ZKRouter implements Router {
/** The Constant logger. */
private static final Logger logger = Logger.getLogger(ZKRouter.class);
/** The zookeeper. */
private ZooKeeperHelper zookeeper = null;
/** The zkpath. */
private ZKPaths zkpath = null;
/** The route updater. */
private RouteUpdater routeUpdater = null;
/** The hold updater. */
private HoldUpdater holdUpdater = null;
/** The data socket. */
private DatagramSocket dataSocket = null;
/**
* The Class Route.
*/
private class Route {
/** The hold. */
private volatile boolean hold = false;
/** The address. */
private SocketAddress address = null;
/** The queue. */
private LinkedList<DatagramPacket> queue = null;
/**
* Instantiates a new route.
*/
public Route() {
}
/**
* Instantiates a new route.
*
* @param host
* the host
* @param port
* the port
* @param hold
* the hold
*/
@SuppressWarnings("unused")
public Route(String host, int port, boolean hold) {
address = new InetSocketAddress(host, port);
hold = false;
}
/**
* Send.
*
* @param data
* the data
* @return true, if successful
*/
public boolean send(byte[] data) {
byte[] packetData = Arrays.copyOf(data, data.length + 1);
if (hold) {
packetData[packetData.length - 1] = (byte) 1;
DatagramPacket packet = new DatagramPacket(packetData,
packetData.length);
LinkedList<DatagramPacket> q = queue;
if (q == null) {
logger.warn("SEND failed: hold queue is null");
return false;
}
// We are either appending to the queue,
// or dequeuing, never both. So no need to synchronize
q.add(packet);
logger.debug("packet added to queue");
} else {
DatagramPacket packet = new DatagramPacket(packetData,
packetData.length);
SocketAddress a = address;
if (a == null) {
logger.warn("SEND failed: destination address is null");
return false;
}
packet.setSocketAddress(a);
try {
dataSocket.send(packet);
logger.debug("sent packet");
} catch (Exception e) {
logger.error("SEND failed: " + e);
return false;
}
}
return true;
}
/**
* Sets the address.
*
* @param dest
* the new address
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void setAddress(String dest) throws IOException {
String[] hostport = dest.split(":");
InetSocketAddress destSock = null;
try {
if (hostport.length == 2) {
destSock = new InetSocketAddress(hostport[0],
new Integer(hostport[1]));
} else {
throw new IOException("Malformed host-port " + dest);
}
} catch (NumberFormatException e) {
throw new IOException("Malformed host-port " + dest);
}
address = destSock;
}
/**
* Unset address.
*/
public void unsetAddress() {
address = null;
}
/**
* Sets the hold.
*
* @return true, if successful
*/
public boolean setHold() {
if (hold) return false;
if (queue == null) queue = new LinkedList<DatagramPacket>();
hold = true;
return true;
}
/**
* Unset hold.
*
* @return true, if successful
*/
public boolean unsetHold() {
if (!hold) return false;
// unhold it right away. new events will not be queued
hold = false;
boolean error = false;
LinkedList<DatagramPacket> q = queue;
if (q != null) {
DatagramPacket packet;
// if route is put on hold mid-way, we will stop sending.
while (!hold && !q.isEmpty()) {
packet = q.remove();
SocketAddress a = address;
if (a != null) {
try {
packet.setSocketAddress(a);
dataSocket.send(packet);
} catch (Exception e) {
logger.error("Error sending queued item: " + e);
error = true;
}
} else {
logger.warn("Purging packet: address is null");
}
}
}
queue = null;
return !error;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return (address != null ? address.toString() : "NULL") + ':'
+ (hold ? "hold" : "pass");
}
}
/**
* Instantiates a new zK router.
*
* @param zookeeper
* the zookeeper
* @param base
* the base
*/
public ZKRouter(ZooKeeperHelper zookeeper, ZKPaths zkpath, Hasher hasher) {
this.zookeeper = zookeeper;
this.zkpath = zkpath;
this.routeUpdater = new RouteUpdater();
this.holdUpdater = new HoldUpdater();
this.hasher = hasher;
try {
this.dataSocket = new DatagramSocket();
} catch (SocketException e) {
logger.error("error creating emission socket: " + e);
this.dataSocket = null;
}
}
/** The route map. */
private ConcurrentHashMap<Part.Id, Route> routeMap = new ConcurrentHashMap<Part.Id, Route>();
private final Hasher hasher;
/**
* Reverse route map.
*
* @return the map
*/
private Map<String, Set<Part.Id>> reverseRouteMap() {
Map<String, Set<Part.Id>> reversed = new TreeMap<String, Set<Part.Id>>();
for (Map.Entry<Part.Id, Route> r : routeMap.entrySet()) {
String to = r.getValue().toString();
Set<Part.Id> s;
if (!reversed.containsKey(to))
reversed.put(to, s = new TreeSet<Part.Id>());
else
s = reversed.get(to);
s.add(r.getKey());
}
return reversed;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.router.Router#send(int, byte[])
*/
public boolean send(int group, int key, byte[] data) {
if (dataSocket != null) {
Part.Id id = hasher.hash(group, key);
if (id == null) return false;
Route r = routeMap.get(id);
if (r == null)
return false;
else
return r.send(data);
}
return false;
}
// //////////////////////////////////////////////////////////
// LOADING FROM ZK /////////////////////////////////////////
// //////////////////////////////////////////////////////////
/*
* (non-Javadoc)
*
* @see io.s4.zeno.router.Router#load()
*/
public void load() {
readMap();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return zkpath.zkBase + " autoreload:" + " routeMap:"
+ routeMap.toString() + "\nassignment:"
+ reverseRouteMap().toString();
}
/**
* Read map.
*/
private void readMap() {
// scan partsBase
logger.debug("reading router map from " + zkpath.partsBase);
try {
List<String> parts = zookeeper.getChildren(zkpath.partsBase
+ "/items", new Watcher() {
public void process(WatchedEvent w) {
readMap();
}
});
ArrayList<Part.Id> partIds = new ArrayList<Part.Id>();
// for each node, check route map and holds.
// update routemap
for (String p : parts) {
Part.Id id = Part.Id.fromString(p);
if (id != null) {
partIds.add(id);
updateDest(zkpath.routeMap(id.toString()));
updateHold(zkpath.routeHold(id.toString()));
}
}
hasher.rebuild(partIds);
} catch (KeeperException e) {
logger.error("exception while listing parts: " + e);
throw (new ZenoError("error reading routing map at "
+ zkpath.partsBase, e));
} catch (InterruptedException e) {
logger.error("interrupted while listing parts");
}
}
/**
* Gets the id.
*
* @param path
* the path
* @return the id
* @throws NumberFormatException
* the number format exception
*/
private Part.Id getId(String path) throws NumberFormatException {
return Part.Id.fromString(path.substring(path.lastIndexOf('/') + 1));
}
/**
* Update hold.
*
* @param path
* the path
*/
private void updateHold(String path) {
try {
Part.Id id = getId(path);
routeMap.putIfAbsent(id, new Route());
if (zookeeper.exists(path, holdUpdater) != null) {
routeMap.get(id).setHold();
} else {
routeMap.get(id).unsetHold();
}
logger.debug("updated hold for " + id + " -> " + routeMap.get(id)
+ " (" + path + ")");
} catch (KeeperException e) {
logger.error("exception while updating routing hold from " + path
+ " :" + e);
throw (new ZenoError("error while updating routing hold state from "
+ path,
e));
} catch (InterruptedException e) {
logger.error("interrupted while updating routing hold from " + path
+ " :" + e);
}
}
/**
* Update dest.
*
* @param path
* the path
*/
private void updateDest(String path) {
try {
Part.Id id = getId(path);
routeMap.putIfAbsent(id, new Route());
Route r = routeMap.get(id);
if (zookeeper.exists(path, routeUpdater) != null) {
// get dest
Stat stat = new Stat();
String dest = new String(zookeeper.getData(path,
routeUpdater,
stat));
// update map
try {
r.setAddress(dest);
} catch (IOException e) {
logger.error("address update failed for partid " + id
+ ": " + e);
}
} else {
// route deleted
r.unsetAddress();
}
logger.debug("updated route for " + id + " -> " + routeMap.get(id)
+ " (" + path + ")");
} catch (KeeperException e) {
throw (new ZenoError("error while updating routing destination from "
+ path,
e));
} catch (Exception e) {
logger.error("exception while updating routing destination from "
+ path + " :" + e);
}
}
/**
* The Class HoldUpdater.
*/
public class HoldUpdater implements Watcher {
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent
* )
*/
public void process(WatchedEvent e) {
String path = e.getPath();
logger.info("updating routing hold from " + path);
updateHold(path);
}
}
/**
* The Class RouteUpdater.
*/
public class RouteUpdater implements Watcher {
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent
* )
*/
public void process(WatchedEvent e) {
String path = e.getPath();
logger.info("updating routing destination from " + path);
updateDest(path);
}
}
}
<file_sep>/src/main/java/io/s4/zeno/config/ConfigMap.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.config;
// TODO: Auto-generated Javadoc
/**
* A key-value map. The keys are strings. The values may be interpreted as a
* variety of types: see the getters for all options. It is recommended that the
* keys be structured hierarchically with dots ({@code .}) as separators, like
* java package names. This allows the creation of maps with a subspace of keys.
*/
public interface ConfigMap {
/**
* Gets the.
*
* @param key
* the key
* @return the string
*/
String get(String key);
/**
* Gets the list.
*
* @param key
* the key
* @return the list
*/
String[] getList(String key);
/**
* Gets the int.
*
* @param key
* the key
* @param v
* the v
* @return the int
*/
int getInt(String key, int v);
/**
* Gets the int list.
*
* @param key
* the key
* @return the int list
*/
int[] getIntList(String key);
/**
* Gets the double.
*
* @param key
* the key
* @param v
* the v
* @return the double
*/
double getDouble(String key, double v);
/**
* Gets the double list.
*
* @param key
* the key
* @return the double list
*/
double[] getDoubleList(String key);
/**
* Gets the long.
*
* @param key
* the key
* @param v
* the v
* @return the long
*/
long getLong(String key, long v);
/**
* Gets the long list.
*
* @param key
* the key
* @return the long list
*/
long[] getLongList(String key);
/**
* Gets the boolean.
*
* @param key
* the key
* @param v
* the v
* @return the boolean
*/
boolean getBoolean(String key, boolean v);
/**
* Gets the boolean list.
*
* @param key
* the key
* @return the boolean list
*/
boolean[] getBooleanList(String key);
/**
* To string.
*
* @return the string
*/
public String toString();
public ConfigMap chroot(String root);
}
<file_sep>/src/main/java/io/s4/zeno/resource/FlexibleResource.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.resource;
import io.s4.zeno.Resource;
// TODO: Auto-generated Javadoc
// A flexible estimate of resources.
// E.g.free memory estimate with lower/upper bounds.
/**
* The Interface FlexibleResource.
*/
public interface FlexibleResource extends Resource {
// can this resource be expanded?
/**
* Can expand.
*
* @return true, if successful
*/
boolean canExpand();
// return an expanded versoin of this
/**
* Expand.
*
* @return the flexible resource
*/
FlexibleResource expand();
// resource is almost empty. e.g. lower bound of free memory estimate is
// zero.
/**
* Almost empty.
*
* @return true, if successful
*/
boolean almostEmpty();
// duplicate
/**
* Duplicate.
*
* @return the flexible resource
*/
FlexibleResource duplicate();
}
<file_sep>/src/main/java/io/s4/zeno/config/RootedConfigMap.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.config;
public class RootedConfigMap implements ConfigMap {
private final String root;
private final ConfigMap c;
public RootedConfigMap(String root, ConfigMap c) {
this.root = root;
this.c = c;
}
protected String k(String key) {
return root + '.' + key;
}
@Override
public String get(String key) {
return c.get(k(key));
}
@Override
public String[] getList(String key) {
return c.getList(k(key));
}
@Override
public int getInt(String key, int v) {
return c.getInt(k(key), v);
}
@Override
public int[] getIntList(String key) {
return c.getIntList(k(key));
}
@Override
public double getDouble(String key, double v) {
return c.getDouble(k(key), v);
}
@Override
public double[] getDoubleList(String key) {
return c.getDoubleList(k(key));
}
@Override
public long getLong(String key, long v) {
return c.getLong(k(key), v);
}
@Override
public long[] getLongList(String key) {
return c.getLongList(k(key));
}
@Override
public boolean getBoolean(String key, boolean v) {
return c.getBoolean(k(key), v);
}
@Override
public boolean[] getBooleanList(String key) {
return c.getBooleanList(k(key));
}
@Override
public ConfigMap chroot(String root) {
return new RootedConfigMap(root, this);
}
}<file_sep>/src/main/java/io/s4/zeno/Site.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno;
import io.s4.zeno.config.ConfigMap;
import io.s4.zeno.config.WritableConfigMap;
import io.s4.zeno.monitor.EventRateLoadMonitor;
/**
* A Site at which a Job can run. The Site receives messages and processes them
* based on the Job that it acquires.
*/
public class Site implements Cluster.Site {
public synchronized void initialize() {
if (state() == State.Null) {
// Register myself with the cluster.
info = cluster.addSite(this);
// initialize the monitor
monitor = new EventRateLoadMonitor(spec);
if (initializer != null) {
initializer.initialize(this);
}
state = State.Initialized;
}
}
/**
* Start the site and its registry.
*/
public synchronized void start() {
initialize();
if (state() == State.Initialized) {
// acquire a job
job = jobList.acquire();
if (job == null) {
// job could not be acquired right away.
// stand by for a job to become available.
state = State.StandingBy;
job = jobList.standbyAcquire();
}
// we should have a job by now.
state = State.JobAcquired;
registry.startServices();
job.initialize();
// All set now...
}
}
/**
* Stop the site.
*/
public synchronized void stop() {
if (state() == State.Running) {
registry.stopServices();
partMap.clear();
job.release();
job = null;
cluster.removeSite(this);
state = State.Null;
}
}
public SiteRegistry registry() {
return registry;
}
/**
* Get the state of this site.
*
* @return current state of the site.
*/
public State state() {
return state;
}
public void setState(State state) {
this.state = state;
}
/**
* Get the load monitor associated with this site.
*
* @return load monitor.
*/
public LoadMonitor loadMonitor() {
return monitor;
}
/**
* Get the event monitor associated with this site. This is used to measure
* the arrival rate and average length of events processed by this site.
*
* @return event monitor.
*/
public EventMonitor eventMonitor() {
return monitor;
}
/**
* Enumeration of possible states of a site.
*/
public enum State {
/**
* Uninitialized.
*/
Null,
/**
* Initialized.
*/
Initialized,
/**
* Standing by to acquire a job.
*/
StandingBy,
/**
* A job has been acquired.
*/
JobAcquired,
/**
* Running the acquired job.
*/
Running,
/**
* Job has been paused.
*/
Paused,
/**
* Some error has occurred and the site is in an invalid state.
*/
Invalid
};
/**
* Node state
*/
private State state = State.Null;
/**
* Combined monitor to measure load and event rate.
*/
private EventRateLoadMonitor monitor = null;
private PartMap partMap = null;
// ///////////////////////////////////////
// Cluster of which this Site is a member.
private Cluster cluster = null;
public void setCluster(Cluster cluster) {
this.cluster = cluster;
}
public Cluster cluster() {
return cluster;
}
// ///////////////////////////////////////
// Status information for this node.
private WritableConfigMap info = null;
public WritableConfigMap info() {
return info;
}
// ///////////////////////////////////////
// Job running in this site.
private Job job = null;
public Job job() {
return job;
}
// ///////////////////////////////////////
// Job List. job is acquired from here.
private JobList jobList = null;
public JobList jobList() {
return jobList;
}
public void setJobList(JobList jobList) {
this.jobList = jobList;
}
// ///////////////////////////////////////
// Part List
private PartList partList = null;
public PartList partList() {
return partList;
}
public void setPartList(PartList partList) {
this.partList = partList;
}
// ///////////////////////////////////////
// Registry with services etc
private SiteRegistry registry = new SiteRegistry();
private String name = null;
public String name() {
return name;
}
// Specs of this site.
private ConfigMap spec;
public ConfigMap spec() {
return spec;
}
// Initializer
public interface Initializer {
void initialize(Site site);
}
Initializer initializer = null;
public void setInitializer(Initializer initializer) {
this.initializer = initializer;
}
public Site(String name, ConfigMap spec) {
this.name = name;
this.spec = spec;
}
}
<file_sep>/src/main/java/io/s4/zeno/coop/DistributedSequenceTest.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.coop;
import io.s4.zeno.util.ZooKeeperHelper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.PropertyConfigurator;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
public class DistributedSequenceTest implements Watcher {
public static void main(String[] arg) throws IOException {
PropertyConfigurator.configure("log4j.properties");
// need an even number of args
if (arg.length == 0 || arg.length % 2 == 1) {
System.err.println("Usage: DistributedSequenceTest start1 length1 [start2 length2 ...]");
System.exit(1);
}
List<Integer> start = new ArrayList<Integer>();
List<Integer> length = new ArrayList<Integer>();
int i = 0;
for (String t : arg) {
if (i % 2 == 0)
start.add(new Integer(t));
else
length.add(new Integer(t));
++i;
}
DistributedSequenceTest test = new DistributedSequenceTest("localhost:2181",
5000);
int last = test.spawn(start, length);
try {
Thread.sleep(last);
} catch (InterruptedException e) {
System.err.println("Interrupted: " + e);
}
System.out.println("Should be done now");
}
DistributedSequence sequence = null;
String connect = "";
int timeout = 5000;
public DistributedSequenceTest(String connect, int timeout) {
this.connect = connect;
this.timeout = timeout;
}
public void process(WatchedEvent e) {
System.out.println("Received a notification: " + e);
}
private int spawn(List<Integer> start, List<Integer> length)
throws IOException {
if (sequence == null) {
ZooKeeper zk = new ZooKeeper(connect, timeout, this);
sequence = new DistributedSequence(new ZooKeeperHelper(zk, 3, 5000),
"/tmp/dsequence");
}
int total = 0;
int st = 0;
for (int i = 0; i < start.size(); ++i) {
st += start.get(i);
TestRunner r = new TestRunner(i, st, length.get(i));
(new Thread(r)).start();
if (st > total)
total = st + length.get(i);
else
total += length.get(i);
}
return total;
}
public static class Item implements DistributedSequence.Item {
String message = "";
public int length = 0;
Item(String m, int t) {
message = m;
length = t;
}
public byte[] getSequenceData() {
return message.getBytes();
}
public void doHeadAction() {
System.out.println("Reached Head: [" + message + "]. Processing...");
try {
Thread.sleep(length);
} catch (InterruptedException e) {
System.out.println("Interrupted [" + message + "]");
}
System.out.println("Done [" + message + "]");
}
public String getMessage() {
return message;
}
}
private class TestRunner implements Runnable {
private int id = 0;
private int start = 0;
private Item item = null;
public TestRunner(int id, int start, int length) {
this.id = id;
this.start = start;
item = new Item("Id:" + id, length);
}
public void run() {
try {
Thread.sleep(start);
} catch (InterruptedException e) {
System.out.println("Interrupted [" + item.getMessage() + "]");
}
System.out.println("Adding [" + item.getMessage() + "]");
DistributedSequence.SequencedItem qi = sequence.add(item);
if (qi == null)
System.out.println("Returned null SequencedItem for "
+ item.getMessage());
try {
while (!qi.isDone())
Thread.sleep(1000);
System.out.println("Task " + id + ": state changed to DONE");
} catch (InterruptedException e) {
System.err.println("Interrupted.");
}
}
}
}
<file_sep>/src/main/java/io/s4/zeno/config/JSONConfigMap.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.config;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// TODO: Auto-generated Javadoc
/**
* The Class JSONConfigMap.
*/
public class JSONConfigMap implements WritableConfigMap {
/** The Constant logger. */
private static final Logger logger = Logger.getLogger(JSONConfigMap.class);
/** The config. */
protected volatile JSONObject config = null;
/**
* Instantiates a new jSON config map.
*/
public JSONConfigMap() {
}
/**
* Instantiates a new jSON config map.
*
* @param x
* the x
*/
public JSONConfigMap(JSONConfigMap x) {
this.config = x.config;
}
/**
* Instantiates a new jSON config map.
*
* @param config
* the config
*/
public JSONConfigMap(JSONObject config) {
this.config = config;
}
/**
* Instantiates a new jSON config map.
*
* @param configStr
* the config str
*/
public JSONConfigMap(String configStr) {
try {
this.config = new JSONObject(configStr);
} catch (JSONException e) {
logger.error("error parsing json: " + e);
}
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#get(java.lang.String)
*/
public String get(String key) {
return get(key, null);
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getList(java.lang.String)
*/
public String[] getList(String key) {
if (config == null) return new String[0];
JSONArray ja = config.optJSONArray(key);
if (ja == null) return new String[0];
int n = ja.length();
String[] a = new String[n];
for (int i = 0; i < n; ++i) {
a[i] = ja.optString(i);
}
return a;
}
/**
* Gets the.
*
* @param key
* the key
* @param v
* the v
* @return the string
*/
public String get(String key, String v) {
return (config == null ? v : config.optString(key, v));
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getInt(java.lang.String, int)
*/
public int getInt(String key, int v) {
return (config == null ? v : config.optInt(key, v));
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getIntList(java.lang.String)
*/
public int[] getIntList(String key) {
if (config == null) return new int[0];
JSONArray ja = config.optJSONArray(key);
if (ja == null) return new int[0];
int n = ja.length();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = ja.optInt(i);
}
return a;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getDouble(java.lang.String, double)
*/
public double getDouble(String key, double v) {
return (config == null ? v : config.optDouble(key, v));
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getDoubleList(java.lang.String)
*/
public double[] getDoubleList(String key) {
if (config == null) return new double[0];
JSONArray ja = config.optJSONArray(key);
if (ja == null) return new double[0];
int n = ja.length();
double[] a = new double[n];
for (int i = 0; i < n; ++i) {
a[i] = ja.optDouble(i);
}
return a;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getLong(java.lang.String, long)
*/
public long getLong(String key, long v) {
return (config == null ? v : config.optLong(key, v));
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getLongList(java.lang.String)
*/
public long[] getLongList(String key) {
if (config == null) return new long[0];
JSONArray ja = config.optJSONArray(key);
if (ja == null) return new long[0];
int n = ja.length();
long[] a = new long[n];
for (int i = 0; i < n; ++i) {
a[i] = ja.optLong(i);
}
return a;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getBoolean(java.lang.String,
* boolean)
*/
public boolean getBoolean(String key, boolean v) {
return (config == null ? v : config.optBoolean(key, v));
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.ConfigMap#getBooleanList(java.lang.String)
*/
public boolean[] getBooleanList(String key) {
if (config == null) return new boolean[0];
JSONArray ja = config.optJSONArray(key);
if (ja == null) return new boolean[0];
int n = ja.length();
boolean[] a = new boolean[n];
for (int i = 0; i < n; ++i) {
a[i] = ja.optBoolean(i);
}
return a;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return config.toString();
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.WritableConfigMap#set(java.lang.String,
* java.lang.String)
*/
public boolean set(String key, String value) {
try {
this.config.put(key, value);
return true;
} catch (JSONException e) {
logger.error("error setting " + key + "=" + value + ": ", e);
return false;
}
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.config.WritableConfigMap#remove(java.lang.String)
*/
public boolean remove(String key) {
this.config.remove(key);
return true;
}
public boolean save() {
// saving is not applicable here.
return true;
}
public WritableConfigMap chroot(String root) {
return new RootedWritableConfigMap(root, this);
}
}
<file_sep>/src/main/java/io/s4/zeno/Part.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno;
import io.s4.zeno.resource.TimeSliceResource;
import io.s4.zeno.util.ZenoDefs;
import org.apache.log4j.Logger;
/**
* A segment of events that are processed by a Job.
*
* A Part is typically obtained from a PartList. Each Part measures its resource
* usage.
*/
public class Part implements Comparable<Part> {
private static Logger logger = Logger.getLogger(Part.class);
public byte[] getData() {
// TODO: extract data from site, related to this part
return ZenoDefs.emptyBytes;
}
public Part(Job job, EventMonitor monitor, int group, int key) {
this.monitor = monitor;
this.job = job;
this.id = new Id(group, key);
this.state = State.Null;
}
public Part(Job job, EventMonitor monitor, Id id) {
this.monitor = monitor;
this.job = job;
this.id = id.clone();
this.state = State.Null;
}
public enum State {
Null,
Running,
Paused,
Invalid
};
State state;
// State changes
public void start() {
if (state == State.Null) {
job.site().partList().markStarted(id);
state = State.Running;
}
}
public void stop() {
if (state == State.Running) {
job.site().partList().unmarkStarted(id);
state = State.Null;
}
}
public void pause() {
if (state == State.Running) {
job.site().partList().markPaused(id);
state = State.Paused;
}
}
public void unpause() {
if (state == State.Paused) {
job.site().partList().unmarkPaused(id);
state = State.Running;
}
}
public void forget() {
}
// Identity
public static class Id implements Cloneable, Comparable<Id> {
public final int group;
public final int key;
public Id(int group, int key) {
this.group = group;
this.key = key;
}
public static Id fromString(String idStr) {
String[] pieces = idStr.split(":");
if (pieces.length == 2) {
try {
int group = Integer.parseInt(pieces[0], 16);
int key = Integer.parseInt(pieces[1], 16);
return new Id(group, key);
} catch (NumberFormatException e) {
logger.error("malformed hex number in Id: " + idStr, e);
}
} else {
logger.error("incorrect number of parts in Id. "
+ "expected GROUP:KEY (hex values); got: " + idStr);
}
return null;
}
public String toString() {
return String.format("%08X:%08X", group, key);
}
@Override
public boolean equals(Object o) {
if (o instanceof Id) {
Id that = (Id) o;
return (this.group == that.group) && (this.key == that.key);
}
return false;
}
public int hashCode() {
return (group << 16) | (key & 0x0000FFFF);
}
public int compareTo(Id that) {
if (this.group != that.group)
return (this.group < that.group ? -1 : +1);
else if (this.key != that.key)
return (this.key < that.key ? -1 : +1);
else
return 0;
}
public Id clone() {
return new Id(group, key);
}
}
Id id;
public Id id() {
return id;
}
// Monitor
public final EventMonitor eventMonitor() {
return monitor;
}
public Resource resourceUsage() {
double usage = monitor.getEventLength() * monitor.getEventRate();
return new TimeSliceResource(usage);
}
public String toString() {
return id.toString();
}
// Order parts in decreasing order of resource usage
public int compareTo(Part other) {
return this.resourceUsage().compareTo(other.resourceUsage());
}
// Params
protected final EventMonitor monitor;
protected final Job job;
// A taken-over part
public static class Taken extends Part {
Taken(Job job, EventMonitor monitor, Id id) {
super(job, monitor, id);
}
private boolean takeoverDone = false;
public void start() {
if (takeoverDone)
super.start();
else
takeoverStart();
}
protected void takeoverStart() {
if (!takeoverDone) {
// update routing information
job.site().partList().markTakenOver(id, job);
takeoverDone = true;
}
}
}
}<file_sep>/src/main/java/io/s4/zeno/statistics/PoissonEstimator.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.statistics;
/**
* Estimate event arrival rate Poisson arrivals.
* <p>
* If events arrive as a Poisson process with rate {@code r}, then the
* inter-arrival times are exponentially distributed with mean {@code 1/r}.
* PoissonEventMonitor estimates the rate {@code r} as the reciprocal of the
* exponential moving average of the inter-arrival times.
* <p>
* For {@code n} events, numbered 1, 2, 3, ..., n:
*
* <pre>
* r = 1 / EMA<sub>h</sub>(dT<sub>2</sub>, dT<sub>3</sub>, ..., dT<sub>n</sub>)
*
* Where:
* * dT<sub>k</sub> = T<sub>k</sub> - T<sub>k-1</sub>
* * T<sub>1</sub>, T<sub>2</sub>, ..., T<sub>n</sub> are the arrival times
* * EMA<sub>h</sub> is the exponential moving average with refresh parameter h
* </pre>
*
* The refresh parameter {@code h} is the weight of the last element in the
* sequence. See {@link ExponentialMovingAverage} for how this parameter relates
* to the half-life of the average.
*/
public class PoissonEstimator implements RateEstimator {
private final Average avgT;
private long last = 0;
/**
* Constructor
*
* @param refresh
* refresh parameter of underlying exponential moving average.
*/
public PoissonEstimator(double refresh) {
avgT = new ExponentialMovingAverage(refresh);
last = System.currentTimeMillis();
}
public void putEvent() {
long now = System.currentTimeMillis();
avgT.put(now - last);
last = now;
}
public double getRate() {
if (!avgT.empty()) {
long now = System.currentTimeMillis();
// pretend that an event occurred at this time. So call
// phantomGet(...)
return 1000.0 / avgT.phantomGet(now - last);
}
return 0.0;
}
public long getMillisSinceLastEvent() {
if (!avgT.empty()) {
long now = System.currentTimeMillis();
return (now - last);
}
return Long.MAX_VALUE;
}
}
<file_sep>/src/main/java/io/s4/zeno/route/Hasher.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.route;
import io.s4.zeno.Part;
import java.util.List;
public interface Hasher {
Part.Id hash(int group, int key);
void rebuild(List<Part.Id> partIds);
}
<file_sep>/src/main/java/io/s4/zeno/protocol/Connection.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.protocol;
import io.s4.zeno.config.ConfigMap;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import org.apache.log4j.Logger;
// TODO: Auto-generated Javadoc
/**
* The Class Connection.
*/
public class Connection {
/** The Constant logger. */
private static final Logger logger = Logger.getLogger(Connection.class);
/** The psock. */
private Socket psock = null;
/** The dsock. */
private Socket dsock = null;
/** The out. */
public PrintWriter out = null;
/** The in. */
public BufferedReader in = null;
/** The data out. */
public BufferedOutputStream dataOut = null;
/** The data in. */
public BufferedInputStream dataIn = null;
/**
* Instantiates a new connection.
*
* @param psock
* the psock
* @param dsock
* the dsock
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public Connection(Socket psock, Socket dsock) throws IOException {
this.psock = psock;
this.dsock = dsock;
out = new PrintWriter(psock.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(psock.getInputStream()));
dataOut = new BufferedOutputStream(dsock.getOutputStream());
dataIn = new BufferedInputStream(dsock.getInputStream());
}
/**
* Close.
*/
public void close() {
try {
if (in != null) in.close();
if (out != null) out.close();
if (psock != null) psock.close();
in = null;
out = null;
psock = null;
} catch (IOException e) {
logger.error("could not close protocol socket connection", e);
}
try {
if (dataIn != null) dataIn.close();
if (dataOut != null) dataOut.close();
if (dsock != null) dsock.close();
dataIn = null;
dataOut = null;
dsock = null;
} catch (IOException e) {
logger.error("could not close data socket connection", e);
}
}
/**
* Creates the to.
*
* @param taker
* the taker
* @return the connection
*/
public static Connection createTo(ConfigMap taker) {
String name = taker.get("name");
String host = taker.get("IPAddress");
int pport = taker.getInt("port.receive.protocol", -1);
int dport = taker.getInt("port.receive.data", -1);
if (host == null || pport < 0 || dport < 0) {
logger.error("cannot create connection to taker " + name
+ ". insufficient information");
return null;
}
Socket psock = null;
Socket dsock = null;
Connection conn = null;
try {
logger.debug("protocol sock to " + name + " at " + host + ":"
+ pport);
psock = new Socket(host, pport);
logger.debug("data sock to " + name + " at " + host + ":" + dport);
dsock = new Socket(host, dport);
conn = new Connection(psock, dsock);
return conn;
} catch (IOException e0) {
logger.error("could not connect to taker " + name, e0);
try {
if (psock != null) psock.close();
} catch (IOException e) {
}
try {
if (dsock != null) dsock.close();
} catch (IOException e) {
}
return null;
}
}
}<file_sep>/src/main/java/io/s4/zeno/service/Housekeeping.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.service;
import io.s4.zeno.Service;
import io.s4.zeno.Site;
/**
* Periodically save site info.
*/
public class Housekeeping extends Service {
private final Site site;
public Housekeeping(Site site) {
this.site = site;
setInitialDelay(0, 5000);
setDelay(5000);
}
@Override
protected void action() {
site.info().save();
}
}
<file_sep>/README.txt
# I. Installing packages before building
mvn install:install-file -DgroupId=org.apache.hadoop -DartifactId=zookeeper -Dversion=3.1.1 -Dpackaging=jar -Dfile=$PATH_TO_ZOOKEEPER_JAR
# II. Build
mvn clean package assembly:assembly
# III. Set up directories in zookeeper.
# 1. Start a ZooKeeper server
# 2. Use the zkCli.sh script provided with Zookeeper
zkCli.sh < /src/main/resources/s4-cluster.cmds
# IV. Start a Zeno Console
# In a separate window (you may omit rlwrap, if it is not installed on the system):
rlwrap java -cp target/zeno-0.1.0.0-jar-with-dependencies.jar:target/zeno-0.1.0.0.jar io.s4.zeno.console.Main localhost /s4cluster
# V. Start some Sites
# In separate windows:
SITE1: java -cp target/zeno-0.1.0.0-jar-with-dependencies.jar:target/zeno-0.1.0.0.jar io.s4.zeno.SiteTest SITE1 localhost /s4cluster "{port.event:12344,port.receive.protocol:21344,port.receive.data:13244}"
SITE2: java -cp target/zeno-0.1.0.0-jar-with-dependencies.jar:target/zeno-0.1.0.0.jar io.s4.zeno.SiteTest SITE2 localhost /s4cluster "{port.event:12345,port.receive.protocol:21345,port.receive.data:13245}"
# VI. Generate Load
# In the console window (IV)
loadgen src/main/resources/high-100.txt
# VII. Notice that the 2 sites are now overloaded and try to shed load.
# Start a third site to take over the load.
SITE3: java -cp target/zeno-0.1.0.0-jar-with-dependencies.jar:target/zeno-0.1.0.0.jar io.s4.zeno.SiteTest SITE3 localhost /s4cluster "{port.event:12346,port.receive.protocol:21346,port.receive.data:13246}"
# Now observe as parts are transferred.
<file_sep>/src/main/java/io/s4/zeno/PartAcquirer.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno;
import io.s4.zeno.config.ConfigMap;
import io.s4.zeno.monitor.PoissonEventMonitor;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* Logic for acquiring parts from a part list based on job configuration.
*/
public class PartAcquirer {
private final static Logger logger = Logger.getLogger(PartAcquirer.class);
// factory for generating monitors for each part
private final EventMonitor.Factory monitorFactory;
// Job with which this acquirer is associated.
private final Job job;
/**
* Construct an acquirer in the context of a job.
*
* @param job
*/
public PartAcquirer(Job job) {
this.job = job;
// initialize monitor factory.
ConfigMap partMonitorSpec = job.spec("part.monitor");
monitorFactory = new PoissonEventMonitor.Factory(partMonitorSpec);
}
/**
* Try to acquire a set of parts. The number of parts acquired is guaranteed
* to be not more than {@code n}. The PartList associated with the site is
* used to acquire the parts.
*
* @param n
* number of parts desired.
*
* @return list of Parts that have been acquired.
*
*/
public List<Part> acquire(int n) {
logger.debug("attempting to acquire " + n + " parts");
List<Part.Id> partIds = job.site().partList().acquire(n);
List<Part> parts = new ArrayList<Part>(partIds.size());
for (Part.Id id : partIds) {
logger.debug("adding partid " + id);
EventMonitor monitor = monitorFactory.getInstance();
Part part = new Part(job, monitor, id);
parts.add(part);
}
logger.debug("acquired " + partIds.size() + " parts");
return parts;
}
/**
* Take over a part. This operation simply creates and returns a new
* {@link Part.Taken} instance.
*
* @param id
* identifier of part
* @return new part instance.
*/
public Part takeover(Part.Id id) {
logger.debug("taking over partid " + id);
EventMonitor monitor = monitorFactory.getInstance();
return new Part.Taken(job, monitor, id);
}
}
<file_sep>/src/main/java/io/s4/zeno/config/WritableConfigMap.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.config;
// TODO: Auto-generated Javadoc
/**
* The Interface WritableConfigMap.
*/
public interface WritableConfigMap extends ConfigMap {
/**
* Sets the.
*
* @param key
* the key
* @param value
* the value
* @return true, if successful
*/
public boolean set(String key, String value);
/**
* Removes the.
*
* @param key
* the key
* @return true, if successful
*/
public boolean remove(String key);
/**
* Save the map to a backing store, if one exists.
*/
public boolean save();
public WritableConfigMap chroot(String root);
}<file_sep>/src/main/java/io/s4/zeno/protocol/ConnectionListener.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.protocol;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;
public class ConnectionListener {
/** The Constant logger. */
private static final Logger logger = Logger.getLogger(ConnectionListener.class);
/** The psock server. */
private ServerSocket psockServer = null;
/** The dsock server. */
private ServerSocket dsockServer = null;
public ConnectionListener(ServerSocket psockServer, ServerSocket dsockServer) {
this.psockServer = psockServer;
this.dsockServer = dsockServer;
}
public static ConnectionListener createInstance(int pport, int dport) {
logger.debug("creating protocol and data ports. proto=" + pport
+ " data=" + dport);
ServerSocket psockServer;
ServerSocket dsockServer;
try {
psockServer = new ServerSocket(pport);
} catch (IOException e) {
logger.error("could not create server socket on pport " + pport
+ ": " + e);
return null;
}
try {
dsockServer = new ServerSocket(dport);
} catch (IOException e) {
logger.error("could not create server socket on dport " + dport
+ ": " + e);
try {
psockServer.close();
} catch (IOException e1) {
logger.error("error closing server socket at pport " + pport
+ " after failing to create server socket at dport "
+ dport);
}
return null;
}
return new ConnectionListener(psockServer, dsockServer);
}
/**
* Good.
*
* @return true, if successful
*/
public boolean good() {
return psockServer != null && dsockServer != null;
}
/**
* Accept.
*
* @return the connection
*/
public Connection accept() {
try {
Socket psock = psockServer.accept();
Socket dsock = dsockServer.accept();
return new Connection(psock, dsock);
} catch (IOException e) {
logger.error("could not accept connections: " + e);
close();
return null;
}
}
/**
* Close.
*/
public void close() {
try {
if (psockServer != null) psockServer.close();
psockServer = null;
} catch (IOException e) {
logger.error("could not close protocol socket connection: " + e);
}
try {
if (dsockServer != null) dsockServer.close();
dsockServer = null;
} catch (IOException e) {
logger.error("could not close data socket connection: " + e);
}
}
}<file_sep>/src/main/java/io/s4/zeno/service/LoadShedder.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.service;
import io.s4.zeno.LoadLevel;
import io.s4.zeno.Resource;
import io.s4.zeno.Service;
import io.s4.zeno.Site;
import io.s4.zeno.protocol.helper.PartOffloader;
import io.s4.zeno.resource.FlexibleResource;
import io.s4.zeno.resource.FlexibleTimeSliceResource;
import io.s4.zeno.resource.TimeSliceResource;
import org.apache.log4j.Logger;
/**
* If load is high, shed some work to other nodes in the cluster.
*/
public class LoadShedder extends Service {
private static final Logger logger = Logger.getLogger(LoadShedder.class);
public LoadShedder(Site site) {
this.site = site;
offloader = new PartOffloader(site);
setInitialDelay(30000, 60000);
setDelay(30000);
}
private Site site;
private PartOffloader offloader;
/*
* (non-Javadoc)
*
* @see io.s4.zeno.coop.BackgroundLoop#action()
*/
public void action() {
if ((site.loadMonitor().getLevel() == LoadLevel.High)) {
logger.info("load is high. attempting to send some parts.");
site.registry().lockAndRun("part_transfer", shedAction);
}
}
Runnable shedAction = new Runnable() {
public void run() {
Resource excessExact = site.loadMonitor().getExcessResourceUsage();
if (!(excessExact instanceof TimeSliceResource)) {
logger.error("Load Shedder only works with TimeSlice resource units.");
return;
}
final double marginLo = 0.1;
final double marginHi = 0.2;
final double expandLo = 1.2;
final double expandHi = 1.5;
final int expandCount = 5;
FlexibleResource excess = new FlexibleTimeSliceResource((TimeSliceResource)excessExact,
marginLo,
marginHi,
expandLo,
expandHi,
expandCount);
logger.info("detected excess resource usage: " + excess);
int sent = offloader.offload(excess);
if (sent > 0) {
site.eventMonitor().reset();
logger.info("reset node event monitor after sending " + sent + " parts");
site.registry().getActivityMonitor("part_transfer").tick();
}
}
};
}
<file_sep>/src/main/java/io/s4/zeno/resource/TimeSliceResource.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.resource;
import io.s4.zeno.EventMonitor;
import io.s4.zeno.Resource;
import org.apache.log4j.Logger;
// TODO: Auto-generated Javadoc
/**
* The Class TimeSliceResource.
*/
public class TimeSliceResource implements Resource {
/** The Constant logger. */
private static final Logger logger = Logger.getLogger(TimeSliceResource.class);
/** The time slice. */
protected double timeSlice;
/**
* Instantiates a new time slice resource.
*
* @param timeSlice
* the time slice
*/
public TimeSliceResource(double timeSlice) {
this.timeSlice = (timeSlice > 0.0 ? timeSlice : 0.0);
}
// type conversion from other resource types
/**
* Instantiates a new time slice resource.
*
* @param r
* the r
*/
public TimeSliceResource(Resource r) {
if (r instanceof TimeSliceResource)
this.timeSlice = ((TimeSliceResource) r).timeSlice;
else
this.timeSlice = 0.0;
}
/**
* Gets the time slice.
*
* @return the time slice
*/
public double getTimeSlice() {
return timeSlice;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.Resource#isEmpty()
*/
public boolean isEmpty() {
return this.timeSlice <= 0.0;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.Resource#canAccept(io.s4.zeno.Resource)
*/
public boolean canAccept(Resource demand) {
TimeSliceResource r = (TimeSliceResource) demand;
return this.timeSlice > r.timeSlice;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.Resource#canAcceptPartial(io.s4.zeno.Resource)
*/
public boolean canAcceptPartial(Resource demand) {
return !isEmpty();
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.Resource#reduce(io.s4.zeno.Resource)
*/
public void reduce(Resource use) {
TimeSliceResource r = (TimeSliceResource) use;
this.timeSlice -= r.timeSlice;
if (this.timeSlice < 0) this.timeSlice = 0;
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.Resource#add(io.s4.zeno.Resource)
*/
public void add(Resource use) {
TimeSliceResource r = (TimeSliceResource) use;
this.timeSlice += r.timeSlice;
}
// Natural order for Resources is: largest resource first
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Resource other) {
TimeSliceResource r = (TimeSliceResource) other;
if (this.timeSlice > r.timeSlice)
return -1;
else if (this.timeSlice < r.timeSlice)
return +1;
else {
return (this.hashCode() > other.hashCode() ? -1 : +1);
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return String.valueOf(timeSlice);
}
/**
* From string.
*
* @param s
* the s
* @return the resource
*/
public static Resource fromString(String s) {
double ts = 0.0;
try {
if (s != null) ts = Double.valueOf(s);
} catch (NumberFormatException e) {
logger.error("malformed resource string: " + s);
ts = 0.0;
}
return new TimeSliceResource(ts);
}
/*
* (non-Javadoc)
*
* @see io.s4.zeno.Resource#toBytes()
*/
public byte[] toBytes() {
return toString().getBytes();
}
/**
* From bytes.
*
* @param data
* the data
* @return the resource
*/
public static Resource fromBytes(byte[] data) {
return fromString((data != null ? (new String(data)) : null));
}
/**
* The Class Capacity.
*/
public static class Capacity {
/** The c low. */
private final double cLow;
/** The c high. */
private final double cHigh;
/**
* Instantiates a new capacity.
*
* @param cLow
* the c low
* @param cHigh
* the c high
*/
public Capacity(double cLow, double cHigh) {
this.cLow = cLow;
this.cHigh = cHigh;
}
/**
* Gets the excess.
*
* @param monitor
* the monitor
* @return the excess
*/
public Resource getExcess(EventMonitor monitor) {
double used = getUsage(monitor);
double excess = (used < cHigh ? 0.0 : (used - cHigh));
return new TimeSliceResource(excess);
}
/**
* Gets the free.
*
* @param monitor
* the monitor
* @return the free
*/
public Resource getFree(EventMonitor monitor) {
double used = getUsage(monitor);
double free = (used > cLow ? 0.0 : (cLow - used));
return new TimeSliceResource(free);
}
/**
* Gets the usage.
*
* @param monitor
* the monitor
* @return the usage
*/
private double getUsage(EventMonitor monitor) {
return monitor.getEventLength() * monitor.getEventRate();
}
}
}
<file_sep>/src/main/java/io/s4/zeno/statistics/Average.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.statistics;
/**
* Running average of a sequence of values.
*/
public abstract class Average {
private boolean _e = true;
/**
* Put a value in the sequence.
*
* @param x
* value
*/
public final void put(double x) {
update(x);
_e = false;
}
/**
* Is the sequence empty?
*
* @return true, if empty. False if atleast one value has been put.
*/
public final boolean empty() {
return _e;
}
/**
* Update the state with a value. This is where concrete implementations
* perform computations.
*
* @param x
* the value
*/
protected abstract void update(double x);
/**
* Get the current average.
*
* @return the average
*/
public abstract double get();
/**
* Compute running average assuming last element of sequence is {@code y}.
* Don't actually include it in the sequence.
*
* @param y
* hypothetical last value of sequence.
* @return average assuming last value of sequence is {@code y}
*/
public abstract double phantomGet(double y);
}
<file_sep>/src/main/java/io/s4/zeno/protocol/ProtocolLock.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.protocol;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
/**
* Re-entrant lock to manage concurrency in protocol.
*/
public class ProtocolLock {
private static final Logger logger = Logger.getLogger(ProtocolLock.class);
private ReentrantLock lock = new ReentrantLock(true);
/**
* Blocks till lock is obtained.
*
* @see #tryTransferLock()
*
* @return the transfer lock
*/
public void get() {
lock.lock();
}
/**
* Release transfer lock. This signifies the end of an operation and allows
* other operations to run.
*/
public void release() {
lock.unlock();
}
/**
* Try to obtain transfer lock within a certain amount of time.
*
* @param t
* time in milliseconds within which lock must be acquired.
* @return true, if successful. If thread is interrupted or lock could not
* be acquired within t ms, returns false.
*/
public boolean tryGet(int t) {
try {
return lock.tryLock(t, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.debug("interrupted while waiting for lock", e);
return false;
}
}
/**
* Try to obtain transfer lock. Returns immediately with status of obtaining
* lock. Note that {@ref #getTransferLock()} blocks.
*
* @return true, if lock was obtained. Otherwise false.
*/
public boolean tryGet() {
return tryGet(0);
}
public String toString() {
return lock.toString();
}
}<file_sep>/src/main/java/io/s4/zeno/util/ZenoDefs.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.util;
import java.util.List;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
// TODO: Auto-generated Javadoc
/**
* The Class ZenoDefs.
*/
public class ZenoDefs {
/** The Constant emptyBytes. */
public static final byte[] emptyBytes = {};
/** The Constant zkACL. */
public static final List<ACL> zkACL = ZooDefs.Ids.OPEN_ACL_UNSAFE;
/** The Constant emptyString. */
public static final String emptyString = "";
}<file_sep>/src/main/java/io/s4/zeno/protocol/helper/TimeSliceBalancer.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.protocol.helper;
import io.s4.zeno.Cluster;
import io.s4.zeno.LoadLevel;
import io.s4.zeno.Resource;
import io.s4.zeno.Site;
import io.s4.zeno.resource.FlexibleResource;
import io.s4.zeno.resource.FlexibleTimeSliceResource;
import io.s4.zeno.resource.TimeSliceResource;
import io.s4.zeno.service.LoadBalancer;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
/**
* Balance by reassigning partitions to make TimeSlice resource usage of each
* node close to the average across the cluster.
*
* @see LoadBalancer
*/
public class TimeSliceBalancer {
private static final Logger logger = Logger.getLogger(TimeSliceBalancer.class);
private final Site site;
private final PartOffloader offloader;
public TimeSliceBalancer(Site site) {
this.site = site;
offloader = new PartOffloader(site);
}
/**
* Perform balancing
*/
public void doBalance() {
// Precondition for balancing:
// 0. Node has recovered from previous transfers.
// 1. All nodes have some advertised free resources.
// We don't want to get in the way of load shedding.
// 2. This node does not have High load.
// 3. This node is not experiencing Low load.
// Balancing is not necessary for low load nodes. Combining
// with (1),(2), this means load level must be medium.
// 4. Free resources on this node is below average.
// Postcondition after balancing:
// 0. L.B. does not run
// 0.a. Cluster is in the realm of load shedding: some node has
// no
// advertised free resources, or
// 0.b. This node is in the realm of load shedding: experiencing
// high load, or
// 0.c. Load level is low, or
// 0.d. Node is recovering from a transfer, or
// 1. This node's free resources are within a margin of average.
if (!site.registry().getActivityMonitor("part_transfer").isSilent(5000)) {
logger.info("not balancing. node is recovering from a previous transfer");
return;
} else if (site.loadMonitor().detectLevel() != LoadLevel.Medium) {
logger.debug("not balancing. load level is "
+ site.loadMonitor().getLevel());
return;
}
// // Get info for all nodes
List<Cluster.Site> allSites = site.cluster().getAllSites();
int n = 0;
double s = 0.0;
double thisFree = 0.0;
boolean balanceRequired = true;
HashMap<String, Double> nodeFree = new HashMap<String, Double>();
for (Cluster.Site rs : allSites) {
double f = rs.info().getDouble("resource.free", -1.0);
logger.debug("advertised free resources for " + rs.name() + ": "
+ f);
if (f > 0.0) {
s += f;
++n;
if (rs == site)
thisFree = f;
else
nodeFree.put(rs.name(), f);
} else if (f <= 0.0) {
balanceRequired = false;
break;
}
}
if (!balanceRequired) {
logger.info("not balancing. some nodes have no free resources. will not get in the way of load shedding.");
return;
}
double average = s / n;
logger.info("this node free resources: " + thisFree);
logger.info("average free resources: " + average);
// nothing to do if this node has more free resources than
// average using a "hysteresis factor"
final double margin = 0.20;
if (thisFree >= average * (1 - margin)) {
logger.info("not balancing. free resources are close to or higher than average.");
return;
}
// otherwise, go over all other nodes and send some load to
// them.
logger.info("free resource is below average.");
final double marginLo = margin;
final double marginHi = margin;
final double expandLo = 1.2;
final double expandHi = 1.2;
final int expandCount = 5;
final FlexibleResource excess = new FlexibleTimeSliceResource(average
- thisFree, marginLo, marginHi, expandLo, expandHi, expandCount);
final Resource nodeFreeReserve = new TimeSliceResource(average * (1 - margin));
// do a balance action only if we can readily acquire the lock.
// don't block
Runnable balanceAction = new Runnable() {
public void run() {
int sent = offloader.offload(excess, nodeFreeReserve);
logger.info("offloaded " + sent + " partitions");
if (sent > 0) {
site.eventMonitor().reset();
site.registry().getActivityMonitor("part_transfer").tick();
}
}
};
if (!site.registry().tryLockAndRun("part_transfer", balanceAction)) {
logger.info("can't run a balance action. Another transfer is in progress.");
}
}
}<file_sep>/src/main/java/io/s4/zeno/Resource.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno;
/**
* An abstract representation of resources. Examples include fraction of time
* used for processing, CPU utilization, Memory usage, etc.
*/
public interface Resource extends Comparable<Resource> {
/**
* Checks if resource empty.
*
* @return true, if empty
*/
boolean isEmpty();
/**
* Tests if this resource is sufficient to satisfy the demanded resources.
*
* @param demand
* the demand
* @return true, if demand can be met by this resource.
*/
boolean canAccept(Resource demand);
/**
* Tests if this resource is sufficient to satisfy the demanded resources, at least partially.
*
* @param demand
* the demand
* @return true, if demand can be met at least partially
*/
boolean canAcceptPartial(Resource demand);
/**
* Reduce resource by a certain amount
*
* @param r
* the amount which it is to be reduced.
*/
void reduce(Resource r);
/**
* Add to resources.
*
* @param r
* the amount to add.
*/
void add(Resource r);
/**
* Represent resource as bytes.
*
* @return byte array representation.
*/
byte[] toBytes();
}
<file_sep>/src/main/java/io/s4/zeno/statistics/ExponentialMovingAverage.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.statistics;
/**
* Exponential moving average of a sequence of values.
*/
public class ExponentialMovingAverage extends Average {
// weighted sum
private volatile double s = 0.0;
// total weight so far: asymptotically tends to 1.
private volatile double w = 0.0;
// weight for last element of sequence.
private final double a;
/**
* Instantiate with weight.
*
* @param a
* weight for last eleent of sequence.
*/
public ExponentialMovingAverage(double a) {
this.a = a;
}
/**
* Update moving average for a sequence of values x<sub>1</sub>,
* x<sub>2</sub>, ..., x<sub>i</sub>
*
* <pre>
* s<sub>i</sub> = (1 - a) * s<sub>i-1</sub> + a * x<sub>i</sub>
* w<sub>i</sub> = (1 - a) * w<sub>i-1</sub> + a
*
* s<sub>0</sub> = 0
* w<sub>0</sub> = 0
*
* For i > 0: avg<sub>i</sub> = s<sub>i</sub> / w<sub>i</sub>
*
* @see io.s4.zeno.statistics.Average#update(double)
*/
protected void update(double x) {
s = (1 - a) * s + a * x;
w = (1 - a) * w + a;
}
public double get() {
return s / w;
}
/**
* Moving average for a sequence of values x<sub>1</sub>, x<sub>2</sub>, ...
* assuming a hypothetical value y as the last element of sequence.
*
* <pre>
* s = (1 - a) * s<sub>i</sub> + a * y
* w = (1 - a) * w<sub>i</sub> + a
*
* avg = s / w
*
* s<sub>i</sub> = (1 - a) * s<sub>i-1</sub> + a * x<sub>i</sub>
* w<sub>i</sub> = (1 - a) * w<sub>i-1</sub> + a
*
* s<sub>0</sub> = 0
* w<sub>0</sub> = 0
*
* @see #update(double)
* @see io.s4.zeno.statistics.Average#phantomGet(double)
*/
public double phantomGet(double y) {
double s1 = (1 - a) * s + a * y;
double w1 = (1 - a) * w + a;
return s1 / w1;
}
}
<file_sep>/src/main/java/io/s4/zeno/util/ZenoError.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.util;
// TODO: Auto-generated Javadoc
/**
* The Class ZenoError.
*/
public class ZenoError extends Error {
/**
* Needed for serializable. Auto-generated by Eclipse.
*/
private static final long serialVersionUID = 66977463295004680L;
/**
* Instantiates a new zeno error.
*
* @param message
* the message
* @param cause
* the cause
*/
public ZenoError(String message, Throwable cause) {
super(message, cause);
}
/**
* Instantiates a new zeno error.
*
* @param cause
* the cause
*/
public ZenoError(Throwable cause) {
super(cause);
}
/**
* Instantiates a new zeno error.
*
* @param message
* the message
*/
public ZenoError(String message) {
super(message);
}
/**
* Instantiates a new zeno error.
*/
public ZenoError() {
super();
}
}
<file_sep>/src/main/java/io/s4/zeno/route/Router.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.route;
// TODO: Auto-generated Javadoc
/**
* The Interface Router.
*/
public interface Router {
/**
* Send.
*
* @param key
* the key
* @param data
* the data
* @return true, if successful
*/
boolean send(int group, int key, byte[] data);
/**
* Load.
*/
void load();
}
<file_sep>/src/main/java/io/s4/zeno/coop/NonblockingLocksetTest.java
/*
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License. See accompanying LICENSE file.
*/
package io.s4.zeno.coop;
import io.s4.zeno.util.ZooKeeperHelper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.PropertyConfigurator;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
// TODO: Auto-generated Javadoc
/**
* The Class ZNodeHolderTest.
*/
public class NonblockingLocksetTest implements Watcher {
/**
* The main method.
*
* @param arg
* the arguments
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void main(String[] arg) throws IOException {
PropertyConfigurator.configure("log4j.properties");
// need an even number of args
if (arg.length == 0) {
System.err.println("Usage: ZNodeHolderTest size1 [size2 size3 ...] [X] [takeover1 takeover2 ...]");
System.exit(1);
}
List<Integer> size = new ArrayList<Integer>();
List<String> take = new ArrayList<String>();
boolean sizes = true;
for (String t : arg) {
if (t.equals("X")) {
sizes = false;
continue;
}
if (sizes)
size.add(new Integer(t));
else
take.add(t);
}
NonblockingLocksetTest test = new NonblockingLocksetTest("localhost:2181", 5000);
test.spawn(size, take);
}
/** The connect. */
String connect = "";
/** The timeout. */
int timeout = 5000;
/**
* Instantiates a new z node holder test.
*
* @param connect
* the connect
* @param timeout
* the timeout
*/
public NonblockingLocksetTest(String connect, int timeout) {
this.connect = connect;
this.timeout = timeout;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent)
*/
public void process(WatchedEvent e) {
System.out.println("Received a notification: " + e);
}
/** The zk. */
private ZooKeeper zk = null;
/**
* Spawn.
*
* @param size
* the size
* @param take
* the take
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void spawn(List<Integer> size, List<String> take)
throws IOException {
if (zk == null) zk = new ZooKeeper(connect, timeout, this);
ZooKeeperHelper zookeeper = new ZooKeeperHelper(zk, 3, 5000);
for (Integer s : size) {
TestRunner r = new TestRunner(s, zookeeper);
(new Thread(r)).start();
}
System.out.println("Sleeping a second...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("interrupted: " + e);
}
NonblockingLockset holder = new NonblockingLockset(zookeeper, "/tmp/grab");
for (String t : take) {
if (holder.takeover(t))
System.out.println("Taken over: " + t);
else
System.out.println("Takeover failed: " + t);
}
}
/**
* The Class TestRunner.
*/
private class TestRunner implements Runnable {
/** The s. */
private int s = 0;
/** The holder. */
NonblockingLockset holder = null;
/**
* Instantiates a new test runner.
*
* @param s
* the s
* @param zk
* the zk
*/
public TestRunner(int s, ZooKeeperHelper zk) {
this.s = s;
holder = new NonblockingLockset(zk, "/tmp/grab");
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run() {
System.out.println("Grabbing " + s + " nodes.");
List<String> names = holder.acquire(s);
if (names == null) {
System.out.println("Got null names set");
return;
}
System.out.println("Wanted " + s + ": got " + names);
}
}
}
| 28caac54256a561f74b16bcb7bffafe35880181d | [
"Java",
"Text"
] | 36 | Java | magicbill/zeno | 7c088d1a1230ac68c6280458105a7ed35ca4a67f | 493e13f23e778e84919a515dbbd72cc6ec8bed12 |
refs/heads/master | <repo_name>Vellyus/name_length<file_sep>/name_length.js
var firstName = prompt("What is your first name?");
firstName = firstName.toUpperCase();
var lastName = prompt("What is your last name?");
lastName = lastName.toUpperCase();
var nameLength = ((firstName + " " + lastName).length);
alert("The string " + "\"" + firstName + " " + lastName + "\"" + " is " + nameLength + " characters long.");
// alert message: The string "<NAME>" is 12 characters long.<file_sep>/README.md
# name_length
Counts how long your name is. Including the space between your first and last name.
| eb93fabf54a42c5efe9bacbf214a45d4343922d6 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Vellyus/name_length | e423242ae085402697f4a790c13918c4122c3bee | 9088f8e37d5855cb46e88c436720516eaccd538a |
refs/heads/master | <file_sep>import React from 'react';
import Auth from '~a/Auth.js';
// import firebase from 'firebase';
// import * as firebaseui from 'firebaseui';
function App() {
return (
<div className="App">
Learn React
<Auth />
</div>
);
}
export default App;
<file_sep>import React from "react";
import styles from './Auth.module.css';
// className: styles.input,
// https://github.com/firebase/firebaseui-web#demo
// https://fir-ui-demo-84a6c.firebaseapp.com/
class AuthDialog extends React.Component {
// constructor(props) {
// super(props);
// };
render() {
let spanStyle = {
color: 'blue',
display : 'inline',
paddingLeft : '15px'
};
return (
<div>
<div className="firebaseui-card-content">
AUTH Starts
<div>
<button>
<img className={styles.ImgIcon} alt=""
src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg">
</img>
<span style={spanStyle}>Sign in with Google</span>
</button>
</div>
<div>
<button>
<img className={styles.ImgIcon + ' ' + styles.bgr1} alt=""
src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/facebook.svg">
</img>
<span style={spanStyle}>Sign in with Facebook</span>
</button>
</div>
<div>
<button>
<img className={styles.ImgIcon + ' ' + styles.bgr2} alt=""
src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/mail.svg">
</img>
<span style={spanStyle}>Sign in with email</span>
</button>
</div>
</div>
</div>
);
}
}
export default AuthDialog; | 609d79ff65c87c43cf44da443aa91b6479a70a1d | [
"JavaScript"
] | 2 | JavaScript | Ulibka68/Firebase-auth-test | c445af5d5e110d723161f14b4a6e3140624d514d | 9e0c5152532c53671faf15e6c8f4cfda77443621 |
refs/heads/master | <repo_name>Jay-wj/big-event<file_sep>/assets/js/user/user_info.js
$(function() {
getInfo()
let form = layui.form
let layer = layui.layer
function getInfo() {
axios.get("/my/userinfo").then(res => {
let data = res.data.data
//给表单赋值
form.val("form", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
"username": data.username,
"nickname": data.nickname,
"email": data.email,
"id": data.id
});
})
}
form.verify({
username: function(value, item){ //value:表单的值、item:表单的DOM对象
if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
return '用户名不能有特殊字符';
}
}
})
$("form").on('submit',function(e) {
e.preventDefault()
let data = $(this).serialize()
console.log(data);
axios.post("/my/userinfo",data).then(res => {
console.log(res);
if(res.data.status !== 0){
return layer.msg('修改出错!');
}
window.parent.getUserInfo()
})
})
$("form").on('reset',function(e) {
e.preventDefault()
getInfo()
})
})<file_sep>/assets/js/ajaxBase.js
// 配置根路径
axios.defaults.baseURL = 'http://ajax.frontend.itheima.net';
// 配置拦截器
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
if(config.url.indexOf('/my') !== -1){
config.headers.Authorization = localStorage.getItem('token')
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
// 响应回的数据身份认证失败,删除token,并跳回登录页
if(response.data.status === 1 && response.data.message === '身份认证失败!'){
// 删除token
localStorage.removeItem('token')
// 跳回登录页
location.href = '/login.html'
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});<file_sep>/assets/js/user/user_resetpwd.js
$(function() {
let form = layui.form
$("form").on('submit',function(e) {
e.preventDefault()
let data = $(this).serialize()
console.log(data);
axios.post("/my/updatepwd",data).then(res => {
console.log(res);
if(res.data.status !== 0){
return layer.msg('修改失败!');
}
layer.msg('修改密码成功!');
$("form")[0].reset()
})
})
form.verify({
pass: [/^[\S]{6,12}$/, "密码必须6到12位,且不能出现空格"],
newPwd:function(val) {
if($("[name=oldPwd]").val() === val) return "与原密码一致";
},
// 两次输入的密码必须一致
samePass: function (value, item) {
// 两次密码进行比较判断,是否一致,如果不一致,出现提示文字
if (value !== $("[name=newPwd]").val()) return "两次输入的新密码不一致";
},
});
}) | e6ce681a597d7aa9e3cbde466f4a9662a1620508 | [
"JavaScript"
] | 3 | JavaScript | Jay-wj/big-event | cc7881ae39270ae53e065fbd4838823a895f1320 | 1f2dc5320e68bb25755991db0adb4a74399caea8 |
refs/heads/master | <file_sep>package com.example.dubboserviceone;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableDubboConfig
@DubboComponentScan("com.example.dubboserviceone.service.dubbo")
public class DubboServiceOneApplication {
public static void main(String[] args) {
SpringApplication.run(DubboServiceOneApplication.class, args);
}
}
<file_sep># springboots-dubbo
## 实验说明
- 分为四个工程,两个service, 以及其对应的api工程,项目依赖关系为,service-one 依赖 service-one-api。service-two 依赖 service-one-api,service-two-api。
- dubbo 服务调用。 service-one-api 定义接口, service-one 负责实现。 service-two 远程调用 service-one 的rpc接口。
- 使用 jmh 在service-two 项目测试远程调用和本地内存调用的差距。
## TODO
- 本地缓存的使用 gauva loadingCache
- LUR方法实现
- 雪花算法实现<file_sep>server.port=8083
dubbo.application.name=dubbo-service-two
dubbo.application.qosPort=22223
dubbo.registry.id=zookeeper-registry
dubbo.registry.protocol=zookeeper
dubbo.registry.address=192.168.101.10:2181
dubbo.protocol.name=dubbo
dubbo.protocol.port=20883
dubbo.protocol.accesslog=dubbo-access.log
dubbo.provider.retries=0
dubbo.provider.timeout=3000
dubbo.monitor.protocol=registry
dubbo.config-center.protocol=zookeeper
dubbo.config-center.address=192.168.101.10:2181<file_sep>package com.example.dubboservicetwo;
import com.example.dubboservicetwo.service.UserService;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
@State(Scope.Thread)
public class JMHSpringbootTests {
private ConfigurableApplicationContext context;
private UserService userService;
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder().include(JMHSpringbootTests.class.getName() + ".*")
.warmupIterations(2).measurementIterations(2)
.forks(1).build();
new Runner(options).run();
}
/**
* setup初始化容器的时候只执行一次
*/
@Setup(Level.Trial)
public void init(){
String arg = "";
context = SpringApplication.run(DubboServiceTwoApplication.class,arg);
userService = context.getBean(UserService.class);
}
@Benchmark
public void test_rpc(){
System.out.println(userService.sayHello("小小"));
}
@Benchmark
public void test_local(){
System.out.println(userService.sayHelloV2("小小"));
}
}
<file_sep>package com.example.dubboserviceone.service.dubbo;
import com.example.dubboserviceone.api.StringDubboService;
import com.example.dubboserviceone.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.Service;
@Service
public class StringDubboServiceImpl implements StringDubboService {
@Override
public String getHelloStr(UserInfoVo userInfoVo) {
if(userInfoVo == null){
return null;
}
return "hello " + "来自" + userInfoVo.getAddress() +"的" + userInfoVo.getUserName() + "!";
}
}
| c8850653350823df669b18dc1e1f4716824a946d | [
"Markdown",
"Java",
"INI"
] | 5 | Java | sfqin/springboots-dubbo | 968e3a4f9f73fd3b0f1dc60ea0070a0c196e455a | 0d3e493e9d8ca3945ab11c467c9afcc2d7e02f7b |
refs/heads/master | <file_sep>/*
* Created on Jan 19, 2004
*
* Copyright (C) 2004 <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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.un4given.editorviewer.views;
import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IPageListener;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IPerspectiveListener;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.part.EditorPart;
/**
* Listener class between the model and the Viewer<p>
* @author <NAME>
*/
public class EditorViewerListener implements IPartListener2,
IPageListener,
IPerspectiveListener,
IPropertyListener {
/**
* Instance of EditorViewer for Callbacks
*/
private EditorViewer _viewer = null;
/**
* Constructor
* @param helper EditorViewer instance for Callbacks
*/
public EditorViewerListener(EditorViewer helper){
_viewer = helper;
}
public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
}
public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective, String changeId) {
if ( IWorkbenchPage.CHANGE_EDITOR_CLOSE.equals(changeId) ){
if ( page == null )
return;
IEditorReference[] refs = page.getEditorReferences();
if ( refs != null && refs.length <= 0 && _viewer.hasVisibleElements() ){
_viewer.refresh();
}
}
}
public void partOpened(IWorkbenchPartReference partRef) {
if ( !(partRef instanceof IEditorReference) )
return;
IEditorPart part = ((IEditorReference)partRef).getEditor(true);
if ( part != null )
part.addPropertyListener(this);
_viewer.addEditor((IEditorReference)partRef);
}
public void partClosed(IWorkbenchPartReference partRef) {
if ( !(partRef instanceof IEditorReference) )
return;
IEditorPart part = ((IEditorReference)partRef).getEditor(true);
if ( part != null )
part.removePropertyListener(this);
_viewer.removeEditor((IEditorReference)partRef);
}
public void partActivated(IWorkbenchPartReference partRef) {}
public void partDeactivated(IWorkbenchPartReference partRef) {}
public void partBroughtToTop(IWorkbenchPartReference partRef) {}
public void partHidden(IWorkbenchPartReference partRef) {}
public void partInputChanged(IWorkbenchPartReference partRef) {}
public void partVisible(IWorkbenchPartReference partRef) {}
/**
* Listen for any Editors to become "DIRTY" so that the Label can dictate the change
* @see org.eclipse.ui.IPropertyListener#propertyChanged(java.lang.Object, int)
*/
public void propertyChanged(Object source, int propId) {
switch (propId){
case EditorPart.PROP_DIRTY :
case EditorPart.PROP_TITLE :
if ( source instanceof IEditorPart ){
IFile file = (IFile)((IEditorPart)source).getEditorInput().getAdapter(IFile.class);
if ( file != null )
_viewer.refresh(file);
}
break;
}
}
public void pageActivated(IWorkbenchPage page) {}
public void pageClosed(IWorkbenchPage page) {}
public void pageOpened(IWorkbenchPage page) {}
}
<file_sep>/*
* Created on Jan 19, 2004
*
* Copyright (C) 2004 <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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.un4given.editorviewer.action;
import org.un4given.EditorViewerPlugin;
import org.un4given.Messages;
import org.un4given.editorviewer.views.EditorViewer;
/**
* Action to close all Editors listed in the view, not necessarily
* all open editors, in case a filter is applied to the view<p>
* <p>
* @author <NAME>
*/
public class CloseAllAction extends CloseAction {
/**
* Constructor
* @param helper EditorViewer instance for callback method
*/
public CloseAllAction(EditorViewer viewer){
super(viewer);
setImageDescriptor(EditorViewerPlugin.getImageDescriptor(Messages.getString("CloseAllAction.0"))); //$NON-NLS-1$
setToolTipText(Messages.getString("CloseAllAction.1")); //$NON-NLS-1$
setText(Messages.getString("CloseAllAction.2")); //$NON-NLS-1$
setDescription(Messages.getString("CloseAllAction.3")); //$NON-NLS-1$
}
/**
* @see org.eclipse.jface.action.Action#run()
*/
public void run(){
_viewer.closeAll();
}
}
<file_sep>EditorViewerPlugin.0=org.un4given.EditorViewerPlugin
CloseAction.0=icons/remove_co.gif
CloseAction.1=Close
CloseAction.2=Close
CloseAction.3=Close
SaveAction.0=icons/save.gif
SaveAction.1=Save
SaveAction.2=Save
SaveAction.3=Save
SaveAllAction.0=icons/saveall.gif
SaveAllAction.1=Save All
SaveAllAction.2=Save All
SaveAllAction.3=Save All
SaveAllAction.4=icons/saveall_off.gif
SortActionGroup.0=Sort...
SortActionGroup.1=sortmode
SortActionGroup.2=-end
SortActionGroup.6=icons/alpha_mode.gif
SortActionGroup.7=by Name
SortActionGroup.8=by Name
SortActionGroup.9=by Name
SortActionGroup.10=icons/alpha_mode.gif
SortActionGroup.11=by Type
SortActionGroup.12=by Type
SortActionGroup.13=by Type
SortActionGroup.14=icons/alpha_mode.gif
LinkEditorAction.0=icons/synced.gif
LinkEditorAction.1=Link with Editor
LinkEditorAction.2=Link with Editor
LinkEditorAction.3=Link with Editor
CollapseAction.0=icons/collapse.gif
CollapseAction.1=Collapse
CollapseAction.2=Collapse
CollapseAction.3=Collapse
ExpandAction.0=icons/expand.gif
ExpandAction.1=Expand
ExpandAction.2=Expand
ExpandAction.3=Expand
CollapseAllAction.0=icons/collapse.gif
CollapseAllAction.1=Collapse All
CollapseAllAction.2=Collapse All
CollapseAllAction.3=Collapse All
ExpandAllAction.0=icons/expand.gif
ExpandAllAction.1=Expand All
ExpandAllAction.2=Expand All
ExpandAllAction.3=Expand All
RefreshAction.0=icons/refresh.gif
RefreshAction.1=Refresh
RefreshAction.2=Refresh
RefreshAction.3=Refresh
LayoutActionGroup.0=Layout...
LayoutActionGroup.1=layout
LayoutActionGroup.2=-end
LayoutActionGroup.3=Hierarchical Mode
LayoutActionGroup.4=Hierarchical Mode
LayoutActionGroup.5=Hierarchical Mode
LayoutActionGroup.6=icons/fullHierarchicalLayout.gif
LayoutActionGroup.7=Flat Mode
LayoutActionGroup.8=Flat Mode
LayoutActionGroup.9=Flat Mode
LayoutActionGroup.10=icons/flatLayout.gif
LayoutActionGroup.11=Semi-Flat Mode
LayoutActionGroup.12=Semi-Flat Mode
LayoutActionGroup.13=Semi-Flat Mode
LayoutActionGroup.14=icons/semiHierarchicalLayout.gif
CloseAllAction.0=icons/removeAll_co.gif
CloseAllAction.1=Close All
CloseAllAction.2=Close All
CloseAllAction.3=Close All
EditorElement.0=*
EditorViewer.0=HIERARCHY_MODE
EditorViewer.1=LINK_MODE
EditorViewer.2=SORT_MODE
EditorViewer.3=HIERARCHY_MODE
EditorViewer.4=SORT_MODE
EditorViewer.5=LINK_MODE
EditorViewer.6=#PopupMenu
EditorViewer.7=-end
ContentProvider.0=ROOT
ContentProvider.1=Other
ContentProvider.2=
ContentProvider.3=icons/java_model_obj.gif
<file_sep>/*
* Created on Jan 19, 2004
*
* Copyright (C) 2004 <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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.un4given.editorviewer.action;
import org.eclipse.jface.action.Action;
import org.un4given.EditorViewerPlugin;
import org.un4given.editorviewer.views.EditorViewer;
/**
* Action to link/unlink the view selection with the Active Editor
* <p>
* @author <NAME>
*/
public class FilterDirtyAction extends Action {
/**
* EditorViewer for callbacks
*/
private final EditorViewer _viewer;
/**
* Linked/Unlinked mode
*/
private int _filterMode = EditorViewerPlugin.NONE_FILTER_MODE;
/**
* Constructor with the default specified linkMode
* @param viewer
* @param linkMode
*/
public FilterDirtyAction(EditorViewer viewer, int filterMode){
_filterMode = filterMode;
_viewer = viewer;
setChecked(_filterMode == EditorViewerPlugin.DIRTY_FILTER_MODE);
if ( isChecked() )
_viewer.setDirtyFileFilter(true);
}
public void setChecked(boolean checked){
super.setChecked(checked);
setImageDescriptor(EditorViewerPlugin.getImageDescriptor("icons/filter_tsk.gif")); //$NON-NLS-1$
setText("Filter Dirty Editors");
setToolTipText("Filter Dirty Editors");
setDescription("Filter Dirty Editors");
}
/**
* Link/unlink the View selection depending on the previous mode
*/
public void run(){
_viewer.setDirtyFileFilter(isChecked());
}
}
<file_sep>/*
* Created on Jan 19, 2004
*
* Copyright (C) 2004 <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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.un4given;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Retrieve properties from resource bundle
*/
public class Messages {
private static final String BUNDLE_NAME = "org.un4given.editorviewer"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE =
ResourceBundle.getBundle(BUNDLE_NAME);
/**
*
*/
private Messages() {}
/**
* @param key
* @return
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
<file_sep>/*
* Created on Jan 19, 2004
*
* Copyright (C) 2004 <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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.un4given.editorviewer.action;
import org.eclipse.jface.action.Action;
import org.un4given.EditorViewerPlugin;
import org.un4given.Messages;
import org.un4given.editorviewer.views.EditorViewer;
/**
* Action to close the Selected Editors<p>
* <p>
* @author <NAME>
*/
public class SaveAllAction extends Action {
protected EditorViewer _viewer;
/**
* Constructor
* @param helper EditorViewer instance for callback method
*/
public SaveAllAction(EditorViewer viewer){
_viewer = viewer;
setImageDescriptor(EditorViewerPlugin.getImageDescriptor(Messages.getString("SaveAllAction.0"))); //$NON-NLS-1$
setDisabledImageDescriptor(EditorViewerPlugin.getImageDescriptor(Messages.getString("SaveAllAction.4")));
setToolTipText(Messages.getString("SaveAllAction.1")); //$NON-NLS-1$
setText(Messages.getString("SaveAllAction.2")); //$NON-NLS-1$
setDescription(Messages.getString("SaveAllAction.3")); //$NON-NLS-1$
}
/**
* @see org.eclipse.jface.action.Action#run()
*/
public void run(){
_viewer.saveAll();
}
}
<file_sep><!--
Copyright (C) 2016 <NAME> <<EMAIL>>
Licensed under GPL v2 or later
-->
<project name="EditorViewer" default="all">
<property name="version" value="0.1.6.2"/>
<property name="src.dir" value="."/>
<property name="build.dir" value="build"/>
<property name="jar.name" value="${ant.project.name}-${version}.jar"/>
<property environment="env"/>
<property name="env.ECLIPSE_PLUGINS_PATH" value=""/>
<path id="eclipse.plugins.dir">
<fileset dir="${env.ECLIPSE_PLUGINS_PATH}" includes="**/*.jar"/>
</path>
<target name="clean">
<delete dir="build"/>
</target>
<target name="eclipse-plugins-path">
<fail unless="env.ECLIPSE_PLUGINS_PATH"
message="Environment variable ECLIPSE_PLUGINS_PATH is not set"/>
</target>
<target name="compile" depends="eclipse-plugins-path">
<mkdir dir="${build.dir}/classes"/>
<javac srcdir="${src.dir}/src" destdir="${build.dir}/classes"
classpathref="eclipse.plugins.dir" includeantruntime="false"/>
</target>
<target name="jar" depends="compile">
<mkdir dir="${build.dir}/jar"/>
<jar destfile="${build.dir}/jar/${jar.name}">
<manifest>
<attribute name="Bundle-ManifestVersion" value="2"/>
<attribute name="Bundle-Name" value="EditorViewer Plug-in"/>
<attribute name="Bundle-SymbolicName" value="EditorViewer; singleton:=true"/>
<attribute name="Bundle-Version" value="${version}"/>
<attribute name="Bundle-Activator" value="org.un4given.EditorViewerPlugin"/>
<attribute name="Bundle-Localization" value="plugin"/>
<attribute name="Require-Bundle" value="org.eclipse.ui,org.eclipse.core.runtime,org.eclipse.core.resources,org.eclipse.jdt.ui,org.eclipse.ui.ide,org.eclipse.wb.core.lib"/>
<attribute name="Bundle-Vendor" value="<NAME>, <NAME>"/>
<attribute name="Eclipse-AutoStart" value="true"/>
</manifest>
<fileset dir="${build.dir}/classes"/>
<zipfileset dir="${src.dir}/icons" prefix="icons"/>
<zipfileset dir="${src.dir}/org" prefix="org"/>
<fileset dir="${src.dir}" includes="plugin.xml"/>
<zipfileset dir="${src.dir}/src" prefix="src"/>
</jar>
</target>
<target name="all" depends="jar" />
<target name="install" depends="all,eclipse-plugins-path">
<copy file="${build.dir}/jar/${jar.name}" todir="${env.ECLIPSE_PLUGINS_PATH}"/>
</target>
</project>
<file_sep>package org.un4given.editorviewer.views;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorReference;
import org.un4given.EditorViewerPlugin;
public class EditorViewerLabelProvider implements ILabelProvider {
private ILabelProvider provider = null;
private EditorViewer _viewer = null;
private boolean showExtensions = true;
public EditorViewerLabelProvider(EditorViewer viewer, ILabelProvider provider){
this._viewer = viewer;
this.provider = provider;
}
public Image getImage(Object element) {
return provider.getImage(element);
}
public String getText(Object element) {
if ( _viewer.getContentProvider().getLayout() == EditorViewerContentProvider.SEMI_LAYOUT ){
if ( element instanceof IFolder ){
String name = ((IFolder)element).getName();
while ( ((IResource)( element = ((IResource)element).getParent() )).getType() != IResource.PROJECT )
name = ((IFolder)element).getName() + "/" + name;
return name.substring(0,name.length());
}
}
if ( element instanceof IFile ){
if ( _viewer.getContentProvider() != null && _viewer.getContentProvider().isFilterDirty() ){
return stripExtension(((IFile)element).getName()) + " *";
} else {
IEditorReference ref = EditorViewerPlugin.getDefault().getReference(_viewer.getSite(),(IFile)element);
if ( ref != null && ref.isDirty() )
return stripExtension(((IFile)element).getName()) + " *";
}
}
return stripExtension(provider.getText(element));
}
public boolean isLabelProperty(Object element, String property) {
return this.provider.isLabelProperty(element, property);
}
private String stripExtension(String text){
if ( !showExtensions ){
int pos = -1;
if ( text.length() > 1 && (pos = text.lastIndexOf(".") ) > 0 )
text = text.substring(0,pos);
}
return text;
}
public void addListener(ILabelProviderListener listener) {
this.provider.addListener(listener);
}
public void removeListener(ILabelProviderListener listener) {
this.provider.removeListener(listener);
}
public void dispose() {
this.provider.dispose();
}
public boolean isShowExtensions() {
return showExtensions;
}
public void setShowExtensions(boolean showExtensions) {
this.showExtensions = showExtensions;
}
}
<file_sep># Copyright (C) 2016 <NAME> <<EMAIL>>
# Licensed under GPL v2 or later
ANT = ant
.PHONY: all
all:
$(ANT) all
.PHONY: clean
clean:
$(ANT) clean
.PHONY: install
install:
$(ANT) install
<file_sep>/*
* Created on Jan 19, 2004
*
* Copyright (C) 2004 <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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.un4given.editorviewer.views;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.collections.map.MultiValueMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.un4given.EditorViewerPlugin;
/**
* Content Provider for the TreeViewer
* <p>
* @author <NAME>
*/
public class EditorViewerContentProvider extends WorkbenchContentProvider {
public static final int FLAT_LAYOUT = 0;
public static final int HIER_LAYOUT = 1;
public static final int SEMI_LAYOUT = 2;
private int layout = HIER_LAYOUT;
private EditorViewer _viewer = null;
private MultiValueMap cache = null;
private boolean filterDirty = false;
public EditorViewerContentProvider(EditorViewer viewer){
this.cache = MultiValueMap.decorate(new HashMap(), HashSet.class);
this._viewer = viewer;
refresh();
}
public void refresh(){
cache.clear();
IEditorReference[] refs = _viewer.getSite().getPage().getEditorReferences();
for ( int i = 0 ; i < refs.length ; i ++ )
add(refs[i]);
}
public void add(IEditorReference ref){
if ( ref == null )
return;
if ( filterDirty && !ref.isDirty() )
return;
IFile res = EditorViewerPlugin.getDefault().getFileForReference(ref);
if ( res == null )
return;
IResource child = res;
IResource parent = res.getParent();
if ( layout == HIER_LAYOUT ){
while ( parent != null ){
cache.put(parent,child);
child = parent;
parent = parent.getParent();
}
} else if ( layout == SEMI_LAYOUT ){
if ( parent.getType() == IResource.FOLDER ){
cache.put(parent, child);
child = parent;
parent = parent.getProject();
cache.put(parent, child);
} else if ( parent.getType() == IResource.PROJECT ){
cache.put(parent, child);
}
cache.put(child.getProject().getParent(), child.getProject());
} else if ( layout == FLAT_LAYOUT ){
cache.put(child.getProject(), child);
cache.put(child.getProject().getParent(), child.getProject());
}
}
public void remove(IEditorReference ref){
if ( ref == null )
return;
IFile res = EditorViewerPlugin.getDefault().getFileForReference(ref);
if ( res == null )
return;
IResource child = res;
IResource parent = res.getParent();
if ( layout == HIER_LAYOUT ){
while ( parent != null ){
Set set = (Set)cache.get(parent);
set.remove(child);
if ( set.size() > 0 )
return;
child = parent;
parent = parent.getParent();
}
} else if ( layout == SEMI_LAYOUT ){
if ( parent.getType() == IResource.FOLDER ){
Set set = (Set)cache.get(parent);
set.remove(child);
if ( set.size() > 0 )
return;
child = parent;
parent = parent.getProject();
set = (Set)cache.get(parent);
set.remove(child);
if ( set.size() > 0 )
return;
parent = child.getProject().getParent();
child = child.getProject();
set = (Set)cache.get(parent);
set.remove(child);
} else if ( parent.getType() == IResource.PROJECT ){
Set set = (Set)cache.get(parent);
set.remove(child);
if ( set.size() > 0 )
return;
parent = child.getProject().getParent();
child = child.getProject();
set = (Set)cache.get(parent);
set.remove(child);
}
} else if ( layout == FLAT_LAYOUT ){
parent = child.getProject();
Set set = (Set)cache.get(parent);
set.remove(child);
if ( set.size() > 0 )
return;
parent = child.getProject().getParent();
child = child.getProject();
set = (Set)cache.get(parent);
set.remove(child);
}
}
public Object[] getChildren(Object element) {
Set elements = (Set)cache.get(element);
if ( elements == null )
return new Object[]{};
return elements.toArray();
}
public Object[] getElements(Object element) {
return getChildren(element);
}
public Object getParent(Object element) {
if ( layout == FLAT_LAYOUT && element instanceof IFile )
return ((IFile)element).getProject();
else if ( layout == SEMI_LAYOUT ){
if ( element instanceof IFile )
return ((IResource)element).getParent();
else if ( element instanceof IFolder )
return ((IFolder)element).getProject();
}
return super.getParent(element);
}
public boolean hasChildren(Object element) {
return cache.containsKey(element);
}
public int getLayout() {
return layout;
}
public void setLayout(int layout) {
this.layout = layout;
_viewer.getViewer().refresh();
}
public boolean isFilterDirty() {
return filterDirty;
}
public void setFilterDirty(boolean filterDirty) {
this.filterDirty = filterDirty;
}
}
| 25cea011fd3e389d7316e47ba1a40f93714cc335 | [
"Java",
"Makefile",
"Ant Build System",
"INI"
] | 10 | Java | hartwork/eclipse-plugin-editorviewer | 5adfa83f1e7b720055b4a28b0bac0c3ca6e60f54 | c1ebc1bbd621bd12960cc1b01325cc7e0d3ceb32 |
refs/heads/master | <file_sep>import React from 'react';
import Button from 'components/Button/button.js';
import Header from 'components/Logo/logo.js';
import DangerButton from 'components/DangerButton/DangerButton.js';
import { ReactComponent as LogoSVG } from 'components/MySVGLogo/mySVG.svg';
import './App.scss';
// @flow
function App() {
return (
<div className="App">
{/* Importing Header with Logo */}
<Header />
{/* Importing Button */}
<Button />
{/* Logo svg */}
<div className="mySVGDiv">
<LogoSVG />
</div>
{/* Importing DangerButton */}
<DangerButton />
</div>
);
}
export default App;
<file_sep>import React, { Component } from 'react';
import Button from 'components/Button/button.js'; // Import a component from another file
class DangerButton extends Component {
render() {
return <Button color="red" />;
}
}
export default DangerButton;
<file_sep>import React, { Component } from 'react';
import './styles.scss'; // Tell Webpack that button.js uses these styles
class Button extends Component {
render() {
// You can use them as regular CSS styles
return (
<button className={this.props.color === 'red' ? 'button red' : 'button'}>
My Button
</button>
);
}
}
export default Button;
| 9179bf6fab9b0145faca23cb3daea4de381793a9 | [
"JavaScript"
] | 3 | JavaScript | agnenevulyte/react-playground | 943f2e7e0078dbfad9bcd91e30c830d0b380a44d | 223ea71f917910f3bfef8c5eec2a8534fbcfe9cb |
refs/heads/master | <repo_name>mohsinalimat/UICollectionViewSplitLayout<file_sep>/UICollectionViewSplitLayoutTests/UICollectionViewSplitLayout+LayoutAttributesInSectionFactoryTests.swift
//
// UICollectionViewSplitLayout+LayoutAttributesInSectionFactoryTests.swift
// UICollectionViewSplitLayoutTests
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import XCTest
@testable import UICollectionViewSplitLayout
class UICollectionViewSplitLayout_LayoutAttributesInSectionFactoryTests: XCTestCase {
var layoutAttributesInSectionFactory: UICollectionViewSplitLayout.LayoutAttributesInSectionFactory!
override func setUp() {
layoutAttributesInSectionFactory = UICollectionViewSplitLayout.LayoutAttributesInSectionFactory()
}
override func tearDown() {
layoutAttributesInSectionFactory = nil
}
func testMakeArbitorarySectionItems() {
let firstPosition = CGPoint(x: 100, y: 100)
let sectioninset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let minimumItemLineSpacing: CGFloat = 10
let numberOfItems = 4
var sizingHandlerCount: Int = 0
let itemSize = CGSize(width: 90, height: 90)
let attrsList = layoutAttributesInSectionFactory.makeItems(
for: 1,
side: .right,
numberOfItems: numberOfItems,
firstPosition: firstPosition,
contentMostLeft: 100,
contentWidth: 200,
sectionInset: sectioninset,
minimumInterItemSpacing: 10,
minimumItemLineSpacing: minimumItemLineSpacing, isNormalizing: false,
sizingHandler: { _ in
sizingHandlerCount += 1
return itemSize
}
)
let expected: CGFloat = firstPosition.y +
2 * itemSize.height +
sectioninset.top +
sectioninset.bottom +
(minimumItemLineSpacing * 1)
XCTAssertEqual(attrsList.lastPosition.y, expected, "")
XCTAssertEqual(sizingHandlerCount, 4, "")
let frames = attrsList.attributes.map { $0.frame }
let expectedFrames = [
CGRect(x: 105, y: 105, width: 90, height: 90),
CGRect(x: 205, y: 105, width: 90, height: 90),
CGRect(x: 105, y: 205, width: 90, height: 90),
CGRect(x: 205, y: 205, width: 90, height: 90)
]
XCTAssertEqual(frames, expectedFrames, "")
let indexPathes = attrsList.attributes.map { $0.indexPath }
let expectedIndexPathes = [
IndexPath(item: 0, section: 1),
IndexPath(item: 1, section: 1),
IndexPath(item: 2, section: 1),
IndexPath(item: 3, section: 1)
]
XCTAssertEqual(indexPathes, expectedIndexPathes, "")
let sides = attrsList.attributes.map { $0.side }
let expectedSides = Array(repeating: UICollectionViewSplitLayoutSide.right, count: 4)
XCTAssertEqual(sides, expectedSides, "")
let sectionInsets = attrsList.attributes.map { $0.sectionInset }
let expectedSectionInsets = Array(repeating: sectioninset, count: 4)
XCTAssertEqual(sectionInsets, expectedSectionInsets, "")
let minimumItemLineSpacings = attrsList.attributes.map { $0.minimumItemLineSpacing }
let expectedMinimumItemLineSpacing = Array(repeating: minimumItemLineSpacing, count: 4)
XCTAssertEqual(minimumItemLineSpacings, expectedMinimumItemLineSpacing, "")
}
func testMakeHeader() {
let firstPosition = CGPoint(x: 100, y: 100)
let sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let minimumItemLineSpacing: CGFloat = 10
let headerSize = CGSize(width: 100, height: 90)
let attrs = layoutAttributesInSectionFactory.makeHeader(
at: 1,
nextPosition: firstPosition,
side: .right,
sectionInset: sectionInset,
minimumItemLineSpacing: minimumItemLineSpacing,
headerSize: headerSize
)
let frame = CGRect(x: 100, y: 100, width: 100, height: 90)
XCTAssertEqual(attrs?.frame, frame, "")
let indexPath = IndexPath(item: 0, section: 1)
XCTAssertEqual(attrs?.indexPath, indexPath, "")
XCTAssertEqual(attrs?.sectionInset, sectionInset, "")
XCTAssertEqual(attrs?.minimumItemLineSpacing, minimumItemLineSpacing, "")
XCTAssertEqual(attrs?.side, .right, "")
}
func testMakeFooter() {
let firstPosition = CGPoint(x: 100, y: 100)
let sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
let minimumItemLineSpacing: CGFloat = 10
let footerSize = CGSize(width: 100, height: 90)
let attrs = layoutAttributesInSectionFactory.makeFooter(
at: 1,
nextPosition: firstPosition,
side: .right,
sectionInset: sectionInset,
minimumItemLineSpacing: minimumItemLineSpacing,
footerSize: footerSize
)
let frame = CGRect(x: 100, y: 100, width: 100, height: 90)
XCTAssertEqual(attrs?.frame, frame, "")
let indexPath = IndexPath(item: 0, section: 1)
XCTAssertEqual(attrs?.indexPath, indexPath, "")
XCTAssertEqual(attrs?.sectionInset, sectionInset, "")
XCTAssertEqual(attrs?.minimumItemLineSpacing, minimumItemLineSpacing, "")
XCTAssertEqual(attrs?.side, .right, "")
}
}
<file_sep>/UICollectionViewSplitLayoutTests/UICollectionViewSplitLayout+PinnedPositionCalculatorTest.swift
//
// UICollectionViewSplitLayout+PinnedPositionCalculatorTest.swift
// UICollectionViewSplitLayoutTests
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import XCTest
@testable import UICollectionViewSplitLayout
class UICollectionViewSplitLayout_PinnedPositionCalculatorTest: XCTestCase {
var layout: UICollectionViewSplitLayout!
var pinnedPositionCalculator: UICollectionViewSplitLayout.PinnedPositionCalculator!
var collectionVc: StubCollectionViewController!
override func setUp() {
layout = UICollectionViewSplitLayout()
pinnedPositionCalculator = UICollectionViewSplitLayout.PinnedPositionCalculator()
collectionVc = StubCollectionViewController(collectionViewLayout: layout)
UIApplication.shared.keyWindow?.rootViewController = collectionVc
collectionVc.collectionView.reloadData()
}
override func tearDown() {
pinnedPositionCalculator = nil
}
func testExecuteToHeader() {
collectionVc.collectionView.scrollToItem(at: IndexPath(item: 5, section: 0), at: .top, animated: false)
let attrs = UICollectionViewSplitLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: IndexPath(item: 0, section: 0))
let point = pinnedPositionCalculator.execute(
of: attrs,
collectionViewLayout: layout
)
XCTAssertEqual(point, collectionVc.collectionView.contentOffset, "")
}
func testExecuteToItem() {
collectionVc.collectionView.scrollToItem(at: IndexPath(item: 5, section: 0), at: .top, animated: false)
let attrs = UICollectionViewSplitLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
let point = pinnedPositionCalculator.execute(
of: attrs,
collectionViewLayout: layout
)
XCTAssertNil(point, "")
}
}
class StubCollectionViewController: UICollectionViewController, UICollectionViewDelegateSectionSplitLayout {
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide {
return .left
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
return CGSize(width: width, height: 200)
}
}
<file_sep>/iOS Sample/iOS Sample/SectionDividedCollectionViewController/SectionDividedCollectionViewCell.swift
//
// SectionDividedCollectionViewCell.swift
// iOS Sample
//
// Created by kahayash on 2018/10/06.
// Copyright © 2018 Yahoo Japan Corporation. All rights reserved.
//
import UIKit
class SectionDividedCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
<file_sep>/iOS Sample/iOS Sample/BasicCollectionViewController/BasicCollectionViewController.swift
//
// BasicCollectionViewController.swift
// iOS Sample
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import UIKit
import UICollectionViewSplitLayout
private let reuseIdentifier = "Cell"
class BasicCollectionViewController: UICollectionViewController {
@IBOutlet weak var layout: UICollectionViewSplitLayout!
var dataSource: [[UIColor]] = [
(0..<20).map { _ in .red },
(0..<20).map { _ in .blue },
(0..<20).map { _ in .green }
]
override func viewDidLoad() {
super.viewDidLoad()
layout.minimumItemLineSpacing = 8
layout.minimumInterItemSpacing = 8
layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
layout.leftSideRatio = 0.4
collectionView.collectionViewLayout = layout
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource[section].count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = dataSource[indexPath.section][indexPath.row]
return cell
}
}
extension BasicCollectionViewController: UICollectionViewDelegateSectionSplitLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
let width = layout.calculateFixedWidthRaughly(
to: 3,
of: side,
minimumInterItemSpacing: layout.minimumInterItemSpacing,
sectionInset: layout.sectionInset)
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide {
if let side = UICollectionViewSplitLayoutSide(leftSideRatio: layout.leftSideRatio) {
return side
}
return section % 2 == 0 ? .left : .right
}
}
<file_sep>/UICollectionViewSplitLayoutTests/UICollectionViewSplitLayout+LayoutAttributesInSectionFactory+ItemStackTests.swift
//
// UICollectionViewSplitLayout+LayoutAttributesInSectionFactory+ItemStackTests.swift
// UICollectionViewSplitLayoutTests
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import XCTest
@testable import UICollectionViewSplitLayout
class UICollectionViewSplitLayout_LayoutAttributesInSectionFactory_ItemStackNoneNormalizingTests: XCTestCase {
var itemCoumnStack: UICollectionViewSplitLayout.LayoutAttributesInSectionFactory.ItemColumnStack!
override func setUp() {
itemCoumnStack = UICollectionViewSplitLayout.LayoutAttributesInSectionFactory.ItemColumnStack(isNormalizing: false)
do {
let attrs = UICollectionViewSplitLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
attrs.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
itemCoumnStack.append(attrs: attrs)
}
do {
let attrs = UICollectionViewSplitLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
attrs.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
itemCoumnStack.append(attrs: attrs)
}
do {
let attrs = UICollectionViewSplitLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
attrs.frame = CGRect(x: 0, y: 0, width: 100, height: 300)
itemCoumnStack.append(attrs: attrs)
}
}
override func tearDown() {
itemCoumnStack = nil
}
func testAppend() {
XCTAssertEqual(itemCoumnStack.refinedAttrs.count, 3, "")
}
func testReset() {
itemCoumnStack.reset()
XCTAssertEqual(itemCoumnStack.refinedAttrs.count, 0, "")
}
func testMaxHeight() {
XCTAssertEqual(itemCoumnStack.maxHeight, 300, "")
}
func testNormalizedAttrs() {
XCTAssertEqual(
itemCoumnStack.refinedAttrs.map { $0.size },
[
CGSize(width: 100, height: 100),
CGSize(width: 100, height: 200),
CGSize(width: 100, height: 300)
], "")
}
}
class UICollectionViewSplitLayout_LayoutAttributesInSectionFactory_ItemStackNormalizingTests: XCTestCase {
var itemCoumnStack: UICollectionViewSplitLayout.LayoutAttributesInSectionFactory.ItemColumnStack!
override func setUp() {
itemCoumnStack = UICollectionViewSplitLayout.LayoutAttributesInSectionFactory.ItemColumnStack(isNormalizing: true)
do {
let attrs = UICollectionViewSplitLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
attrs.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
itemCoumnStack.append(attrs: attrs)
}
do {
let attrs = UICollectionViewSplitLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
attrs.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
itemCoumnStack.append(attrs: attrs)
}
do {
let attrs = UICollectionViewSplitLayoutAttributes(forCellWith: IndexPath(item: 0, section: 0))
attrs.frame = CGRect(x: 0, y: 0, width: 100, height: 300)
itemCoumnStack.append(attrs: attrs)
}
}
override func tearDown() {
itemCoumnStack = nil
}
func testAppend() {
XCTAssertEqual(itemCoumnStack.refinedAttrs.count, 3, "")
}
func testReset() {
itemCoumnStack.reset()
XCTAssertEqual(itemCoumnStack.refinedAttrs.count, 0, "")
}
func testMaxHeight() {
XCTAssertEqual(itemCoumnStack.maxHeight, 300, "")
}
func testNormalizedAttrs() {
XCTAssertEqual(
itemCoumnStack.refinedAttrs.map { $0.size },
[
CGSize(width: 100, height: 300),
CGSize(width: 100, height: 300),
CGSize(width: 100, height: 300)
], "")
}
}
<file_sep>/README.md

[](http://cocoapods.org/pods/UICollectionViewSplitLayout)

[](http://cocoapods.org/pods/UICollectionViewSplitLayout)
[](http://cocoapods.org/pods/UICollectionViewSplitLayout)
[](https://github.com/Carthage/Carthage)
UICollectionViewSplitLayout makes collection view more responsive.

# What's this?
UICollectionViewSplitLayout is a subclass of UICollectionViewLayout. It divides sections into one or two column.
Collection view has "Section" which organizes item collection.
UICollectionViewFlowLayout places them from top to bottom.
On the other hands, UICollectionViewSplitLayout divides sections into two columns.
You can dynamically update the width of them and which column each section is on.
For example, UICollectionViewSplitLayout can changes the number of column according to device orientation. All you need is assigning value to ```leftSideRatio``` when changing screen size. This figure describes that a collection view has three sections (red, blue and green) and UICollectionViewSplitLayout layouts them side by side.

It may be hard to imagine how it works, please run [EmojiCollectionViewController](https://github.com/yahoojapan/UICollectionViewSplitLayout/blob/master/iOS%20Sample/iOS%20Sample/EmojiPhotosCollectionViewController/EmojiCollectionViewController.swift).
# Requirement
+ iOS 9.0+
+ Swift 4.2
# Installation
### Carthage
#### 1. create Cartfile
```ruby:Cartfile
github "https://github.com/yahoojapan/UICollectionViewSplitLayout"
```
#### 2. install
```
> carthage update
```
### CocoaPods
#### 1. create Podfile
```ruby:Podfile
platform :ios, '8.0'
use_frameworks!
pod "UICollectionViewSplitLayout", :git => 'https://github.com/yahoojapan/UICollectionViewSplitLayout.git'
```
#### 2. install
```
> pod install
```
# Getting Started
It’s good to start from replacing UICollectionViewFlowLayout with UICollectionViewSplitLayout.
## 1. Create UICollectionViewController
Set UICollectionViewController on Storyboard.
<img width="300" alt="2018-10-24 10 28 36" src="https://user-images.githubusercontent.com/18320004/47400738-7e9c7e80-d779-11e8-9753-52e62ced2afc.png">
Add implementation to construct a collection view.
```swift
import UIKit
private let reuseIdentifier = "Cell"
class BasicCollectionViewController: UICollectionViewController {
var dataSource: [[UIColor]] = [
(0..<20).map { _ in .red },
(0..<20).map { _ in .blue },
(0..<20).map { _ in .green }
]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource[section].count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = dataSource[indexPath.section][indexPath.row]
return cell
}
}
```
Build the code.
<img width="300" alt="2018-10-24 10 27 42" src="https://user-images.githubusercontent.com/18320004/47400781-b4d9fe00-d779-11e8-86e7-2d35ab45822c.png">
It shows three sections whose items have different colors.
## 2. Input "UICollectionViewSplitLayout" as Custom Layout Class
Switch "Flow" to "Custom" in Layout attribute and input "UICollectionViewSplitLayout" into Class and Module attributes.
<img width="316" alt="2018-10-30 11 07 59" src="https://user-images.githubusercontent.com/18320004/47691120-1e538400-dc34-11e8-821b-3b9bafb2dbfc.png">
## 3. Assign parameters to UICollectionViewSplitLayout object
Connect the layout class to source code. Assign the parameters on viewDidLoad()
```swift
@IBOutlet weak var layout: UICollectionViewSplitLayout!
override func viewDidLoad() {
super.viewDidLoad()
//...
//...
// margins for each section
layout.minimumItemLineSpacing = 8
layout.minimumInterItemSpacing = 8
layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
// Column Setting
layout.leftSideRatio = 0.4
layout.splitSpacing = 8
//...
//...
}
```
## 4. Implement the layout delegate for UICollectionViewSplitLayout
Implement UICollectionViewDelegateTwoColumnLayout. The following methods is required.
```swift
extension BasicCollectionViewController: UICollectionViewDelegateSectionSplitLayout {
// Fix the size of each item as UICollectionViewDelegateFlowLayout does. calculateFixedWidthRaughly() is utility method UICollectionViewSplitLayout has.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
let width = layout.calculateFixedWidthRaughly(
to: 3,
of: side,
minimumInterItemSpacing: layout.minimumInterItemSpacing,
sectionInset: layout.sectionInset)
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide {
// when a section number is odd, the items are placed into left side.
return section % 2 == 0 ? .left : .right
}
}
```
It arranges the sections side by side.
<img width="300" alt="2018-10-30 23 41 03" src="https://user-images.githubusercontent.com/18320004/47726194-52af5a80-dc9d-11e8-82da-72e799837f6c.png">
See [BasicCollectionViewController](https://github.com/yahoojapan/UICollectionViewSplitLayout/blob/master/iOS%20Sample/iOS%20Sample/BasicCollectionViewController/BasicCollectionViewController.swift) to run the above example.
# Architecture
It is one of the UICollectionViewLayout. So you can change a layout without updating code in UICollectionViewDelegate and UICollectionViewDataSource. It is reasonable to apply a new layout. All you have to do is studying layout class and the delegate.
# Usage
## How to Split
UICollectionViewSplitLayout calculates width of the left and right side with the following parameter.
```swift
leftSideRatio = 0.4
```
It has a Float value which is the ration of left side to the entire width.
In addition, left and right sides have spacing between them.
```swift
splitSpacing = 10
```
If a collection view has 110pt width, the above setting requires 40pt width to the left side and 60pt width to the right side.
When leftSideRatio has 0.0, splitSpacing is ignored as an exception.
You can choose which side each section is in. UICollectionViewDeleagteSectionSplitLayout provides a method to do that.
```swift
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide
```
UICollectionViewSplitLayout hooks the delegate every time a collection view calls invalidateLayout().
## Margins
UICollectionViewSplitLayout has these parameters to determine margins.
```swift
/// The minimum spacing to use between items in the same row.
open var minimumInterItemSpacing: CGFloat
/// The minimum spacing to use between lines of items in the grid.
open var minimumItemLineSpacing: CGFloat
/// The margins used to lay out content in a section
open var sectionInset: UIEdgeInsets
```
They have the corresponding delegate methods by section (optional).
```swift
// section inset to each section
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int, side: UICollectionViewSplitLayoutSide) -> UIEdgeInsets
// minimumInterItemSpacing to each section
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInterItemSpacingForSectionAtIndex section: Int, side: UICollectionViewSplitLayoutSide) -> CGFloat
// minimumItemLineSpacing to each section
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumItemLineSpacingForSectionAtIndex section: Int, side: UICollectionViewSplitLayoutSide) -> CGFloat
```
## Pinning (iOS 11~)
UICollectionViewSplitLayout pins seciton header like UICollectionViewFlowLayout. This feature is supported from iOS 11. ```sectionPinToVisibleBounds``` enables to work it.
## Setting Attriutes
UICollectionViewSplitLayout uses three kinds of attribute, item, supplementary view and decoration view.
### Item
You need to implement cell sizing. UICollectionViewSplitLayout provides a delegate to implement it.
```swift
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath,
width: CGFloat,
side: UICollectionViewSplitLayoutSide) -> CGSize
```
You can divide the sizes evenly with a utility method.
```swift
open func calculateFixedWidthRaughly(
to num: Int,
of side: UICollectionViewSplitLayoutSide,
minimumInterItemSpacing: CGFloat,
sectionInset: UIEdgeInsets) -> CGFloat
```
### Supplementary view for header and footer
You can implement header and footer sizing. UICollectionViewSplitLayout provides delegate to implement it.
If the sizes are zero, header and footer are ignoured.
```swift size
// header
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize
// footer size
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize
```
### decoration view for backgroundColor
UICollectionSplitLayout has a special decoration view. It has the same size as the section. You can determine backgroundColor to each section with the following delegate.
```swift
@objc optional func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
itemsBackgroundColorFor section: Int,
side: UICollectionViewSplitLayoutSide) -> UIColor?
```
## Line Height Normalization
If isNormalizingLineHeight is true, item height is adjusted to outline height of the line (defalut: false).
```swift
open var isNormalizingLineHeight: Bool
```
# License
The MIT License (MIT)
Copyright (c) 2018 Yahoo Japan Corporation
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.
<file_sep>/UICollectionViewSplitLayout.podspec
#
# Be sure to run `pod lib lint StringStylizer.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "UICollectionViewSplitLayout"
s.version = "1.0.0"
s.summary = "UICollectionViewSplitLayout makes collection view more responsive."
s.description = <<-DESC
UICollectionViewSplitLayout is a subclass of UICollectionViewLayout. It divides sections into one or two column.
Collection view has "Section" which organizes item collection. UICollectionViewFlowLayout layouts them from top to bottom.
On the other hands, UICollectionViewSplitLayout divides sections into two columns. You can dynamically update the width of them and which column each section is on.
DESC
s.homepage = "https://github.com/yahoojapan/UICollectionViewSplitLayout"
s.license = 'MIT'
s.author = { "<NAME>" => "<EMAIL>" }
s.source = { :git => "https://github.com/yahoojapan/UICollectionViewSplitLayout.git", :tag => s.version.to_s }
s.ios.deployment_target = '9.0'
s.source_files = "UICollectionViewSplitLayout/*.swift"
end
<file_sep>/UICollectionViewSplitLayout/UICollectionViewSplitLayout+PinnedPositionCalculator.swift
//
// UICollectionViewSplitLayout+PinnedLayoutManager.swift
// UICollectionViewSplitLayout
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import UIKit
extension UICollectionViewSplitLayout {
/// calculates floating point for supplymentaly view
/// - parameter attrs: suppulymentaly view attributes
/// - returns: floating point for supplymentaly view
class PinnedPositionCalculator {
@available(iOS 11.0, *)
func execute(
of attrs: UICollectionViewSplitLayoutAttributes,
collectionViewLayout: UICollectionViewSplitLayout) -> CGPoint? {
guard let collectionView = collectionViewLayout.collectionView else { return nil }
guard attrs.representedElementKind == UICollectionView.elementKindSectionHeader
|| attrs.representedElementKind == UICollectionView.elementKindSectionFooter else { return nil }
let section = attrs.indexPath.section
let numberOfItem = collectionView.numberOfItems(inSection: section)
let firstIndexPath = IndexPath(item: 0, section: section)
let lastIndexPath = IndexPath(item: max(0, (numberOfItem - 1)), section: section)
var origin = attrs.frame.origin
let headerHeight: CGFloat
let footerHeight: CGFloat
if numberOfItem == 0 {
let topHeaderHeight = CGFloat(0)
let firstAttrs = collectionViewLayout.layoutAttributesForSupplementaryView(
ofKind: UICollectionView.elementKindSectionHeader, at: firstIndexPath
)
headerHeight = (firstAttrs?.frame.minY ?? 0) - topHeaderHeight - attrs.sectionInset.top
let bottomHeaderHeight = attrs.frame.height
let lastAttrs = collectionViewLayout.layoutAttributesForSupplementaryView(
ofKind: UICollectionView.elementKindSectionFooter, at: lastIndexPath
)
footerHeight = (lastAttrs?.frame.maxY ?? 0) - bottomHeaderHeight + attrs.sectionInset.bottom + attrs.minimumItemLineSpacing
} else {
let topHeaderHeight = attrs.frame.height
let firstAttrs = collectionViewLayout.layoutAttributesForItem(at: firstIndexPath)
headerHeight = (firstAttrs?.frame.minY ?? 0) - topHeaderHeight - attrs.sectionInset.top
let bottomHeaderHeight = attrs.frame.height
let lastAttrs = collectionViewLayout.layoutAttributesForItem(at: lastIndexPath)
footerHeight = (lastAttrs?.frame.maxY ?? 0) + attrs.sectionInset.bottom - bottomHeaderHeight
}
let pinnedOffsetY = collectionView.safeAreaInsets.top + collectionView.contentOffset.y
origin.y = min(max(pinnedOffsetY, headerHeight), footerHeight)
return origin
}
}
}
<file_sep>/UICollectionViewSplitLayoutTests/UICollectionViewSplitLayoutTests.swift
//
// UICollectionViewSplitLayoutTests.swift
// UICollectionViewSplitLayoutTests
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import XCTest
@testable import UICollectionViewSplitLayout
class UICollectionViewSplitLayoutTests: XCTestCase {
private var vc: SpyCollectionViewController!
var layout: UICollectionViewSplitLayout!
override func setUp() {
layout = UICollectionViewSplitLayout()
vc = SpyCollectionViewController(collectionViewLayout: layout)
UIApplication.shared.keyWindow?.rootViewController = vc
}
override func tearDown() {
layout = nil
vc = nil
UIApplication.shared.keyWindow?.rootViewController = nil
}
func testInvalidateLayout() {
vc.collectionView.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
vc.dataSource = [[0, 1, 2], [0, 1, 2, 3, 4, 5], [0, 1, 2]]
layout.leftSideRatio = 1
vc.collectionView.reloadData()
let expected = [
CGPoint(x: 0, y: 0),
CGPoint(x: 100, y: 0),
CGPoint(x: 200, y: 0),
CGPoint(x: 0, y: 100),
CGPoint(x: 100, y: 100),
CGPoint(x: 200, y: 100),
CGPoint(x: 300, y: 100),
CGPoint(x: 0, y: 200),
CGPoint(x: 0, y: 300),
CGPoint(x: 100, y: 300),
CGPoint(x: 200, y: 300)
]
let actual = [
IndexPath(item: 0, section: 0),
IndexPath(item: 1, section: 0),
IndexPath(item: 2, section: 0),
IndexPath(item: 0, section: 1),
IndexPath(item: 1, section: 1),
IndexPath(item: 2, section: 1),
IndexPath(item: 3, section: 1),
IndexPath(item: 4, section: 1),
IndexPath(item: 0, section: 2),
IndexPath(item: 1, section: 2),
IndexPath(item: 2, section: 2)
].compactMap { layout.layoutAttributesForItem(at: $0)?.frame.origin }
XCTAssertEqual(actual, expected, "")
}
func testLayoutAttributesForElements() {
vc.collectionView.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
vc.dataSource = [[0, 1, 2], [0, 1, 2, 3, 4, 5], [0, 1, 2]]
layout.leftSideRatio = 1
vc.collectionView.reloadData()
let actual = layout.layoutAttributesForElements(in: CGRect(x: 0, y: 100, width: 400, height: 100))?
.compactMap { $0.indexPath }
let expected = [
IndexPath(item: 0, section: 1),
IndexPath(item: 1, section: 1),
IndexPath(item: 2, section: 1),
IndexPath(item: 3, section: 1),
IndexPath(item: 0, section: 1)
]
XCTAssertEqual(actual, expected, "")
}
func testLayoutAttributesForItem() {
vc.collectionView.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
vc.dataSource = [[0, 1, 2], [0, 1, 2, 3, 4, 5], [0, 1, 2]]
layout.leftSideRatio = 1
vc.collectionView.reloadData()
let actual = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 1))
let expected = CGRect(x: 0, y: 100, width: 100, height: 100)
XCTAssertEqual(actual?.frame, expected, "")
}
func testLayoutAttributesForDecorationView() {
vc.collectionView.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
vc.dataSource = [[0, 1, 2], [0, 1, 2, 3, 4, 5], [0, 1, 2]]
layout.leftSideRatio = 1
vc.collectionView.reloadData()
let actual = layout.layoutAttributesForDecorationView(ofKind: UICollectionViewSplitLayoutBackgroundView.className, at: IndexPath(item: 0, section: 1))?.frame
let expected = CGRect(x: 0, y: 100, width: 400, height: 200)
XCTAssertEqual(actual, expected, "")
}
func testCollectionViewContentSize() {
vc.collectionView.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
vc.dataSource = [[0, 1, 2], [0, 1, 2, 3, 4, 5], [0, 1, 2]]
layout.leftSideRatio = 1
vc.collectionView.reloadData()
let actual = layout.collectionViewContentSize
let expected = CGSize(width: 400, height: 400)
XCTAssertEqual(actual, expected, "")
}
func testOnyRecalculateWhenIsInvalidationBoundsChageTrue() {
vc.collectionView.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
vc.dataSource = [[0, 1, 2], [0, 1, 2, 3, 4, 5], [0, 1, 2]]
layout.leftSideRatio = 1
vc.collectionView.reloadData()
vc.collectionView.scrollRectToVisible(CGRect(x: 0, y: 100, width: 400, height: 300), animated: false)
XCTAssertEqual(vc.sizeCallCount, 12, "")
vc.collectionView.collectionViewLayout.invalidateLayout()
XCTAssertEqual(vc.sizeCallCount, 24, "")
}
}
private let reuseIdentifier = "Cell"
private class SpyCollectionViewController: UICollectionViewController, UICollectionViewDelegateSectionSplitLayout {
var dataSource: [[Int]] = []
var sizeCallCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource[section].count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
sizeCallCount += 1
return CGSize(width: 100, height: 100)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide {
return .left
}
}
<file_sep>/iOS Sample/iOS Sample/EmojiPhotosCollectionViewController/EmojiCollectionViewController.swift
//
// SplitCollectionViewController.swift
// iOS Sample
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import UIKit
import UICollectionViewSplitLayout
private let reuseIdentifier = "Cell"
struct Emoji {
struct CodePoint {
let label: String
let value: String
}
let mainCharacter: String
let name: String
let codePoint: [CodePoint]
let others: [String]
}
enum EmojiDataSource {
case summary(mianCharacter: String, name: String)
case classification(classification: Emoji.CodePoint)
case sampleImage(imageName: String)
}
struct EmojiDataSourceFactory {
static func make(emoji: Emoji) -> [(sectionTitle: String?, items: [EmojiDataSource], side: UICollectionViewSplitLayoutSide, hasFooter: Bool)] {
return [
(sectionTitle: nil, items: [.summary(mianCharacter: emoji.mainCharacter, name: emoji.name)], side: .left, hasFooter: false),
(sectionTitle: nil, items: emoji.codePoint.map { .classification(classification: $0) }, side: .left, hasFooter: true),
(sectionTitle: "Emoji Collection", items: emoji.others.map { .sampleImage(imageName: $0) }, side: .right, hasFooter: false)
]
}
}
class EmojiCollectionViewController: UICollectionViewController {
static let summaryCollectionViewCellSizing = UINib(nibName: "SummaryCollectionViewCell", bundle: nil).instantiate(withOwner: self, options: nil).first as! SummaryCollectionViewCell
static let codePointCollectionViewCellSizing = UINib(nibName: "CodePointCollectionViewCell", bundle: nil).instantiate(withOwner: self, options: nil).first as! CodePointCollectionViewCell
private let emoji = Emoji(
mainCharacter: "👨👩👧👦",
name: "Family: Man, Woman, Girl, Boy",
codePoint: [
.init(label: "👨", value: "U+1F468"),
.init(label: "", value: "U+200D"),
.init(label: "👩", value: "U+1F469"),
.init(label: "", value: "U+200D"),
.init(label: "👧", value: "U+1F467"),
.init(label: "", value: "U+200D"),
.init(label: "👦", value: "U+1F466")
],
others: ["👨🏻⚕️", "👩🎓", "👨🏫", "👩🌾", "👨🍳", "👩🔧", "👨🏭", "👩💼", "👨🔬", "👩💻", "👨🎤", "👩🎨", "👨✈️", "👩🚀", "👨🚒", "👮♀️", "🕵️♂️", "👷♀️"]
)
let layout = UICollectionViewSplitLayout()
private var dataSource = [(sectionTitle: String?, items: [EmojiDataSource], side: UICollectionViewSplitLayoutSide, hasFooter: Bool)]()
override func viewDidLoad() {
super.viewDidLoad()
layout.splitSpacing = 16
if #available(iOS 11.0, *) {
layout.sectionPinToVisibleBounds = true
}
collectionView.collectionViewLayout = layout
collectionView.contentInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
collectionView.register(UINib(nibName: "SimpleCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SimpleCollectionReusableView")
collectionView.register(UINib(nibName: "SimpleCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SimpleCollectionReusableView")
collectionView.register(UINib(nibName: "CodePointCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CodePointCollectionViewCell")
collectionView.register(UINib(nibName: "OtherEmojiCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "OtherEmojiCollectionViewCell")
collectionView.register(UINib(nibName: "SummaryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "SummaryCollectionViewCell")
dataSource = EmojiDataSourceFactory.make(emoji: emoji)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource[section].items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch dataSource[indexPath.section].items[indexPath.item] {
case .summary(let character, let name):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SummaryCollectionViewCell", for: indexPath) as! SummaryCollectionViewCell
cell.nameLabel.text = name
cell.emojiLabel.text = character
return cell
case .classification(let classification):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CodePointCollectionViewCell", for: indexPath) as! CodePointCollectionViewCell
cell.categoryLabel.text = classification.label
cell.nameLabel.text = classification.value
return cell
case .sampleImage(let character):
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "OtherEmojiCollectionViewCell", for: indexPath) as! OtherEmojiCollectionViewCell
cell.emojiLabel.text = character
return cell
}
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SimpleCollectionReusableView", for: indexPath) as! SimpleCollectionReusableView
view.titleLabel.text = dataSource[indexPath.section].sectionTitle
return view
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
layout.leftSideRatio = size.width > size.height ? 0.4 : UICollectionViewSplitLayoutSide.left.leftSideRatio
coordinator.animate(alongsideTransition: { [weak self] (context) in
self?.layout.invalidateLayout()
}) { (context) in }
}
}
extension EmojiCollectionViewController: UICollectionViewDelegateSectionSplitLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
switch dataSource[indexPath.section].items[indexPath.item] {
case .summary(_, let name):
EmojiCollectionViewController.summaryCollectionViewCellSizing.nameLabel.text = name
var size = UIView.layoutFittingCompressedSize
size.width = layout.contentWidth(of: side)
return EmojiCollectionViewController.summaryCollectionViewCellSizing.contentView.systemLayoutSizeFitting(size, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow)
case .classification(let classification):
EmojiCollectionViewController.codePointCollectionViewCellSizing.categoryLabel.text = classification.label
EmojiCollectionViewController.codePointCollectionViewCellSizing.nameLabel.text = classification.value
var size = UIView.layoutFittingCompressedSize
size.width = layout.contentWidth(of: side)
return EmojiCollectionViewController.codePointCollectionViewCellSizing.contentView.systemLayoutSizeFitting(size, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow)
case .sampleImage(_):
let num = layout.leftSideRatio == UICollectionViewSplitLayoutSide.left.leftSideRatio ? 2 : 3
let width = layout.calculateFixedWidthRaughly(to: num, of: side, minimumInterItemSpacing: layout.minimumInterItemSpacing, sectionInset: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8))
return CGSize(width: width, height: width)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide {
if let side = UICollectionViewSplitLayoutSide(leftSideRatio: layout.leftSideRatio) {
return side
} else {
return dataSource[section].side
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
return dataSource[section].sectionTitle != nil ? CGSize(width: layout.contentWidth(of: side), height: 60) : .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, itemsBackgroundColorFor section: Int, side: UICollectionViewSplitLayoutSide) -> UIColor? {
return .white
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int, side: UICollectionViewSplitLayoutSide) -> UIEdgeInsets {
switch dataSource[section].items.first {
case .sampleImage?:
return UIEdgeInsets(top: 0, left: 8, bottom: 16, right: 8)
case .classification?:
return UIEdgeInsets(top: 0, left: 0, bottom: 16, right: 0)
default:
return .zero
}
}
}
<file_sep>/UICollectionViewSplitLayout/UICollectionViewSplitLayout+LayoutAttributesInSectionFactory.swift
//
// UICollectionViewSplitLayout+LayoutAttributesInSectionFactory.swift
// UICollectionViewSplitLayout
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import UIKit
extension UICollectionViewSplitLayout {
class LayoutAttributesInSectionFactory {
/// stack to calculate frames on one column
class ItemColumnStack {
let isNormalizing: Bool
init(isNormalizing: Bool) {
self.isNormalizing = isNormalizing
}
/// If isNormalizing is set true, refinedAttrs returns normalized height.
var refinedAttrs: [UICollectionViewSplitLayoutAttributes] {
if isNormalizing {
return normalizedAttrs
} else {
return attributesList
}
}
/// layout attributes on one column
private var attributesList = [UICollectionViewSplitLayoutAttributes]()
/// max height on one column
var maxHeight: CGFloat {
return attributesList.map{ $0.frame.height }.reduce(CGFloat(0)) { max($0, $1) }
}
/// outline size
private var normalizedAttrs: [UICollectionViewSplitLayoutAttributes] {
attributesList.forEach { $0.frame.size = CGSize(width: $0.frame.width, height: maxHeight) }
return attributesList
}
/// reset all layout attributes
func reset() {
attributesList = []
}
/// add layout attributes
func append(attrs: UICollectionViewSplitLayoutAttributes) {
attributesList.append(attrs)
}
}
func makeItems(for section: Int,
side: UICollectionViewSplitLayoutSide,
numberOfItems: Int,
firstPosition: CGPoint,
contentMostLeft: CGFloat,
contentWidth: CGFloat,
sectionInset: UIEdgeInsets,
minimumInterItemSpacing: CGFloat,
minimumItemLineSpacing: CGFloat,
isNormalizing: Bool,
sizingHandler: (IndexPath) -> CGSize) -> (attributes: [UICollectionViewSplitLayoutAttributes], lastPosition: CGPoint) {
let columnStack = ItemColumnStack(isNormalizing: isNormalizing)
var itemAttributes = [UICollectionViewSplitLayoutAttributes]()
var currentPosition = firstPosition
currentPosition.y += sectionInset.top
currentPosition.x += sectionInset.left
for item in 0..<numberOfItems {
let indexPath = IndexPath(item: item, section: section)
let size = sizingHandler(indexPath)
if size.width == 0.0 || size.height == 0.0 {
continue
}
let needsLineBreak = isOverMostRightPosition(
of: side,
toPosition: currentPosition.x + size.width,
sectionInset: sectionInset,
contentMostLeft: contentMostLeft,
contentWidth: contentWidth
)
if needsLineBreak {
itemAttributes += columnStack.refinedAttrs
currentPosition = CGPoint(
x: contentMostLeft + sectionInset.left,
y: columnStack.maxHeight + currentPosition.y + minimumItemLineSpacing
)
columnStack.reset()
}
let attr = UICollectionViewSplitLayoutAttributes(forCellWith: indexPath)
attr.side = side
attr.sectionInset = sectionInset
attr.minimumItemLineSpacing = minimumItemLineSpacing
attr.frame.origin = currentPosition
attr.frame.size = size
columnStack.append(attrs: attr)
currentPosition = CGPoint(
x: attr.frame.maxX + minimumInterItemSpacing,
y: attr.frame.minY
)
}
itemAttributes += columnStack.refinedAttrs
currentPosition = CGPoint(
x: contentMostLeft,
y: columnStack.maxHeight + currentPosition.y + sectionInset.bottom)
columnStack.reset()
return (itemAttributes, currentPosition)
}
/// position x is over right edge on the column
/// - parameter side: UICollectionViewSplitLayoutSide
/// - parameter x: position
/// - returns: position x is over the right edge
func isOverMostRightPosition(
of side: UICollectionViewSplitLayoutSide,
toPosition x: CGFloat,
sectionInset: UIEdgeInsets,
contentMostLeft: CGFloat,
contentWidth: CGFloat) -> Bool {
let contentMostRight = (contentMostLeft + contentWidth)
let sectionMostRight = contentMostRight - sectionInset.right
return sectionMostRight < x
}
/// return layout attributes for each section header
/// - parameter section: Int
/// - parameter nextPosition: CGPoint
/// - parameter side: UICollectionViewSplitLayoutSide
/// - returns: layout attributes for each section header
func makeHeader(
at section: Int,
nextPosition: CGPoint,
side: UICollectionViewSplitLayoutSide,
sectionInset: UIEdgeInsets,
minimumItemLineSpacing: CGFloat,
headerSize: CGSize) -> UICollectionViewSplitLayoutAttributes? {
if headerSize.width == 0.0 || headerSize.height == 0.0 {
return nil
}
let headerAttributes = UICollectionViewSplitLayoutAttributes(
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
with: IndexPath(item: 0, section: section)
)
headerAttributes.side = side
headerAttributes.sectionInset = sectionInset
headerAttributes.minimumItemLineSpacing = minimumItemLineSpacing
headerAttributes.frame.origin = nextPosition
headerAttributes.frame.size = headerSize
return headerAttributes
}
/// return layout attributes for each section footer
/// - parameter section: Int
/// - parameter nextPosition: CGPoint
/// - parameter side: UICollectionViewSplitLayoutSide
/// - returns: layout attributes for each section footer
func makeFooter(
at section: Int,
nextPosition: CGPoint,
side: UICollectionViewSplitLayoutSide,
sectionInset: UIEdgeInsets,
minimumItemLineSpacing: CGFloat,
footerSize: CGSize) -> UICollectionViewSplitLayoutAttributes? {
if footerSize.width == 0.0 || footerSize.height == 0.0 {
return nil
}
let footerAttributes = UICollectionViewSplitLayoutAttributes(
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
with: IndexPath(item: 0, section: section)
)
footerAttributes.side = side
footerAttributes.sectionInset = sectionInset
footerAttributes.minimumItemLineSpacing = minimumItemLineSpacing
footerAttributes.frame.origin = nextPosition
footerAttributes.frame.size = footerSize
return footerAttributes
}
func makeBackgroundDecoration(
section: Int,
itemsLeftTopPosition: CGPoint,
sectionBottomPositionY: CGFloat,
side: UICollectionViewSplitLayoutSide,
contentWidth: CGFloat,
backgroundColor: UIColor?) -> UICollectionViewSplitLayoutAttributes {
let decorationAttrs = UICollectionViewSplitLayoutAttributes(
forDecorationViewOfKind: UICollectionViewSplitLayoutBackgroundView.className,
with: IndexPath(item: 0, section: section)
)
decorationAttrs.frame.origin = itemsLeftTopPosition
decorationAttrs.frame.size = CGSize(
width: contentWidth,
height: sectionBottomPositionY - decorationAttrs.frame.minY
)
decorationAttrs.side = side
decorationAttrs.zIndex = -1
decorationAttrs.decoratedSectionBackgroundColor = backgroundColor
return decorationAttrs
}
}
}
<file_sep>/UICollectionViewSplitLayout/UICollectionViewSplitLayout.swift
//
// UICollectionViewSplitLayout.swift
// UICollectionViewSplitLayout
//
// Copyright (c) 2018 Yahoo Japan Corporation.
//
// 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.
import UIKit
/// This class defines which side each section is on
@objc public enum UICollectionViewSplitLayoutSide: Int {
case left = 1, right = 0
public init?(leftSideRatio: CGFloat) {
if leftSideRatio == 1 {
self = .left
} else if leftSideRatio == 0 {
self = .right
} else {
return nil
}
}
public var leftSideRatio: CGFloat {
return CGFloat(rawValue)
}
public func needsIgnored(to leftSideRatio: CGFloat) -> Bool {
return ignoredLeftSideRatio == leftSideRatio
}
private var ignoredLeftSideRatio: CGFloat {
switch self {
case .left:
return UICollectionViewSplitLayoutSide.right.leftSideRatio
case .right:
return UICollectionViewSplitLayoutSide.left.leftSideRatio
}
}
}
/// Custom invalidation context for UICollectionViewSplitLayout.
open class UICollectionViewSplitLayoutInvalidationContext: UICollectionViewLayoutInvalidationContext {
public var isInvalidationBoundsChage = false
}
/// Custom layout attributes for UICollectionViewSplitLayout.
open class UICollectionViewSplitLayoutAttributes: UICollectionViewLayoutAttributes {
public var side: UICollectionViewSplitLayoutSide!
public var sectionInset: UIEdgeInsets = .zero
public var minimumItemLineSpacing: CGFloat = 0
public var decoratedSectionBackgroundColor: UIColor?
}
/// delegate class for UICollectionViewSplitLayout.
@objc public protocol UICollectionViewDelegateSectionSplitLayout: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int, side: UICollectionViewSplitLayoutSide) -> UIEdgeInsets
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInterItemSpacingForSectionAtIndex section: Int, side: UICollectionViewSplitLayoutSide) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumItemLineSpacingForSectionAtIndex section: Int, side: UICollectionViewSplitLayoutSide) -> CGFloat
@objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, itemsBackgroundColorFor section: Int, side: UICollectionViewSplitLayoutSide) -> UIColor?
}
/// layout class to divide sections into left and right
open class UICollectionViewSplitLayout: UICollectionViewLayout {
public enum SectionInsetReference: Int {
case fromContentInset
case fromSafeArea
}
/// The minimum spacing to use between items in the same row.
open var minimumInterItemSpacing: CGFloat = 0
/// The minimum spacing to use between lines of items in the grid.
open var minimumItemLineSpacing: CGFloat = 0
/// The margins used to lay out content in a section
open var sectionInset: UIEdgeInsets = .zero
/// contentInset of collection view
private var contentInset: UIEdgeInsets {
get {
return collectionView?.contentInset ?? .zero
}
set {
collectionView?.contentInset = newValue
}
}
private var pinnedPositionCalculator = PinnedPositionCalculator()
private var layoutAttributesInSectionFactory = LayoutAttributesInSectionFactory()
func configure(
pinnedPositionCalculator: PinnedPositionCalculator,
layoutAttributesInSectionFactory: LayoutAttributesInSectionFactory) {
self.pinnedPositionCalculator = pinnedPositionCalculator
self.layoutAttributesInSectionFactory = layoutAttributesInSectionFactory
}
private var _sectionInsetReference: SectionInsetReference = .fromSafeArea
@available(iOS 11.0, *)
public var sectionInsetReference: SectionInsetReference {
get {
return _sectionInsetReference
}
set {
_sectionInsetReference = newValue
}
}
/// A Boolean value indicating whether pin to the top of the collection view bounds during scrolling.
private var _sectionPinToVisibleBounds: Bool = false
@available(iOS 11.0, *)
public var sectionPinToVisibleBounds: Bool {
get {
return _sectionPinToVisibleBounds
}
set {
_sectionPinToVisibleBounds = newValue
}
}
/// left:right -> leftSideRatio : (1 - leftSideRatio)
open var leftSideRatio: CGFloat = 1
/// The margin between left and right sides
/// If leftSideRaio is 1 or 0, the value of this property is ignored.
open var splitSpacing: CGFloat = 0
/// If true, item height is adjusted to outline height of the line (defalut: false).
open var isNormalizingLineHeight: Bool = false
private var actualSideSpacing: CGFloat {
return (leftSideRatio == 1 || leftSideRatio == 0) ? 0 : splitSpacing
}
// MARK:- layout cache
private var sectionAttributes = [[UICollectionViewSplitLayoutAttributes]]()
private var sectionSupplymentalyAttributes = [[UICollectionViewSplitLayoutAttributes]]()
private var sectionDecorationAttributes = [UICollectionViewSplitLayoutAttributes]()
private var tailPositionY = CGFloat(0)
// MARK:- calculation for frame
/// divides content width equally to calculate item width.
///
/// - Parameters:
/// - num: number of item on line
/// - side: which side
/// - minimumInterItemSpacing: The minimum spacing to use between items in the same row
/// - sectionInset: The minimum spacing to use between lines of items in the grid
/// - Returns: item width
open func calculateFixedWidthRaughly(
to num: Int,
of side: UICollectionViewSplitLayoutSide,
minimumInterItemSpacing: CGFloat,
sectionInset: UIEdgeInsets) -> CGFloat {
guard 0 < num else { return 0 }
let horizontalSpacing = sectionInset.horizontal + (minimumInterItemSpacing * (CGFloat(num) - 1))
let validWidth = contentWidth(of: side) - horizontalSpacing
return CGFloat(Int(validWidth) / num)
}
/// return left edge of the side
/// - parameter side: UICollectionViewSplitLayoutSide
/// - returns: left edge of the side
open func contentMostLeft(of side: UICollectionViewSplitLayoutSide) -> CGFloat {
switch side {
case .left:
return contentInsetStartingInsets.left
case .right:
return contentInsetStartingInsets.left + contentWidth(of: .left) + actualSideSpacing
}
}
open func contentWidth(of side: UICollectionViewSplitLayoutSide) -> CGFloat {
let totalContentWidth = (collectionViewContentSize.width - actualSideSpacing)
switch side {
case .left:
return totalContentWidth * leftSideRatio
case .right:
return totalContentWidth - (totalContentWidth * leftSideRatio)
}
}
public override init() {
super.init()
register(
UICollectionViewSplitLayoutBackgroundView.self,
forDecorationViewOfKind: UICollectionViewSplitLayoutBackgroundView.className
)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
register(
UICollectionViewSplitLayoutBackgroundView.self,
forDecorationViewOfKind: UICollectionViewSplitLayoutBackgroundView.className
)
}
//MARK:- UICollectionViewLayout
override open class var invalidationContextClass: AnyClass {
return UICollectionViewSplitLayoutInvalidationContext.self
}
override open class var layoutAttributesClass: AnyClass {
return UICollectionViewLayoutAttributes.self
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let leftSideAttributes = sectionAttributes.joined().filter({ $0.side == .left })
let rightSideAttributes = sectionAttributes.joined().filter({ $0.side == .right })
let leftSectionInRectAttributes = leftSideAttributes.filter { rect.intersects($0.frame) }
let rightSectionInRectAttributes = rightSideAttributes.filter { rect.intersects($0.frame) }
let layoutAttributes = leftSectionInRectAttributes + rightSectionInRectAttributes
let supplymentalyAttributesInRect = sectionSupplymentalyAttributes.joined().filter { (supplementary) in
layoutAttributes.filter({ $0.indexPath.section == supplementary.indexPath.section }).count > 0
}
let sectionList = Set(layoutAttributes.map { $0.indexPath.section })
let backgroundViewDecorationAttributesInRect = sectionList.compactMap {
layoutAttributesForDecorationView(
ofKind: UICollectionViewSplitLayoutBackgroundView.className,
at: IndexPath(item: 0, section: $0)
)
}
if #available(iOS 11.0, *), sectionPinToVisibleBounds {
for attrs in supplymentalyAttributesInRect where attrs.representedElementKind == UICollectionView.elementKindSectionHeader {
if let origin = pinnedPositionCalculator.execute(of: attrs, collectionViewLayout: self) {
attrs.zIndex = 1024
attrs.frame.origin = origin
}
}
}
return supplymentalyAttributesInRect + layoutAttributes + backgroundViewDecorationAttributesInRect
}
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return sectionAttributes[indexPath.section][indexPath.item]
}
open override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return sectionDecorationAttributes.first(where: { $0.representedElementKind == elementKind && $0.indexPath.section == indexPath.section })
}
override open var collectionViewContentSize: CGSize {
guard let collectionView = collectionView else {
return CGSize.zero
}
let size = CGSize(
width: collectionView.bounds.width - contentInset.horizontal - contentInsetStartingInsets.horizontal,
height: tailPositionY + contentInset.bottom
)
return size
}
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
open override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds)
if let _context = context as? UICollectionViewSplitLayoutInvalidationContext {
_context.isInvalidationBoundsChage = true
}
return context
}
open override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) {
super.invalidateLayout(with: context)
if let _context = context as? UICollectionViewSplitLayoutInvalidationContext,
!_context.isInvalidationBoundsChage {
recalculateLayoutAttributes()
}
}
//MARK:- private
/// makes layout attributes
/// - parameter side: UICollectionViewSplitLayoutSide
/// - parameter section: Int
/// - parameter currentPosition: CGPoint
/// - returns: ([UICollectionViewSplitLayoutAttributes], [UICollectionViewSplitLayoutAttributes], CGPoint)
private func makeLayoutAttributesInSection(
of side: UICollectionViewSplitLayoutSide,
section: Int,
currentPosition: CGPoint,
minimumItemLineSpacing: CGFloat,
minimumInterItemSpacing: CGFloat,
contentMostLeft: CGFloat,
contentWidth: CGFloat,
collectionView: UICollectionView?) -> (attrsList: [UICollectionViewSplitLayoutAttributes], supplementalyAttrsList: [UICollectionViewSplitLayoutAttributes], decorationAttrsList: UICollectionViewSplitLayoutAttributes, currentPosition: CGPoint)? {
guard let collectionView = collectionView, let delegate = collectionView.delegate as? UICollectionViewDelegateSectionSplitLayout else { return nil }
var currentPosition = currentPosition
var supplementalyAttributes = [UICollectionViewSplitLayoutAttributes]()
let sectionInset = delegate.collectionView?(
collectionView,
layout: self,
insetForSectionAtIndex:
section,
side: side) ?? self.sectionInset
let headerSize = delegate.collectionView?(
collectionView,
layout: self,
referenceSizeForHeaderInSection: section,
width: contentWidth,
side: side) ?? .zero
let headerAttributes = layoutAttributesInSectionFactory.makeHeader(
at: section,
nextPosition: currentPosition,
side: side,
sectionInset: sectionInset,
minimumItemLineSpacing: minimumItemLineSpacing,
headerSize: headerSize
)
if let headerAttributes = headerAttributes {
supplementalyAttributes.append(headerAttributes)
currentPosition = CGPoint(
x: contentMostLeft,
y: headerAttributes.frame.maxY
)
}
let itemsLeftTopPosition = currentPosition
let (attrsList, lastPosition) = layoutAttributesInSectionFactory.makeItems(
for: section,
side: side,
numberOfItems: collectionView.numberOfItems(inSection: section),
firstPosition: currentPosition,
contentMostLeft: contentMostLeft,
contentWidth: contentWidth,
sectionInset: sectionInset,
minimumInterItemSpacing: minimumInterItemSpacing,
minimumItemLineSpacing: minimumItemLineSpacing,
isNormalizing: isNormalizingLineHeight,
sizingHandler: { indexPath in
return delegate.collectionView(
collectionView,
layout: self,
sizeForItemAtIndexPath: indexPath,
width: contentWidth,
side: side
)
})
currentPosition = lastPosition
let decorationBackgroundColor = delegate.collectionView?(
collectionView,
layout: self,
itemsBackgroundColorFor: section,
side: side
)
let decorationAttrs = layoutAttributesInSectionFactory.makeBackgroundDecoration(
section: section,
itemsLeftTopPosition: itemsLeftTopPosition,
sectionBottomPositionY: currentPosition.y,
side: side,
contentWidth: contentWidth,
backgroundColor: decorationBackgroundColor
)
let footerSize = delegate.collectionView?(
collectionView,
layout: self,
referenceSizeForFooterInSection: section,
width: contentWidth,
side: side) ?? .zero
let footerAttributes = layoutAttributesInSectionFactory.makeFooter(
at: section,
nextPosition: currentPosition,
side: side,
sectionInset: sectionInset,
minimumItemLineSpacing: minimumItemLineSpacing,
footerSize: footerSize
)
if let footerAttributes = footerAttributes {
supplementalyAttributes.append(footerAttributes)
currentPosition = CGPoint(
x: contentMostLeft,
y: footerAttributes.frame.maxY
)
}
return (
attrsList: attrsList,
supplementalyAttrsList: supplementalyAttributes,
decorationAttrsList: decorationAttrs,
currentPosition: currentPosition
)
}
/// starting point of content ineset
var contentInsetStartingInsets: UIEdgeInsets {
guard #available(iOS 11.0, *) else {
return .zero
}
switch sectionInsetReference {
case .fromContentInset:
return .zero
case .fromSafeArea:
return collectionView?.safeAreaInsets ?? .zero
}
}
/// initializes and calculates layout attributes for each elements
private func recalculateLayoutAttributes() {
guard let collectionView = collectionView, let delegate = collectionView.delegate as? UICollectionViewDelegateSectionSplitLayout else { return }
sectionAttributes = []
sectionSupplymentalyAttributes = []
sectionDecorationAttributes = []
tailPositionY = 0
let contentMostLeftOnLeftSide = contentMostLeft(of: .left)
let contentMostLeftOnRightSide = contentMostLeft(of: .right)
var leftSideIncrementedPosition = CGPoint(x: contentMostLeftOnLeftSide, y: 0)
var rightSideIncrementedPosition = CGPoint(x: contentMostLeftOnRightSide, y: 0)
for section in 0..<collectionView.numberOfSections {
let side = delegate.collectionView(collectionView, layout: self, sideForSection: section)
if side.needsIgnored(to: leftSideRatio) {
continue
}
let _minimumItemLineSpacing = delegate.collectionView?(
collectionView,
layout: self,
minimumItemLineSpacingForSectionAtIndex: section, side: side) ?? minimumItemLineSpacing
let _minimumInterItemSpacing = delegate.collectionView?(
collectionView,
layout: self,
minimumInterItemSpacingForSectionAtIndex: section, side: side) ?? minimumInterItemSpacing
switch side {
case .left:
let _attributes = makeLayoutAttributesInSection(
of: .left,
section: section,
currentPosition: leftSideIncrementedPosition,
minimumItemLineSpacing: _minimumItemLineSpacing,
minimumInterItemSpacing: _minimumInterItemSpacing,
contentMostLeft: contentMostLeftOnLeftSide,
contentWidth: contentWidth(of: .left),
collectionView: collectionView
)
if let (attrList, supplementaryList, decorationAttributes, currentPosition) = _attributes {
let maxY = max(supplementaryList.last?.frame.maxY ?? 0, currentPosition.y)
tailPositionY = max(tailPositionY, maxY)
leftSideIncrementedPosition = currentPosition
sectionAttributes.append(attrList)
sectionSupplymentalyAttributes.append(supplementaryList)
sectionDecorationAttributes.append(decorationAttributes)
}
case .right:
let _attributes = makeLayoutAttributesInSection(
of: .right,
section: section,
currentPosition: rightSideIncrementedPosition,
minimumItemLineSpacing: _minimumItemLineSpacing,
minimumInterItemSpacing: _minimumInterItemSpacing,
contentMostLeft: contentMostLeftOnRightSide,
contentWidth: contentWidth(of: .right),
collectionView: collectionView
)
if let (attrList, supplementaryList, decorationAttributes, currentPosition) = _attributes {
let maxY = max(supplementaryList.last?.frame.maxY ?? 0, currentPosition.y)
tailPositionY = max(tailPositionY, maxY)
rightSideIncrementedPosition = currentPosition
sectionAttributes.append(attrList)
sectionSupplymentalyAttributes.append(supplementaryList)
sectionDecorationAttributes.append(decorationAttributes)
}
}
}
}
}
// MARK:- background view for each seciton
class UICollectionViewSplitLayoutBackgroundView: UICollectionReusableView {
open override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
if let _layoutAttribute = layoutAttributes as? UICollectionViewSplitLayoutAttributes {
backgroundColor = _layoutAttribute.decoratedSectionBackgroundColor
}
}
}
// MARK:- Utility Extension
private extension UIEdgeInsets {
var horizontal: CGFloat {
return left + right
}
var vertical: CGFloat {
return top + bottom
}
}
extension NSObject {
static var className: String {
return String(describing: self)
}
}
<file_sep>/iOS Sample/iOS Sample/SectionDividedCollectionViewController/SectionDividedCollectionViewController.swift
//
// SectionDividedCollectionViewController.swift
// iOS Sample
//
// Created by kahayash on 2018/10/06.
// Copyright © 2018 Yahoo Japan Corporation. All rights reserved.
//
import UIKit
import UICollectionViewSplitLayout
class SectionDividedCollectionViewController: UICollectionViewController, UICollectionViewDelegateSectionSplitLayout {
let layout = UICollectionViewSplitLayout()
private let dataSource: [(headerColor: UIColor, footerColor: UIColor, elements: [(color: UIColor, size: CGSize)], decorationColor: UIColor)] = {
let colors = (0..<10).map({ _ in UIColor.gray })
let randomSizeHandler: () -> CGSize = { return CGSize(width: CGFloat.random(in: 50..<100), height: CGFloat.random(in: 50..<150)) }
return [
(headerColor: .red, footerColor: .blue, elements: (0..<10).map({ _ in (color: UIColor.lightGray, size: randomSizeHandler()) }), decorationColor: .green),
(headerColor: .red, footerColor: .blue, elements: (0..<20).map({ _ in (color: UIColor.lightGray, size: randomSizeHandler()) }), decorationColor: .green),
(headerColor: .red, footerColor: .blue, elements: (0..<30).map({ _ in (color: UIColor.lightGray, size: randomSizeHandler()) }), decorationColor: .green),
(headerColor: .red, footerColor: .blue, elements: (0..<40).map({ _ in (color: UIColor.lightGray, size: randomSizeHandler()) }), decorationColor: .green),
(headerColor: .red, footerColor: .blue, elements: (0..<50).map({ _ in (color: UIColor.lightGray, size: randomSizeHandler()) }), decorationColor: .green),
(headerColor: .red, footerColor: .blue, elements: (0..<60).map({ _ in (color: UIColor.lightGray, size: randomSizeHandler()) }), decorationColor: .green),
(headerColor: .red, footerColor: .blue, elements: (0..<70).map({ _ in (color: UIColor.lightGray, size: randomSizeHandler()) }), decorationColor: .green)
]
}()
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
collectionView.collectionViewLayout = layout
layout.minimumInterItemSpacing = 8
layout.minimumItemLineSpacing = 8
layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
layout.leftSideRatio = view.frame.width < view.frame.height ? 1 : 0.4
layout.splitSpacing = 8
if #available(iOS 11.0, *) {
layout.sectionPinToVisibleBounds = true
}
collectionView.register(UINib(nibName: "SectionDividedCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "SectionDividedCollectionViewCell")
collectionView.register(UINib(nibName: "SectionDividedSupplymentaryView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SectionDividedSupplymentaryView")
collectionView.register(UINib(nibName: "SectionDividedSupplymentaryView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionDividedSupplymentaryView")
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
layout.leftSideRatio = size.width < size.height ? 1 : 0.4
coordinator.animate(alongsideTransition: { [weak self] (_) in
self?.collectionView.collectionViewLayout.invalidateLayout()
}, completion: nil)
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return dataSource.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return dataSource[section].elements.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SectionDividedCollectionViewCell", for: indexPath) as! SectionDividedCollectionViewCell
cell.backgroundColor = dataSource[indexPath.section].elements[indexPath.item].color
cell.titleLabel.text = "section \(indexPath.section): item \(indexPath.item)"
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionDividedSupplymentaryView", for: indexPath) as! SectionDividedSupplymentaryView
view.backgroundColor = kind == UICollectionView.elementKindSectionHeader ? dataSource[indexPath.section].headerColor : dataSource[indexPath.section].footerColor
view.titleLabel.text = "section \(indexPath.section) \(kind == UICollectionView.elementKindSectionHeader ? "header" : "footer")"
return view
}
// MARK: UICollectionViewDelegateSectionSplitLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sideForSection section: Int) -> UICollectionViewSplitLayoutSide {
if let side = UICollectionViewSplitLayoutSide(leftSideRatio: layout.leftSideRatio) {
return side
}
switch section {
case 0, 2, 3, 5:
return .left
default:
return .right
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
switch indexPath.section {
case 0, 2, 4, 6:
return dataSource[indexPath.section].elements[indexPath.row].size
case 1, 5:
return CGSize(width: layout.calculateFixedWidthRaughly(to: 2, of: side, minimumInterItemSpacing: layout.minimumInterItemSpacing, sectionInset: layout.sectionInset), height: 100)
default:
return CGSize(width: layout.calculateFixedWidthRaughly(to: 1, of: side, minimumInterItemSpacing: layout.minimumInterItemSpacing, sectionInset: layout.sectionInset), height: 44)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
return CGSize(width: layout.contentWidth(of: side), height: 44)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int, width: CGFloat, side: UICollectionViewSplitLayoutSide) -> CGSize {
return CGSize(width: layout.contentWidth(of: side), height: 44)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, itemsBackgroundColorFor section: Int, side: UICollectionViewSplitLayoutSide) -> UIColor? {
return dataSource[section].decorationColor
}
}
| 94d1c6a5024223ca81f3608646a31d5130c61e44 | [
"Swift",
"Ruby",
"Markdown"
] | 13 | Swift | mohsinalimat/UICollectionViewSplitLayout | c2c791a26271494ef1326bb07a3dbb04b294cb1d | 842f84b53b5eee26863c993ccf36b89e85f758d1 |
refs/heads/master | <repo_name>jeanfabre/Exitgames--Custom--Samples_U4<file_sep>/Assets/PUN Custom Samples/PunAndChatDemo/Scripts/PlayerPunChat.cs
using UnityEngine;
using System.Collections;
using ExitGames.Client.Photon;
using ExitGames.Client.Photon.Chat;
public class PlayerPunChat : Photon.PunBehaviour, IPunChatChannel {
public GameObject UiPrefab;
PlayerPunChatUI instance;
public string UserId;
public string channelId;
// Use this for initialization
void Start () {
GameObject go = Instantiate(UiPrefab) as GameObject;
instance = go.GetComponent<PlayerPunChatUI>();
instance.SetTarget(this);
UserId = this.photonView.owner.UserId;
channelId = PhotonNetwork.room.Name;
PunChatClientBroker.Register((IPunChatChannel)this);
}
#region IPunChatChannel implementation
void IPunChatChannel.OnSubscribed (bool result){}
void IPunChatChannel.OnUnsubscribed (){}
void IPunChatChannel.OnGetMessages (string[] senders, object[] messages)
{
Debug.Log("Player <"+UserId+"> getting messages from "+senders.ToStringFull());
if (senders[senders.Length-1] == UserId)
{
instance.SetMessage(
(string)messages[messages.Length-1])
;
}
}
string IPunChatChannel.Channel {
get {
return channelId;
}
set {
channelId = value;
}
}
#endregion
}
<file_sep>/Assets/PUN Custom Samples/PunAndChatDemo/Scripts/MenuManager.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MenuManager : MonoBehaviour {
public GameObject PlayerPrefab;
public PunAndChatConnection Connector;
public GameObject background;
public GameObject UserIdForm;
public InputField UserIdInputField;
public GameObject ConnectingPanel;
public GameObject MainChatPanel;
public InputField ChatMessage;
public bool debug;
public void Connect(string userId) {
if (debug) Debug.Log("MenuManager : Connect");
background.SetActive(true);
UserIdForm.SetActive(false);
ConnectingPanel.SetActive(true);
MainChatPanel.SetActive(false);
Connector.UserId = userId;
Connector.NickName = userId;
Connector.Connect();
}
public void SendChatMessage()
{
if (debug) Debug.Log("MenuManager: SendChatMessage "+ChatMessage.text);
PunChatClientBroker.ChatClient.PublishMessage(PhotonNetwork.room.Name,ChatMessage.text);
}
#region MonoBehavior Callbacks
// Use this for initialization
void Start () {
ConnectingPanel.SetActive(false);
UserIdForm.SetActive(true);
MainChatPanel.SetActive(false);
}
void OnEnable()
{
PunAndChatConnection.OnConnectedAction += OnConnected;
PunAndChatConnection.OnDisconnectedAction += OnDisconnected;
}
void OnDisable()
{
PunAndChatConnection.OnConnectedAction -= OnConnected;
PunAndChatConnection.OnDisconnectedAction -= OnDisconnected;
}
#endregion
#region PUN Callbacks
public void OnPhotonRandomJoinFailed()
{
PhotonNetwork.CreateRoom(null,new RoomOptions(){PublishUserId=true},TypedLobby.Default);
}
public void OnJoinedRoom()
{
if (debug) Debug.Log("MenuManager: OnJoinedRoom : "+PhotonNetwork.room.Name);
UserIdForm.SetActive(false);
background.SetActive(false);
MainChatPanel.SetActive(true);
PunChatClientBroker.ChatClient.Subscribe(new string[]{PhotonNetwork.room.Name});
PhotonNetwork.Instantiate(this.PlayerPrefab.name, transform.position, Quaternion.identity, 0);
}
public void OnLeftRoom()
{
if (debug) Debug.Log("MenuManager: OnLeftRoom");
background.SetActive(true);
MainChatPanel.SetActive(false);
UserIdForm.SetActive(true);
PunChatClientBroker.ChatClient.Unsubscribe(new string[]{PhotonNetwork.room.Name});
}
#endregion
#region PunAndChatConnection Callbacks
void OnConnected()
{
if (debug) Debug.Log("MenuManager: OnConnected");
ConnectingPanel.SetActive(false);
PhotonNetwork.JoinRandomRoom();
}
void OnDisconnected()
{
if (debug) Debug.Log("MenuManager: OnDisconnected");
background.SetActive(true);
ConnectingPanel.SetActive(false);
UserIdForm.SetActive(true);
}
#endregion PunAndChatConnection
}
<file_sep>/Assets/Photon Chat Utils/PunChatClientBroker.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using ExitGames.Client.Photon.Chat;
/// <summary>
/// Implement this interface to receive connection information from ChatClient.
/// It's mandatory to register/Unregister your interfaces instance PunChatClientBroker.instance.Register() and PunChatClientBroker.instance.Unregister()
/// </summary>
public interface IPunChatConnection
{
/// <summary>
/// Called when ChatClient is connected
/// </summary>
void OnConnected();
/// <summary>
/// Called when ChatClient is disconnected
/// </summary>
void OnDisconnected();
/// <summary>
/// Called when ChatClient state changes
/// </summary>
/// <param name="state">State.</param>
void OnChatStateChange (ChatState state);
}
/// <summary>
/// Implement this interface to receive User centric informations from the ChatClient.
/// It's mandatory to register/Unregister your interfaces instance PunChatClientBroker.instance.Register() and PunChatClientBroker.instance.Unregister()
/// </summary>
public interface IPunChatUser
{
/// <summary>
/// The user targeted by this Interface Instance.
/// Set this prior registering to PunChatClientBroker()
/// </summary>
/// <value>The user.</value>
string User { get; set; }
/// <summary>
/// Status Update for this User.
/// </summary>
/// <param name="status">Status.</param>
/// <param name="gotMessage">If set to <c>true</c> got message.</param>
/// <param name="message">Message.</param>
void OnStatusUpdate (int status, bool gotMessage, object message);
/// <summary>
/// messages received for this User
/// </summary>
/// <param name="channel">Channel.</param>
/// <param name="senders">Senders.</param>
/// <param name="messages">Messages.</param>
void OnGetMessages (string channel,string[] senders, object[] messages);
/// <summary>
/// Private Messages for this User
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="message">Message.</param>
/// <param name="channelName">Channel name.</param>
void OnPrivateMessage (string sender, object message, string channelName);
}
/// <summary>
/// Implement this interface to receive Channel centric informations from the ChatClient.
/// It's mandatory to register/Unregister your interfaces instance PunChatClientBroker.instance.Register() and PunChatClientBroker.instance.Unregister()
/// </summary>
public interface IPunChatChannel
{
/// <summary>
/// The Channel targeted by this Interface Instance.
/// </summary>
/// <value>The channel.</value>
string Channel { get; set; }
/// <summary>
/// Subscription for this Channel by the local User
/// </summary>
/// <param name="result">If set to <c>true</c> result.</param>
void OnSubscribed (bool result);
/// <summary>
/// Unsubscription for this channel by the local User
/// </summary>
void OnUnsubscribed ();
/// <summary>
/// Messages received for this Channel
/// </summary>
/// <param name="senders">Senders.</param>
/// <param name="messages">Messages.</param>
void OnGetMessages (string[] senders, object[] messages);
}
/// <summary>
/// Pun chat client broker.
/// Register your classes to be inform of particular contexts.
/// Interfaces: IPunChatConnection,IPunChatUser,IPunChatChannel
/// </summary>
public class PunChatClientBroker : MonoBehaviour, IChatClientListener {
/// <summary>
/// Singleton
/// </summary>
public static PunChatClientBroker Instance;
/// <summary>
/// The chat client.
/// When using the PunChatClientBroker, this is the property to use to access the ChatClient.
/// </summary>
public static ChatClient ChatClient;
/// <summary>
/// The auth values.
/// </summary>
public static ExitGames.Client.Photon.Chat.AuthenticationValues AuthValues;
/// <summary>
/// Define if service needs to be called every Update or not.
/// </summary>
public bool activeService = true;
/// <summary>
/// Output logs to the Unity Console.
/// </summary>
public bool debug = false;
static List<IPunChatConnection> PunChatConnectionList = new List<IPunChatConnection>();
static Dictionary<string,List<IPunChatUser>> PunChatUserList = new Dictionary<string, List<IPunChatUser>>();
static Dictionary<string,List<IPunChatChannel>> PunChatChannelList = new Dictionary<string, List<IPunChatChannel>>();
#region Action Delegates
/// <summary>
/// Callback for Disconnection event
/// </summary>
public static Action OnDisconnectedAction { get; set; }
/// <summary>
/// Callback for connected event.
/// </summary>
public static Action OnConnectedAction { get; set; }
/// <summary>
/// Callback when chat state changed
/// </summary>
public static Action<ChatState> OnChatStateChangeAction { get; set; }
/// <summary>
/// Callback when the local Player subscribed to channel(s)
/// </summary>
public static Action<string[],bool[]> OnSubscribedAction { get; set; }
/// <summary>
/// Callback when the local Player unsubscribed from channel(s)
/// </summary>
public static Action<string[]> OnUnsubscribedAction { get; set; }
/// <summary>
/// Callback when a User status changed
/// </summary>
public static Action<string,int,bool,object> OnStatusUpdateAction { get; set; }
#endregion Action Delegates
void Awake() {
Instance = this;
ChatClient = new ChatClient(this);
}
void Update() {
if (PunChatClientBroker.ChatClient != null && activeService)
{
PunChatClientBroker.ChatClient.Service();
}
}
#region IChatClientListener implementation
public void DebugReturn (ExitGames.Client.Photon.DebugLevel level, string message)
{
if (level == ExitGames.Client.Photon.DebugLevel.ERROR)
{
UnityEngine.Debug.LogError(message);
}
else if (level == ExitGames.Client.Photon.DebugLevel.WARNING)
{
UnityEngine.Debug.LogWarning(message);
}
else
{
if (debug) UnityEngine.Debug.Log(message);
}
}
public void OnConnected ()
{
if (debug) Debug.Log("PunChatClientBroker: OnConnected",this);
if (OnConnectedAction!=null) OnConnectedAction();
PunChatConnectionList.ForEach(p => p.OnConnected());
}
public void OnDisconnected ()
{
if(debug) Debug.Log("PunChatClientBroker: OnDisconnected",this);
OnDisconnectedAction();
PunChatConnectionList.ForEach(p => p.OnDisconnected());
}
public void OnChatStateChange (ChatState state)
{
if (debug) Debug.Log("PunChatClientBroker: OnChatStateChange "+state,this);
if (OnChatStateChangeAction!=null) OnChatStateChangeAction(state);
PunChatConnectionList.ForEach(p => p.OnChatStateChange(state));
}
public void OnGetMessages (string channelName, string[] senders, object[] messages)
{
if (debug) Debug.Log("PunChatClientBroker: OnGetMessages for "+channelName+" senders "+senders.ToStringFull(),this);
if (PunChatChannelList.ContainsKey(channelName))
{
PunChatChannelList[channelName].ForEach(p => p.OnGetMessages(senders,messages));
}
foreach(var _ui in PunChatUserList)
{
_ui.Value.ForEach(p => p.OnGetMessages(channelName,senders,messages));
}
}
public void OnPrivateMessage (string sender, object message, string channelName)
{
if (debug) Debug.Log("PunChatClientBroker: OnPrivateMessage from "+sender,this);
if (PunChatUserList.ContainsKey(sender))
{
PunChatUserList[sender].ForEach(p => p.OnPrivateMessage(sender,message,channelName));
}
}
public void OnSubscribed (string[] channels, bool[] results)
{
if (debug) Debug.Log("PunChatClientBroker: OnSubscribed to "+channels.ToStringFull(),this);
if (OnSubscribedAction!=null) OnSubscribedAction(channels,results);
int i=0;
foreach(string _channel in channels)
{
if (PunChatChannelList.ContainsKey(_channel))
{
PunChatChannelList[_channel].ForEach(p => p.OnSubscribed(results[i]));
}
i++;
}
}
public void OnUnsubscribed (string[] channels)
{
if (debug) Debug.Log("PunChatClientBroker: OnUnsubscribed from "+channels.ToStringFull(),this);
if (OnUnsubscribedAction!=null) OnUnsubscribedAction(channels);
int i=0;
foreach(string _channel in channels)
{
if (PunChatChannelList.ContainsKey(_channel))
{
PunChatChannelList[_channel].ForEach(p => p.OnUnsubscribed());
}
i++;
}
}
public void OnStatusUpdate (string user, int status, bool gotMessage, object message)
{
if (debug) Debug.Log("PunChatClientBroker: OnStatusUpdate for "+user+" status:"+status,this);
if (OnStatusUpdateAction!=null) OnStatusUpdateAction(user,status,gotMessage,message);
if (PunChatUserList.ContainsKey(user))
{
PunChatUserList[user].ForEach(p => p.OnStatusUpdate(status,gotMessage,message));
}
}
#endregion IChatClientListener implementation
#region Interfaces Registration
static public void Register(IPunChatConnection target)
{
if (target==null)
{
return;
}
if (!PunChatConnectionList.Contains(target))
{
if (Instance!=null && Instance.debug) Debug.Log("PunChatClientBroker: Register Connection ");
PunChatConnectionList.Add(target);
}
}
static public void Unregister(IPunChatConnection target)
{
if (target==null)
{
return;
}
if (!PunChatConnectionList.Contains(target))
{
if (Instance!=null && Instance.debug) Debug.Log("PunChatClientBroker: Unregister Connection ");
PunChatConnectionList.Remove(target);
}
}
static public void Register(IPunChatUser target)
{
if (target==null || string.IsNullOrEmpty(target.User) )
{
return;
}
if (!PunChatUserList.ContainsKey(target.User))
{
PunChatUserList[target.User] = new List<IPunChatUser>();
}
if (!PunChatUserList[target.User].Contains(target))
{
if (Instance!=null && Instance.debug) Debug.Log("PunChatClientBroker: register User "+target.User);
PunChatUserList[target.User].Add(target);
}
}
static public void Unregister(IPunChatUser target)
{
if (target==null || string.IsNullOrEmpty(target.User) )
{
return;
}
if (!PunChatUserList.ContainsKey(target.User))
{
return;
}
if (!PunChatUserList[target.User].Contains(target))
{
if (Instance!=null && Instance.debug) Debug.Log("PunChatClientBroker: Unregister User "+target.User);
PunChatUserList[target.User].Remove(target);
}
}
static public void Register(IPunChatChannel target)
{
if (target==null || string.IsNullOrEmpty(target.Channel) )
{
return;
}
if (!PunChatChannelList.ContainsKey(target.Channel))
{
PunChatChannelList[target.Channel] = new List<IPunChatChannel>();
}
if (!PunChatChannelList[target.Channel].Contains(target))
{
if (Instance!=null && Instance.debug) Debug.Log("PunChatClientBroker: Register channel "+target.Channel);
PunChatChannelList[target.Channel].Add(target);
}
}
static public void Unregister(IPunChatChannel target)
{
if (target==null || string.IsNullOrEmpty(target.Channel) )
{
return;
}
if (!PunChatChannelList.ContainsKey(target.Channel))
{
return;
}
if (!PunChatChannelList[target.Channel].Contains(target))
{
if (Instance!=null && Instance.debug) Debug.Log("PunChatClientBroker: Unregister channel "+target.Channel);
PunChatChannelList[target.Channel].Remove(target);
}
}
#endregion Interfaces Registration
}
<file_sep>/Assets/PUN Custom Samples/Common/Scripts/PhotonNetworkExtensions.cs
using UnityEngine;
using System.Collections;
/// <summary>
/// Photon network extensions.
/// WARNING: this we can't extends static classes, it's not technically extensions but rather composisions.
/// </summary>
public static class PhotonNetworkExtensions {
public static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, byte group,bool usePrefabPool = false)
{
return Instantiate(prefabName, position, rotation, group, null,usePrefabPool);
}
public static GameObject Instantiate(string prefabName, Vector3 position, Quaternion rotation, byte group, object[] data, bool usePrefabPool = false)
{
IPunPrefabPool _prefabPool = null;
if (! usePrefabPool)
{
_prefabPool = PhotonNetwork.PrefabPool;
PhotonNetwork.PrefabPool = null;
}
GameObject _instance = PhotonNetwork.Instantiate(prefabName, position, rotation, group, data);
if (! usePrefabPool)
{
PhotonNetwork.PrefabPool = _prefabPool;
}
return _instance;
}
}<file_sep>/README.md
# Exitgames--Custom--Samples_u4
Unity Exitgames Custom Samples
This repository is a set of custom demo for PUN and related products
- [Unity 4.7.2](http://unity3d.com/)
- [PUN 1.79](https://www.assetstore.unity3d.com/en/#!/content/1786)
## Unity Packages
You can find packages samples download in the [Packages](https://github.com/jeanfabre/Exitgames--Custom--Samples_U4/tree/master/Packages) folder
<file_sep>/Assets/PUN Custom Samples/PunAndChatDemo/Scripts/NamePickUiForm.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
[System.Serializable]
public class OnSubmit : UnityEvent<string> {}
public class NamePickUiForm : MonoBehaviour
{
private const string UserNamePlayerPref = "NamePickUserName";
public InputField UserNameInput;
public OnSubmit OnSubmit;
public void Start()
{
string prefsName = PlayerPrefs.GetString(UserNamePlayerPref);
if (!string.IsNullOrEmpty(prefsName))
{
this.UserNameInput.text = prefsName;
}
}
// new UI will fire "EndEdit" event also when loosing focus. So check "enter" key and only then StartChat.
public void EndEditOnEnter()
{
if (Input.GetKey(KeyCode.Return) || Input.GetKey(KeyCode.KeypadEnter))
{
this.Submit();
}
}
public void Submit()
{
// ChatGui chatNewComponent = FindObjectOfType<ChatGui>();
//chatNewComponent.UserName = this.idInput.text.Trim();
//chatNewComponent.Connect();
enabled = false;
PlayerPrefs.SetString(UserNamePlayerPref, UserNameInput.text);
this.OnSubmit.Invoke(UserNameInput.text);
}
}<file_sep>/Assets/Photon Chat Utils/PunAndChatConnection.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ExitGames.Client.Photon.Chat;
/// <summary>
/// Leverage connection for Pun and Chat for them to work in tandem.
///
/// Dependancy: PunChatClientBroker. It's likely a good idea to have both components on One GameObject for clarity.
///
/// The Premise is that Chat UserId is the same as Pun UserId (coming from your Online Social network system for your gamer's community during authentication).
///
/// Call Connect() and Disconnect() to control both PUN and Chat Connections.
///
/// Register to OnConnectedAction() and OnDisconnectedAction() Actions to receive callbacks on connection status for Pun+Chat Tandem.
///
/// TODO: more options for connecting, and external authentication setup
/// </summary>
public class PunAndChatConnection : MonoBehaviour, IPunChatConnection {
/// <summary>
/// The game version. Use both for PUN and CHAT
/// </summary>
public string GameVersion = "1.0";
/// <summary>
/// The user identifier. Used for both PUN and CHAT
///
/// Set this value prior calling Connect() method
/// </summary>
public string UserId = "";
/// <summary>
/// The NickName. This is a PUN only feature. Leave to empty if you don't want this script to use it.
/// </summary>
public string NickName = "";
/// <summary>
/// If true, output logs on the various states of PUN and Chat connection.
/// </summary>
public bool debug = false;
/// <summary>
/// Callback when PUN and CHAT are both connected. Use Connect() method to initiate connections for PUN and CHAT
/// </summary>
public static Action OnConnectedAction { get; set; }
/// <summary>
/// Callback when either PUN or Chat disconnected. Use Disconnect() method to disconnect both PUN and CHAT
/// </summary>
public static Action OnDisconnectedAction { get; set; }
private bool IsConnected;
#region MonoBehaviour Callbacks
void Start()
{
PunChatClientBroker.Register(this);
IsConnected = false;
}
#endregion
/// <summary>
/// Connect to PUN and CHAT
/// UserId is expected to be set prior calling
///
/// Register to OnConnectedAction delegate to be informed when connection is effective for both PUN and CHAT
/// </summary>
public void Connect()
{
if (debug) Debug.Log("PunAndChatConnection: Connect() as <"+UserId+">");
PunChatClientBroker.ChatClient.Connect(PhotonNetwork.PhotonServerSettings.ChatAppID, GameVersion, new ExitGames.Client.Photon.Chat.AuthenticationValues(UserId));
if (!PhotonNetwork.connected)
{
if (!string.IsNullOrEmpty(NickName)) PhotonNetwork.playerName = NickName;
PhotonNetwork.AuthValues = new AuthenticationValues(){UserId=UserId};
PhotonNetwork.ConnectUsingSettings(GameVersion);
}
}
/// <summary>
/// Disconnect from PUN and CHAT
///
/// Register to OnDisconnectedAction delegate to be informed when disconnection occured with either PUN or CHAT
/// </summary>
public void disconnect()
{
if (debug) Debug.Log("PunAndChatConnection: disconnect()");
IsConnected = false;
if (PunChatClientBroker.ChatClient !=null && PunChatClientBroker.ChatClient.CanChat)
{
PunChatClientBroker.ChatClient.Disconnect();
}
if (PhotonNetwork.connected)
{
PhotonNetwork.Disconnect();
}
}
void CheckIfBothConnected()
{
if (IsConnected)
{
return ;
}
if (PunChatClientBroker.ChatClient == null){
return;
}
IsConnected = PhotonNetwork.connected && PunChatClientBroker.ChatClient.CanChat;
if (IsConnected)
{
if (debug) Debug.Log("PunAndChatConnection: PUN and CHAT connected");
if (OnConnectedAction!=null) OnConnectedAction();
}
}
#region Pun CallBacks
public virtual void OnConnectedToMaster()
{
if (debug) Debug.Log("PunAndChatConnection: OnConnectedToMaster() was called by PUN.");
CheckIfBothConnected();
}
public virtual void OnJoinedLobby()
{
if (debug) Debug.Log("PunAndChatConnection:OnJoinedLobby() was called by PUN.");
CheckIfBothConnected();
}
public virtual void OnDisconnectedFromPhoton()
{
if (debug) Debug.Log("PunAndChatConnection: OnDisconnectedFromPhoton() was called by PUN.");
if (OnDisconnectedAction!=null) OnDisconnectedAction();
}
#endregion Pun CallBacks
#region IPunChatConnection implementation
public void OnConnected()
{
if (debug) Debug.Log("PunAndChatConnection: OnConnected() was called by Chat.");
PunChatClientBroker.ChatClient.SetOnlineStatus(ChatUserStatus.Online);
CheckIfBothConnected();
}
public void OnDisconnected()
{
if (debug) Debug.Log("PunAndChatConnection: OnDisconnected() was called by Chat. cause:"+PunChatClientBroker.ChatClient.DisconnectedCause);
PunChatClientBroker.ChatClient = null;
if (OnDisconnectedAction!=null) OnDisconnectedAction();
}
public void OnChatStateChange (ChatState state)
{
if (debug) Debug.Log("PunAndChatConnection: OnChatStateChange() was called by Chat. ChatState:"+state);
}
#endregion
}
<file_sep>/Assets/PUN Custom Samples/PunAndChatDemo/Scripts/PlayerPunChatUI.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerPunChatUI : MonoBehaviour {
#region Public Properties
[Tooltip("Pixel offset from the player target")]
public Vector3 ScreenOffset = new Vector3(0f,30f,0f);
[Tooltip("UI Text to display Player's Name")]
public Text PlayerNameText;
[Tooltip("UI Slider to display Player's Health")]
public Text messageText;
#endregion
#region Private Properties
PlayerPunChat _target;
float _characterControllerHeight = 0f;
Transform _targetTransform;
Renderer _targetRenderer;
Vector3 _targetPosition;
#endregion
#region MonoBehaviour Messages
/// <summary>
/// MonoBehaviour method called on GameObject by Unity during early initialization phase
/// </summary>
void Awake(){
this.GetComponent<Transform>().SetParent (GameObject.Find("Canvas").GetComponent<Transform>());
}
/// <summary>
/// MonoBehaviour method called on GameObject by Unity on every frame.
/// update the health slider to reflect the Player's health
/// </summary>
void Update()
{
// Destroy itself if the target is null, It's a fail safe when Photon is destroying Instances of a Player over the network
if (_target == null) {
Destroy(this.gameObject);
return;
}
}
/// <summary>
/// MonoBehaviour method called after all Update functions have been called. This is useful to order script execution.
/// In our case since we are following a moving GameObject, we need to proceed after the player was moved during a particular frame.
/// </summary>
void LateUpdate () {
// Do not show the UI if we are not visible to the camera, thus avoid potential bugs with seeing the UI, but not the player itself.
if (_targetRenderer!=null) {
this.gameObject.SetActive(_targetRenderer.isVisible);
}
// #Critical
// Follow the Target GameObject on screen.
if (_targetTransform!=null)
{
_targetPosition = _targetTransform.position;
_targetPosition.y += _characterControllerHeight/2f;
this.transform.position = Camera.main.WorldToScreenPoint (_targetPosition) + ScreenOffset;
}
}
#endregion
#region Public Methods
public void SetTarget(PlayerPunChat target){
if (target == null) {
Debug.LogError("<Color=Red><b>Missing</b></Color> PlayerPunChat target for PlayerUI.SetTarget.",this);
return;
}
// Cache references for efficiency because we are going to reuse them.
_target = target;
_targetTransform = _target.GetComponent<Transform>();
_targetRenderer = _target.GetComponent<Renderer>();
CharacterController _characterController = _target.GetComponent<CharacterController> ();
// Get data from the Player that won't change during the lifetime of this Component
if (_characterController != null){
_characterControllerHeight = _characterController.height;
}
if (PlayerNameText != null) {
PlayerNameText.text = _target.photonView.owner.NickName;
}
}
public void SetMessage(string message)
{
messageText.text = message;
}
#endregion
}
| e748e6ed8900407deb385e981e92b264180df986 | [
"Markdown",
"C#"
] | 8 | C# | jeanfabre/Exitgames--Custom--Samples_U4 | 9d1d92b3d6f30f15ffdd96c757ef5154e767f65d | bd6f72d0471ab87c4b1666aa7b026312a8ee40f5 |
refs/heads/master | <repo_name>izaakschroeder/generator-flowtype<file_sep>/README.md
# generator-flowtype
Add [flow] static type checking to your JavaScript projects.
```sh
npm install -g @metalab/generator-flowtype
yo @metalab/flowtype
```
Use with React:
```sh
yo @metalab/flowtype:lib --path node_modules/fbjs/flow/include
```
**IMPORTANT**: `flow check --all` is pretty broken. You have to annotate every single file you want to check with `/* @flow */`. Hopefully this will be addressed with https://github.com/facebook/flow/issues/284.
[flow]: http://flowtype.org
<file_sep>/lib/merge.js
var NEWLINE = /\r\n|[\n\v\f\r\x85\u2028\u2029]/;
var SECTION = /\[([^\]]+)\]/;
var WHITESPACE = /^\s*$/;
function uniq(a) {
return a.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
};
function parse(input) {
var sections = { };
var section = '_';
var lines = input.split(NEWLINE);
lines.forEach(function(line) {
var parts = SECTION.exec(line);
if (parts) {
section = parts[1];
} else if (!WHITESPACE.exec(line)) {
if (!(section in sections)) {
sections[section] = [];
}
sections[section].push(line);
}
});
return sections;
}
module.exports = function merge(dst, src) {
var result = [ ];
dst = parse(dst);
src = parse(src);
Object.keys(src).forEach(function(section) {
if (!(section in dst)) {
dst[section] = src[section];
} else {
dst[section].push.apply(dst[section], src[section]);
}
});
Object.keys(dst).forEach(function(section) {
dst[section] = uniq(dst[section]);
result.push('[' + section + ']');
result.push.apply(result, dst[section]);
result.push('');
});
return result.join('\n');
}
<file_sep>/generators/ignore/index.js
var util = require('yeoman-util');
var merge = require('../../lib/merge');
module.exports = util.Base.extend({
prompting: util.prompt([{
name: 'path',
type: 'input',
message: 'Path to ignore',
}]),
writing: util.copy('.flowconfig', 'flowconfig', {
transform: merge
}),
});
| 0457f0d92638ad402fc1e18e026c8458bb7aaab5 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | izaakschroeder/generator-flowtype | 290c3e97aa90fd9e6b0190bc74a0f6cf3223188d | 4585753ad4f5cc07b36450d314bb9f35418f5bd8 |
refs/heads/master | <repo_name>Miladkhoshdel/phpmyadmin_brute_forcer<file_sep>/phpmyadmin_brute_forcer.py
#Created By: <NAME>
#Blog: https://regux.com
#Email: <EMAIL>
#Telegram: @miladkhoshdel
import urllib2
import argparse
import sys
import os
import time
def banner():
print(' ')
print(' ################################################################################################')
print(' ## ##')
print(' ## __ __ ___ _ _ __ __ ___ _ __ ##')
print(' ## | \/ |_ _| | /_\ | \/ |_ _| |/ / ##')
print(" ## | |\/| || || |__ / _ \| |\/| || || ' < ##")
print(' ## |_| |_|___|____/_/ \_\_| |_|___|_|\_\ ##')
print(' ## ##')
print(' ## BY: <NAME> | Mikili ##')
print(' ## Blog: https://blog.regux.com ##')
print(' ## ##')
print(' ################################################################################################')
print(' ')
print(' Usage: ./phpmyadmin_brute_forcer.py [options]')
print(' ')
print(' Options: -t, --target <hostname/ip> | Target')
print(' -u, --user <user> | User')
print(' -w, --wordlist <filename> | Wordlist')
print(' ')
print(' Example: python phpmyadmin_brute_forcer.py -t http://target/phpmyadmin -u [username] -w ./a.txt')
print(' ')
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target")
parser.add_argument("-u", "--username")
parser.add_argument("-w", "--wordlist")
args = parser.parse_args()
if not args.target or not args.username or not args.wordlist:
banner()
sys.exit(0)
target = args.target
username = args.username
wordlist = args.wordlist
a = 0
def login(t, u, p):
try:
sys.stdout.write('[-] checking user [' + u + '] with password [' + p + ']')
sys.stdout.flush()
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, t, u, p)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(t)
restart_line()
sys.stdout.write('[-] checking user [' + u + '] with password [' + p + ']\t\t\tSuccess!')
sys.stdout.flush()
print('')
print('Password Successfully found.')
print('')
print('-------------------------')
print(' Host: ' + t)
print(' User: ' + u)
print(' Pass: ' + p)
print('-------------------------')
return True
except:
restart_line()
sys.stdout.write('[-] checking user [' + u + '] with password [' + p + ']\t\t\tFailed!')
sys.stdout.flush()
print('')
return False
pass
def attack(t, u, w):
try:
wordlist = open(w, "r")
passwords = wordlist.readlines()
for w in passwords:
w = w.strip()
result = login(t, u, w)
if result:
exit()
except IOError:
print "\n Please Check your wordlist. \n"
sys.exit(0)
attack(target, username, wordlist)
<file_sep>/README.md
Welcome to phpMyAdmin Brute Forcer!
===================
Created By: **<NAME>**
Blog: https://regux.com
Email: <EMAIL>
Telegram: @miladkhoshdel
----------
Documents
-------------
This is the source code of phpMyAdmin Brute Forcer. This script get a wordlist and brute force phpMyAdmin accounts.
> **Note:**
The code is written in python **2.7.x**
**Important**: you must install python before run this script.
> - For install python in linux:
wget --no-check-certificate https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tgz
tar -xzf Python-2.7.13.tgz
cd Python-2.7.13
> - For install python on windows:
Download python 2.7.13 from below url:
URL: https://www.python.org/downloads/
| 7579f162e60f8a39c451015e909ccad3c89b672d | [
"Markdown",
"Python"
] | 2 | Python | Miladkhoshdel/phpmyadmin_brute_forcer | 70f8293ebfa17b94fefccad70dff8f4be8ba07b1 | 63a48f7e9e798680ed5cded965c1fb7aa3dafcf1 |
refs/heads/master | <repo_name>hungerr/yueqiu<file_sep>/yueqiu/views.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse,Http404
from django.contrib.auth import authenticate, login, logout
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated,AllowAny
from django.core.files.base import ContentFile
import json
import random
import datetime
import requests
import math
from theuser.models import MyUser,MyUserToken
from yueqiu.models import Sport,Area,Site,PersonSports,ClubSports,Shows,\
Message,Comment,Love,Version,Opition
class UnsafeSessionAuthentication(SessionAuthentication):
def authenticate(self, request):
http_request = request._request
user = getattr(http_request, 'user', None)
if not user or not user.is_active:
return None
return (user, None)
class CreateToken(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def send_token(self,token,phone):
url='http://116.213.72.20/SMSHttpService/send.aspx'
content='【约球】您的验证码是'+token
data={'username':'fuchi','password':'<PASSWORD>','mobile':phone,'content':content}
r=requests.post(url,data=data)
return r.content
def post(self, request, format=None):
phone=request.POST.get('USERID','')
phone=str(phone)
if phone:
user,created=MyUserToken.objects.get_or_create(phone=phone)
token=random.randint(100000,999999)
user.token=str(token)
user.save()
result=self.send_token(str(token),phone)
if result=='0':
data={"RETCODE":"0",}
return Response(data)
else:
data={'success':False,'err_code':result}
return Response(data)
else:
data={'success':False,'err_msg':'empty phone','err_code':1004}
return Response(data)
class Reg(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def post(self, request, format=None):
phone=request.POST.get('MOBINO','').strip()
phone=str(phone)
token=request.POST.get('VERFCD','').strip()
token=str(token)
usertype=request.POST.get('USERTP','').strip()
usertype=int(usertype)
try:
usertoken=MyUserToken.objects.get(phone=phone)
if usertoken.token==token:
if MyUser.objects.filter(MOBILE=phone).exists():
data={'success':False,'RETCODE':1001,'RETPARAS':'phone number was used'}
else:
user=MyUser.objects.create_user(MOBILE=phone,password='<PASSWORD>')
data={'success':True,'RETCODE':0,'MOBILE':phone,'_USERID':user.id}
else:
data={'success':False,'RETCODE':1003,'RETPARAS':u'wrong token'}
except:
data={'success':False,'RETCODE':1004,'RETPARAS':u'token donot exists'}
return Response(data)
class UpdateAndLogin(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
phone=str(phone)
user=self.get_user(phone)
nicknm=request.POST.get('NICKNM','').strip()
passwd=request.POST.get('PASSWD','').strip()
user.NICKNM=nicknm
if not user.is_third:
user.set_password(passwd)
user.save()
data={"RETCODE":"0","RETPARAS":"登陆成功","_LOGNTP":"0","_USERID":phone,}
return Response(data)
class VerCode(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_token(self, phone,token):
try:
return MyUserToken.objects.get(phone=phone,token=token)
except MyUserToken.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('MOBINO','').strip()
token=request.POST.get('VERFCD','').strip()
myusertoken=self.get_token(phone,token)
data={"RETCODE":"0","RETPARAS":"验证成功"}
return Response(data)
class Login(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
pw=request.POST.get('PASSWD','').strip()
if phone and pw:
user=authenticate(MOBILE=phone,password=pw)
if user is not None:
if user.is_active:
login(request,user)
data={'success':True,'_USERID':user.MOBILE,'RETCODE':'0','RETPARSA':u"登陆成功",'_LOGNTP':'0'}
else:
data={'success':False,'err_msg':'user is disabled'}
elif MyUser.objects.filter(MOBILE=phone).exists():
data={'success':False,'RETCODE':1001,'err_msg':'wrong password'}
else:
data={'success':False,'RETCODE':1002,'err_msg':'need reg'}
else:
data={'success':False,'RETCODE':1003,'err_msg':'empty phone or password'}
return Response(data)
class ThirdLogin(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
platnm=request.POST.get('PLATNM','').strip()
if (not MyUser.objects.filter(MOBILE=phone).exists()) and (not MyUser.objects.filter(openid=phone).exists()) :
user=MyUser.objects.create_user(MOBILE=phone,password='<PASSWORD>')
user.openid=phone
user.is_third=True
user.save()
data={'success':True,'_USERID':phone,'RETCODE':'0','RETPARSA':u"登陆成功",'_LOGNTP':'1'}
return Response(data)
class ModifyPW(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
pw=request.POST.get('PASSWD','').strip()
user=self.get_user(phone)
user.set_password(pw)
data={'success':True,'_USERID':phone,'RETCODE':'0','RETPARSA':u"登陆成功",'_LOGNTP':'0'}
return Response(data)
class GetBindStat(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
user=self.get_user(phone)
if user.is_bind:
data={'success':True,"RETPARAS" :u"您已绑定了手机",'RETCODE':'0','ISBIND':"1",}
else:
data={'success':True,"RETPARAS" :u"您未绑定了手机",'RETCODE':'0','ISBIND':"0",}
return Response(data)
class BindMobile(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_token(self, phone):
try:
return MyUserToken.objects.get(phone=phone)
except MyUserToken.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
token=request.POST.get('VERFCD','').strip()
mobile=request.POST.get('MOBINO','').strip()
user=self.get_user(phone)
usertoken=self.get_token(mobile)
if usertoken.token==token:
user.MOBILE=mobile
user.openid=phone
user.is_bind=True
user.save()
data={'success':True,"RETPARAS" :u"绑定手机号成功",'RETCODE':'0',}
else:
data={'success':True,"RETPARAS" :u"验证码错误",'RETCODE':'1',}
return Response(data)
class CreatePersonalSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return Sport.objects.get(pk=int(pk))
except Sport.DoesNotExist:
raise Http404
def get_site(self, pk):
try:
return Site.objects.get(pk=int(pk))
except Site.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORNO','').strip()
name=request.POST.get('SPNAME','').strip()
siteid=request.POST.get('SITEID','').strip()
time=request.POST.get('SPTIME','').strip()
maxper=request.POST.get('MAXPER','').strip()
spcost=request.POST.get('SPCOST','').strip()
desc=request.POST.get('DESCRI','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
site=self.get_site(siteid)
year=int(time[0:4])
month=int(time[4:6])
day=int(time[6:8])
hour=int(time[8:10])
minute=int(time[10:12])
start=datetime.datetime(year=year,month=month,day=day,hour=hour,minute=minute)
psport=PersonSports.objects.create(name=name,site=site,start=start,max_num=\
int(maxper),money=int(spcost),cus=user,\
sport=sport,desc=desc,state=1)
psport.members.add(user)
psport.save()
data={'success':True,"RETPARAS" :u"创建个人活动成功",'RETCODE':'0','SPORID':psport.id}
return Response(data)
class CreateClubSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return Sport.objects.get(pk=int(pk))
except Sport.DoesNotExist:
raise Http404
def get_site(self, pk):
try:
return Site.objects.get(pk=int(pk))
except Site.DoesNotExist:
raise Http404
def post(self, request, format=None):
body=request.body
body=json.loads(body)
userid=body['USERID']
user=self.get_user(userid)
sportid=body['SPORNO']
sport=self.get_sport(sportid)
name=body['SPNAME']
time=body['SPTIME']
cost=body['SPCOST']
desc=body['DESCRI']
year=int(time[0:4])
month=int(time[4:6])
day=int(time[6:8])
hour=int(time[8:10])
minute=int(time[10:12])
start=datetime.datetime(year=year,month=month,day=day,hour=hour,minute=minute)
clubsport=ClubSports.objects.create(name=name,start=start,money=cost,\
cus=user,sport=sport,desc=desc,state=1)
for play in body['PLAYLIST']:
playid=int(play['PLAYID'])
time=play['BGINDT']
year=int(time[0:4])
month=int(time[4:6])
day=int(time[6:8])
hour=int(time[8:10])
minute=int(time[10:12])
start=datetime.datetime(year=year,month=month,day=day,hour=hour,minute=minute)
time=play['ENDDAT']
year=int(time[0:4])
month=int(time[4:6])
day=int(time[6:8])
hour=int(time[8:10])
minute=int(time[10:12])
end=datetime.datetime(year=year,month=month,day=day,hour=hour,minute=minute)
siteid=play['SITEID']
site=self.get_site(siteid)
maxper=int(play['MAXPER'])
Shows.objects.create(playid=playid,start=start,end=end,site=site,\
max_num=maxper,clubsport=clubsport)
data={"RETPARAS" :u"创建俱乐部活动成功",'RETCODE':'0','SPORID':clubsport.id}
return Response(data)
class GetSportTypes(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def post(self, request, format=None):
data=Sport.objects.values()
return Response(data)
class GetAreas(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def post(self, request, format=None):
data=Area.objects.values()
return Response(data)
class AttendPersonalSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return PersonSports.objects.get(pk=int(pk))
except PersonSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORID','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
if sport.members.count()<sport.max_num and sport.state==1:
sport.members.add(user)
sport.save()
data={"RETPARAS" :u"恭喜你",'RETCODE':'0'}
else:
data={"RETPARAS" :u"人数已满或者活动已开始或者取消",'RETCODE':'1'}
return Response(data)
class CancelPersonalSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return PersonSports.objects.get(pk=int(pk))
except PersonSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORID','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
if sport.cus==user:
sport.state=3
sport.save()
data={"RETPARAS" :u"恭喜你",'RETCODE':'0'}
else:
data={"RETPARAS" :u"你不是发起人",'RETCODE':'1'}
return Response(data)
class ConfirmPersonalSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return PersonSports.objects.get(pk=int(pk))
except PersonSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORID','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
if sport.cus==user:
sport.state=2
sport.save()
data={"RETPARAS" :u"恭喜你",'RETCODE':'0'}
else:
data={"RETPARAS" :u"你不是发起人",'RETCODE':'1'}
return Response(data)
class AttendClubSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return Shows.objects.get(pk=int(pk))
except Shows.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('PLAYID','').strip()
user=self.get_user(phone)
show=self.get_sport(sport)
if show.members.count()<show.max_num and show.clubsport.state==1:
show.members.add(user)
show.save()
data={"RETPARAS" :u"恭喜你",'RETCODE':'0'}
else:
data={"RETPARAS" :u"人数已满或者活动已开始或者取消",'RETCODE':'1'}
return Response(data)
class CancelClubSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return ClubSports.objects.get(pk=int(pk))
except ClubSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORID','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
if sport.cus==user:
sport.state=3
sport.save()
data={"RETPARAS" :u"恭喜你",'RETCODE':'0'}
else:
data={"RETPARAS" :u"你不是发起人",'RETCODE':'1'}
return Response(data)
class ConfirmClubSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return ClubSports.objects.get(pk=int(pk))
except ClubSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORID','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
if sport.cus==user:
sport.state=2
sport.save()
data={"RETPARAS" :u"恭喜你",'RETCODE':'0'}
else:
data={"RETPARAS" :u"你不是发起人",'RETCODE':'1'}
return Response(data)
class QueryPersonalSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return PersonSports.objects.get(pk=int(pk))
except PersonSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORID','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
data={}
data["BINDNO"]=sport.cus.MOBILE
data["NICKNM"]=sport.cus.NICKNM
data['DESCRI']=sport.desc
data['INICON']=sport.cus.ICONID.name
data['JOINERS']=sport.members.values('ICONID','NICKNM','MOBILE')
data['MAXPER']=sport.max_num
data['RETCODE']=0
data["spaddr"]=sport.site.name
data['SPCOST']=sport.money
data['SPNAME']=sport.name
data['SPORNO']=sport.sport.id
data["STATE"]=sport.state
data['SPTIME']=sport.start.strftime('%Y%m%d%H%M')
if user in sport.members.all():
data['HSJOIN']=1
else:
data['HSJOIN']=0
return Response(data)
class QueryClubSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return ClubSports.objects.get(pk=int(pk))
except ClubSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
phone=request.POST.get('USERID','').strip()
sport=request.POST.get('SPORID','').strip()
user=self.get_user(phone)
sport=self.get_sport(sport)
data={}
data["BINDNO"]=sport.cus.MOBILE
data["NICKNM"]=sport.cus.NICKNM
data['DESCRI']=sport.desc
data['INICON']=sport.cus.ICONID.name
data['PLLIST']=[]
for play in sport.shows_set.all():
playdata={}
playdata['BGINDT']=play.start.strftime('%Y%m%d%H%M')
playdata['ENDDAT']=play.end.strftime('%Y%m%d%H%M')
playdata['MAXPER']=play.max_num
playdata['PLAYID']=play.id
playdata['SPADDR']=play.site.name
if user in play.members.all():
playdata['HSJION']=1
else:
playdata['HSJION']=0
data['PLLIST'].append(playdata)
data['RETCODE']=0
data['SPCOST']=sport.money
data['SPNAME']=sport.name
data['SPORNO']=sport.sport.id
data["STATE"]=sport.state
data['SPTIME']=sport.start.strftime('%Y%m%d%H%M')
return Response(data)
class QueryAttendPersonals(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_sport(self, pk):
try:
return Shows.objects.get(pk=int(pk))
except Shows.DoesNotExist:
raise Http404
def post(self, request, format=None):
show=request.POST.get('PLAYID','').strip()
show=self.get_sport(show)
data={"JOINERS":show.members.values('MOBILE','ICONID','NICKNM'),"RETCODE":"0","RETPARAS":"查询成功"}
return Response(data)
class ApplyForSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return PersonSports.objects.get(pk=int(pk))
except PersonSports.DoesNotExist:
raise Http404
def get_show(self, pk):
try:
return Shows.objects.get(pk=int(pk))
except Shows.DoesNotExist:
raise Http404
def post(self, request, format=None):
fromid=request.POST.get('FROMID','').strip()
toid=request.POST.get('TARGID','').strip()
style=request.POST.get('TYPE','').strip()
showid=request.POST.get('PLAYID','').strip()
sportid=request.POST.get('SPORID','').strip()
fromid=self.get_user(fromid)
to=self.get_user(toid)
if int(style)==2:
sport=self.get_sport(sportid)
Message.objects.create(fromuser=fromid,touser=to,style=2,\
personalsport=sport)
else:
show=self.get_show(showid)
Message.objects.create(fromuser=fromid,touser=to,style=3,\
show=show)
data={"RETCODE":"0","RETPARAS":"操作成功"}
return Response(data)
class MarkLocation(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
location=request.POST.get('LOCATION','').strip()
user=self.get_user(userid)
wei=location.split(',')[0]
jing=location.split(',')[1]
user.LATITU=wei
user.LONGIT=jing
user.save()
data={"RETCODE":"0","RETPARAS":"操作成功"}
return Response(data)
class GetSites(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def post(self, request, format=None):
location=request.POST.get('LOCATION','').strip()
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
data=Site.objects.values()
for site in data:
site_wei=float(site['LATITU'])
site_jing=float(site['LONGIT'])
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
site['distance']=d
return Response(data)
class GetSportInSite(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_site(self, pk):
try:
return Site.objects.get(pk=int(pk))
except Site.DoesNotExist:
raise Http404
def post(self, request, format=None):
siteid=request.POST.get('SITEID','').strip()
site=self.get_site(siteid)
data=[]
sports=Sport.objects.all()
for sport in Sport.objects.all():
if not PersonSports.objects.filter(site=site,sport=sport).exists() and not Shows.objects.filter(site=site,sport=sport).exists():
sports.remove(sport)
data=sports.values('id','ICONID','SPORNM')
return Response(data)
class GetPlayInSite(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_site(self, pk):
try:
return Site.objects.get(pk=int(pk))
except Site.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
siteid=request.POST.get('SITEID','').strip()
site=self.get_site(siteid)
location=request.POST.get('LOCATION','').strip()
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
site_wei=float(site.LATITU)
site_jing=float(site.LONGIT)
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data=[]
for sport in site.personsports_set.all():
if user in sport.members.all():
data.append({"DISTANCE":d,"HSJION":sport.members.count(),"MAXPER":sport.max_num,"MYJION":"0",\
"NICKNM":sport.cus.NICKNM,"PICONID":sport.cus.ICONID.name if sport.cus.ICONID else '',"SICONID":sport.sport.ICONID.name if sport.sport.ICONID else '',\
"SPADDR":site.name,"SPCOST":sport.money,"SPNAME" : sport.name,"SPORNO":sport.sport.SPORNM,\
"SPORID" : sport.id,"SPTIME":sport.start.strftime('%Y%m%d%H%M'),})
else:
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"MYJION" : "1",
"NICKNM" : sport.cus.NICKNM,
"PICONID" : sport.cus.ICONID.name if sport.cus.ICONID else '',
"SICONID" : sport.sport.ICONID.name if sport.sport.ICONID else '',
"SPADDR" : site.name,
"SPCOST" : sport.money,
"SPNAME" : sport.name,
"SPORNO" : sport.sport.SPORNM,
"SPORID" : sport.id,
"SPTIME" : sport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class SearchClubSports(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_site(self, pk):
try:
return Site.objects.get(pk=int(pk))
except Site.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
siteid=request.POST.get('SITEID','').strip()
site=self.get_site(siteid)
location=request.POST.get('LOCATION','').strip()
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
site_wei=float(site.LATITU)
site_jing=float(site.LONGIT)
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data=[]
for sport in site.shows_set.all():
if user in sport.members.all():
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"MYJION" : "0",
"NICKNM" : sport.clubsport.cus.NICKNM,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '',
"SPADDR" : site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPROID" : sport.id,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
else:
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"MYJION" : "1",
"NICKNM" : sport.clubsport.cus.NICKNM,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '',
"SPADDR" : site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPROID" : sport.id,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class CommentUser(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
com=request.POST.get('COMMTP','').strip()
if com=='DOWN':
user.bad+=1
if com=='UP':
user.good+=1
user.save()
data={"RETCODE" : "0", "RETPARAS" : "评价成功"}
return Response(data)
class CommentSport(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return PersonSports.objects.get(pk=int(pk))
except PersonSports.DoesNotExist:
raise Http404
def get_show(self, pk):
try:
return ClubSports.objects.get(pk=int(pk))
except ClubSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('COMMID','').strip()
style=request.POST.get('TYPE','').strip()
content=request.POST.get('COMMTX','').strip()
sportid=request.POST.get('SPORID','').strip()
user=self.get_user(userid)
if int(style)==1:
sport=self.get_sport(sportid)
Comment.objects.create(user=user,style=1,personalsport=sport,content=content)
if int(style)==2:
sport=self.get_show(sportid)
Comment.objects.create(user=user,style=2,show=sport,content=content)
data={"RETCODE" : "0", "RETPARAS" : "评价成功"}
return Response(data)
class SelectMyLove(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return Sport.objects.get(pk=int(pk))
except Sport.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
style=request.POST.get('OPERTP','').strip()
star=request.POST.get('LOVELV','').strip()
star=int(star)
sportid=request.POST.get('SPORNO','').strip()
user=self.get_user(userid)
sport=self.get_sport(sportid)
if Love.objects.filter(user=user,sport=sport).exists():
if int(style)==1:
love=Love.objects.get(user=user,sport=sport)
love.star=star
love.save()
user.sports.add(sport)
user.save()
else:
Love.objects.get(user=user,sport=sport).delete()
user.sports.remove(sport)
user.save()
else:
if int(style)==1:
Love.objects.create(user=user,sport=sport,star=star)
user.sports.add(sport)
user.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class RecommSite(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_site(self, pk):
try:
return Site.objects.get(pk=int(pk))
except Site.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
style=request.POST.get('OPERTP','').strip()
siteid=request.POST.get('SITEID','').strip()
user=self.get_user(userid)
site=self.get_site(siteid)
if int(style)==1:
user.sites.add(site)
user.save()
else:
user.sites.remove(site)
user.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class UserCenter(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
data={"DOWNCM" :user.bad,"FRIEND" : user.friends.count(),\
"INTERESTS" : user.sports.values(),
"JIONED" :PersonSports.objects.filter(state=4,members=user).count()+Shows.objects.filter(clubsport__state=4,members=user).count(),
"NICKNM" : user.NICKNM,
"RETCODE" : "0",
"RETPARAS" : "操作成功",
"SIGNUP" : PersonSports.objects.filter(state__lt=3,members=user).count()+Shows.objects.filter(clubsport__state__lt=3,members=user).count(),
"SYSINF" : Message.objects.filter(touser=user,is_read=False).count(),
"UPCOMM" : user.good
}
if user.ICONID:
data['ICONID']=user.ICONID.name
else:
data['ICONID']=''
if user.TYPE==0:
data['INITIA']=PersonSports.objects.filter(cus=user).count()
else:
data['INITIA']=ClubSports.objects.filter(cus=user).count()
return Response(data)
class UpdateUserData(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
gender=request.POST.get('SEXUAL','').strip()
age=request.POST.get('PERAGE','').strip()
phone=request.POST.get('MOBILE','').strip()
desc=request.POST.get('RESUMM','').strip()
user=self.get_user(userid)
user.SEXUAL=int(gender)
user.PERAGE=int(age)
user.MOBILE=phone
user.RESUME=desc
user.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class QueryUserCenter(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
style=request.POST.get('LANGUA','').strip()
user=self.get_user(userid)
data={
"INTERESTS" : user.sports.values(),
"MOBILE" : user.MOBILE,
"NICKNM" : user.NICKNM,
"PERAGE" : user.PERAGE,
"RECOMMENDS" : user.sites.values(),
"RESUME" : user.RESUME,
"RETCODE" : "0",
"RETPARAS" : "操作成功",
"SEXUAL" : user.SEXUAL
}
if user.ICONID:
data['ICONID']=user.ICONID.name
else:
data['ICONID']=''
return Response(data)
class QueryEnterSportsPeronal(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
location=request.POST.get('LOCATION','').strip()
if location:
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
data=[]
for sport in PersonSports.objects.filter(state__lt=4,members=user):
site_wei=float(sport.site.LATITU)
site_jing=float(sport.site.LONGIT)
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.cus.NICKNM,
"PICONID" : sport.cus.ICONID.name if sport.cus.ICONID else '' ,
"SICONID" : sport.sport.ICONID.name if sport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.money,
"SPNAME" : sport.name,
"SPORNO" : sport.sport.SPORNM,
"SPORID" : sport.id,
'STATE':sport.state,
"SPTIME" : sport.start.strftime('%Y%m%d%H%M'),
})
else:
data=[]
for sport in PersonSports.objects.filter(state__lt=4,members=user):
data.append({"DISTANCE":'',"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.cus.NICKNM,
"PICONID" : sport.cus.ICONID.name if sport.cus.ICONID else '',
"SICONID" : sport.sport.ICONID.name if sport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.money,
"SPNAME" : sport.name,
"SPORNO" : sport.sport.SPORNM,
"SPORID" : sport.id,
'STATE':sport.state,
"SPTIME" : sport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class QueryEnterSportsClub(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
location=request.POST.get('LOCATION','').strip()
if location:
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
data=[]
for sport in Shows.objects.filter(clubsport__state__lt=4,members=user):
site_wei=float(sport.site.LATITU)
site_jing=float(sport.site.LONGIT)
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.clubsport.cus.NICKNM,
"PLAYID":sport.id,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPORID" : sport.clubsport.id,
'STATE':sport.clubsport.state,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
else:
data=[]
for sport in Shows.objects.filter(clubsport__state__lt=4,members=user):
data.append({"DISTANCE":'',"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.clubsport.cus.NICKNM,
"PLAYID":sport.id,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPORID" : sport.clubsport.id,
'STATE':sport.clubsport.state,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class QueryStartSportsPeronal(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
location=request.POST.get('LOCATION','').strip()
state=request.POST.get('SPSTAT','').strip()
state=int(state)
if location:
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
data=[]
for sport in PersonSports.objects.filter(state=state,cus=user):
site_wei=float(sport.site.LATITU)
site_jing=float(sport.site.LONGIT)
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.cus.NICKNM,
"PICONID" : sport.cus.ICONID.name if sport.cus.ICONID else '',
"SICONID" : sport.sport.ICONID.name if sport.sport.ICONID else '' ,
"SPADDR" : sport.site.name,
"SPCOST" : sport.money,
"SPNAME" : sport.name,
"SPORNO" : sport.sport.SPORNM,
"SPORID" : sport.id,
'STATE':sport.state,
"SPTIME" : sport.start.strftime('%Y%m%d%H%M'),
})
else:
data=[]
for sport in PersonSports.objects.filter(state=state,cus=user):
data.append({"DISTANCE":'',"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.cus.NICKNM,
"PICONID" : sport.cus.ICONID.name if sport.cus.ICONID else '',
"SICONID" : sport.sport.ICONID.name if sport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.money,
"SPNAME" : sport.name,
"SPORNO" : sport.sport.SPORNM,
"SPORID" : sport.id,
'STATE':sport.state,
"SPTIME" : sport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class KickPersonPersonal(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_sport(self, pk):
try:
return PersonSports.objects.get(pk=int(pk))
except PersonSports.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
kickid=request.POST.get('KICKID','').strip()
sportid=request.POST.get('SPORID','').strip()
user=self.get_user(userid)
kick=self.get_user(kickid)
sport=self.get_sport(sportid)
if sport.cus==user:
sport.members.remove(kick)
sport.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class QueryOverSportsPeronal(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
location=request.POST.get('LOCATION','').strip()
if location:
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
data=[]
for sport in PersonSports.objects.filter(state=4,members=user):
site_wei=float(sport.site.LATITU)
site_jing=float(sport.site.LONGIT)
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.cus.NICKNM,
"PICONID" : sport.cus.ICONID.name if sport.cus.ICONID else '',
"SICONID" : sport.sport.ICONID.name if sport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.money,
"SPNAME" : sport.name,
"SPORNO" : sport.sport.SPORNM,
"SPORID" : sport.id,
'STATE':sport.state,
"SPTIME" : sport.start.strftime('%Y%m%d%H%M'),
})
else:
data=[]
for sport in PersonSports.objects.filter(state=4,members=user):
data.append({"DISTANCE":'',"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.cus.NICKNM,
"PICONID" : sport.cus.ICONID.name if sport.cus.ICONID else '',
"SICONID" : sport.sport.ICONID.name if sport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.money,
"SPNAME" : sport.name,
"SPORNO" : sport.sport.SPORNM,
"SPORID" : sport.id,
'STATE':sport.state,
"SPTIME" : sport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class QueryOverSportsClub(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
location=request.POST.get('LOCATION','').strip()
if location:
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
data=[]
for sport in Shows.objects.filter(clubsport__state=4,members=user):
site_wei=float(sport.site.LATITU)
site_jing=float(sport.site.LONGIT)
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.clubsport.cus.NICKNM,
"PLAYID":sport.id,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '' ,
"SPADDR" : sport.site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPORID" : sport.clubsport.id,
'STATE':sport.clubsport.state,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
else:
data=[]
for sport in Shows.objects.filter(clubsport__state=4,members=user):
data.append({"DISTANCE":'',"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.clubsport.cus.NICKNM,
"PLAYID":sport.id,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPORID" : sport.clubsport.id,
'STATE':sport.clubsport.state,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class GetMyF(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
style=request.POST.get('RELATP','').strip()
if int(style)==0:
data=user.friends.values('ICONID','NICKNM','PERAGE','SEXUAL','MOBILE')
for i in data:
i['INTERESTS']=self.get_user(i['MOBILE']).sports.values()
else:
data=user.blacks.values('ICONID','NICKNM','PERAGE','SEXUAL','MOBILE')
for i in data:
i['INTERESTS']=self.get_user(i['MOBILE']).sports.values()
return Response(data)
class RemoveMyF(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
fid=request.POST.get('RELAID','').strip()
user=self.get_user(userid)
f=self.get_user(fid)
style=request.POST.get('RELATP','').strip()
if int(style)==0:
user.friends.remove(f)
user.save()
else:
user.blacks.remove(f)
user.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class GetMessages(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
data=Message.objects.filter(touser=user,is_read=False).values('fromuser','fromuser__NICKNM','fromuser__ICONID','date','style','personalsport','show','content')
return Response(data)
class ClubCenter(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
data={"INTERESTS" : user.sports.values(),
"NICKNM" : user.NICKNM,
"RETCODE" : "0",
"RETPARAS" : "操作成功",
"INITIA" : ClubSports.objects.filter(state__lt=3,cus=user).count(),
}
if user.ICONID:
data['ICONID']=user.ICONID.name
else:
data['ICONID']=''
return Response(data)
class QueryClubCenter(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
data={"INTERESTS" : user.sports.values(),
"NICKNM" : user.NICKNM,
"RETCODE" : "0",
"RETPARAS" : "操作成功",
"INITIA" : ClubSports.objects.filter(state__lt=3,cus=user).count(),
"RECOMMENDS":user.sites.values(),
"MOBILE":user.MOBILE,
"RESUME":user.RESUME,
}
if user.ICONID:
data['ICONID']=user.ICONID.name
else:
data['ICONID']=''
return Response(data)
class QueryStartSportsClub(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
location=request.POST.get('LOCATION','').strip()
state=request.POST.get('SPSTAT','').strip()
state=int(state)
if location:
wei=float(location.split(',')[0])
jing=float(location.split(',')[1])
data=[]
for sport in Shows.objects.filter(clubsport__state=state,clubsport__cus=user):
site_wei=float(sport.site['LATITU'])
site_jing=float(sport.site['LONGIT'])
d=6370996*math.acos(math.cos(wei*3.14/180 )*math.cos(site_wei*3.14/180)*math.cos(jing*3.14/180 -site_jing*3.14/180)+math.sin(wei*3.14/180 )*math.sin(site_wei*3.14/180))
data.append({"DISTANCE":d,"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.clubsport.cus.NICKNM,
"PLAYID":sport.id,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPORID" : sport.clubsport.id,
'STATE':sport.clubsport.state,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
else:
data=[]
for sport in Shows.objects.filter(clubsport__state=state,clubsport__cus=user):
data.append({"DISTANCE":'',"HSJION":sport.members.count(),
"MAXPER" : sport.max_num,
"NICKNM" : sport.clubsport.cus.NICKNM,
"PLAYID":sport.id,
"PICONID" : sport.clubsport.cus.ICONID.name if sport.clubsport.cus.ICONID else '',
"SICONID" : sport.clubsport.sport.ICONID.name if sport.clubsport.sport.ICONID else '',
"SPADDR" : sport.site.name,
"SPCOST" : sport.clubsport.money,
"SPNAME" : sport.clubsport.name,
"SPORNO" : sport.clubsport.sport.SPORNM,
"SPORID" : sport.clubsport.id,
'STATE':sport.clubsport.state,
"SPTIME" : sport.clubsport.start.strftime('%Y%m%d%H%M'),
})
return Response(data)
class KickPersonClub(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_show(self, pk):
try:
return Shows.objects.get(pk=int(pk))
except Shows.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
kickid=request.POST.get('KICKID','').strip()
showid=request.POST.get('PLAYID','').strip()
user=self.get_user(userid)
kick=self.get_user(kickid)
show=self.get_show(showid)
if show.clubsport.cus==user:
show.members.remove(kick)
show.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class AddFriend(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
fromid=request.POST.get('FROMID','').strip()
toid=request.POST.get('TARGID','').strip()
style=request.POST.get('TYPE','').strip()
fromid=self.get_user(fromid)
to=self.get_user(toid)
Message.objects.create(fromuser=fromid,touser=to,style=1,\
)
data={"RETCODE":"0","RETPARAS":"操作成功"}
return Response(data)
class ApplyFriend(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def get_message(self, pk):
try:
return Message.objects.get(pk=int(pk))
except Message.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
addid=request.POST.get('RELAID','').strip()
messageid=request.POST.get('MESSAGEID','').strip()
user=self.get_user(userid)
add=self.get_user(addid)
message=self.get_message(messageid)
user.friends.add(add)
user.save()
add.friends.add(user)
add.save()
if message.fromuser==add or message.touser==add:
message.is_read=True
message.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class AddBlack(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
addid=request.POST.get('RELAID','').strip()
user=self.get_user(userid)
add=self.get_user(addid)
user.friends.remove(add)
user.blacks.add(add)
user.save()
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
class SetHead(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
user=self.get_user(userid)
img=request.FILES.get('FILEST','')
if img:
if img.size<3000000:
file_content = ContentFile(img.read())
user.ICONID.save(img.name, file_content)
else:
data={'success':False,'err_code':'too big img'}
return Response(data)
user.save()
if user.ICONID:
data={"RETCODE" : "0", "RETPARAS" : "操作成功",'ICONID':user.ICONID.name}
else:
data={'success':True,'phone':user.phone,'id':user.id}
return Response(data)
class CheckVersion(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def post(self, request, format=None):
versionnumber=request.POST.get('VERSNO','').strip()
version=Version.objects.last()
if version.version!=versionnumber:
data={
"DESCTX" : version.desc,
"DOWNUL" : version.download,
"NVERSNO" : version.version,
"PLSHDT" : version.date.strftime('%Y%m%d%H%M'),
"RETCODE" : "0",
"RETPARAS" : "您的软件有新的版本,请更新"
}
else:
data={"RETCODE" : "1","RETPARAS" : "无更新"}
return Response(data)
class MakeOpition(APIView):
authentication_classes = (UnsafeSessionAuthentication,)
permission_classes = (AllowAny,)
def get_user(self, phone):
try:
return MyUser.objects.get(MOBILE=phone)
except MyUser.DoesNotExist:
raise Http404
def post(self, request, format=None):
userid=request.POST.get('USERID','').strip()
content=request.POST.get('CONTEN','').strip()
user=self.get_user(userid)
Opition.objects.create(user=user,content=content)
data={"RETCODE" : "0", "RETPARAS" : "操作成功"}
return Response(data)
<file_sep>/theuser/models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone
from django.conf import settings
from yueqiu.models import Sport,Site
class MyUserManager(BaseUserManager):
def create_user(self, MOBILE, password):
if not MOBILE:
raise ValueError('Users must have an phone')
user = self.model(MOBILE=MOBILE)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, MOBILE, password):
user = self.create_user(MOBILE, password=<PASSWORD>)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
GENDER_CHOICES=(
(0,u'男'),
(1,u'女'),
)
CHOICES=(
(0,u'个人用户'),
(1,u'俱乐部'),
)
TCHOICES=(
(True,u'第三方登录'),
(False,u'非第三方登录'),
)
BCHOICES=(
(True,u'已绑定'),
(False,u'未绑定'),
)
MOBILE=models.CharField(max_length=20,unique=True,verbose_name='注册电话号码')
NICKNM=models.CharField(max_length=20,verbose_name='昵称',blank=True)
PERAGE=models.IntegerField(verbose_name='年龄',blank=True,null=True)
SEXUAL=models.IntegerField(choices=GENDER_CHOICES,verbose_name='性别',blank=True,null=True)
ICONID = models.ImageField(
upload_to='user',
verbose_name='头像',blank=True,null=True)
TYPE=models.IntegerField(choices=CHOICES,verbose_name='用户类型',default=0)
is_third=models.BooleanField(choices=TCHOICES,verbose_name='是否第三方',default=False)
openid=models.CharField(max_length=50,verbose_name='第三方id',blank=True)
is_bind=models.BooleanField(choices=BCHOICES,verbose_name='是否绑定手机',default=False)
RESUME=models.TextField(max_length=500,verbose_name='个人简介',blank=True)
good=models.IntegerField(verbose_name='好评数',default=0)
bad=models.IntegerField(verbose_name='差评数',default=0)
sports=models.ManyToManyField(Sport,verbose_name='兴趣',blank=True,null=True)
sites=models.ManyToManyField(Site,verbose_name='推荐场馆',blank=True,null=True)
friends=models.ManyToManyField(settings.AUTH_USER_MODEL,verbose_name='好友',blank=True,null=True,related_name='friendss')
blacks=models.ManyToManyField(settings.AUTH_USER_MODEL,verbose_name='黑名单',blank=True,null=True,related_name='blackss')
LATITU=models.CharField(max_length=20,verbose_name='纬度')
LONGIT=models.CharField(max_length=20,verbose_name='经度')
is_active = models.BooleanField(default=True,verbose_name='活跃用户')
is_admin = models.BooleanField(default=False,verbose_name='管理权限')
USERNAME_FIELD = 'MOBILE'
objects = MyUserManager()
def __unicode__(self):
return self.MOBILE
def get_full_name(self):
return self.MOBILE
def get_short_name(self):
return self.MOBILE
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?" # Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app ‘app_label‘?" # Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
# Simplest possible answer: All admins are staff
return self.is_admin
class Meta:
verbose_name = '用户'
verbose_name_plural = "用户"
class MyUserToken(models.Model):
phone=models.CharField(max_length=20,unique=True)
token=models.CharField(max_length=20)
pub_date=models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.phone
class Meta:
verbose_name = '验证码'
verbose_name_plural = "验证码"
<file_sep>/yueqiu/models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
class Sport(models.Model):
SPORNM=models.CharField(max_length=20,verbose_name='名称')
ename=models.CharField(max_length=20,verbose_name='英文名')
ICONID = models.ImageField(
upload_to='GiftType/%Y/%m/%d',
verbose_name='图像')
def __unicode__(self):
return self.SPORNM
class Meta:
verbose_name = '运动类型'
verbose_name_plural = "运动类型"
class Area(models.Model):
name=models.CharField(max_length=20,verbose_name='名称')
ename=models.CharField(max_length=20,verbose_name='英文名')
def __unicode__(self):
return self.name
class Meta:
verbose_name = '区域'
verbose_name_plural = "区域"
class Site(models.Model):
name=models.CharField(max_length=20,verbose_name='名称')
ename=models.CharField(max_length=20,verbose_name='英文名')
place=models.CharField(max_length=100,verbose_name='地址')
eplace=models.CharField(max_length=100,verbose_name='地址英文名')
LATITU=models.CharField(max_length=20,verbose_name='纬度')
LONGIT=models.CharField(max_length=20,verbose_name='经度')
area=models.ForeignKey(Area,verbose_name='区域')
keys=models.CharField(max_length=50,verbose_name='关键字')
def __unicode__(self):
return self.name
class Meta:
verbose_name = '场馆'
verbose_name_plural = "场馆"
class PersonSports(models.Model):
CHOICES=(
(1,'等待中'),
(2,'已确认'),
(3,'已取消'),
(4,'已结束'),
)
name=models.CharField(max_length=20,verbose_name='名称')
site=models.ForeignKey(Site,verbose_name='场馆')
start=models.DateTimeField(verbose_name='开始时间')
max_num=models.IntegerField(verbose_name='最大人数')
money=models.IntegerField(verbose_name='经费')
cus=models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name='发起人',related_name='cus')
sport=models.ForeignKey(Sport,verbose_name='活动类型')
desc=models.TextField(max_length=500,verbose_name='简介')
state=models.IntegerField(choices=CHOICES,verbose_name='活动状态')
members=models.ManyToManyField(settings.AUTH_USER_MODEL,verbose_name=u'报名参与者',related_name='member')
def __unicode__(self):
return self.name
class Meta:
verbose_name = '个人活动'
verbose_name_plural = "个人活动"
class ClubSports(models.Model):
CHOICES=(
(1,'等待中'),
(2,'已确认'),
(3,'已取消'),
(4,'已结束'),
)
name=models.CharField(max_length=20,verbose_name='名称')
start=models.DateTimeField(verbose_name='报名时间')
money=models.IntegerField(verbose_name='经费')
cus=models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name='发起人')
sport=models.ForeignKey(Sport,verbose_name='活动类型')
desc=models.TextField(max_length=500,verbose_name='简介')
state=models.IntegerField(choices=CHOICES,verbose_name='活动状态')
def __unicode__(self):
return self.name
class Meta:
verbose_name = '俱乐部活动'
verbose_name_plural = "俱乐部活动"
class Shows(models.Model):
playid=models.IntegerField(verbose_name='场次')
start=models.DateTimeField(verbose_name='开始时间')
end=models.DateTimeField(verbose_name='结束时间')
site=models.ForeignKey(Site,verbose_name='场馆')
max_num=models.IntegerField(verbose_name='最大人数')
clubsport=models.ForeignKey(ClubSports,verbose_name='所属俱乐部活动')
members=models.ManyToManyField(settings.AUTH_USER_MODEL,verbose_name=u'报名参与者')
def __unicode__(self):
return self.clubsport.name
class Meta:
verbose_name = '俱乐部活动场次'
verbose_name_plural = "俱乐部活动场次"
class Message(models.Model):
CHOICES=(
(1,'好友请求'),
(2,'邀请个人活动'),
(3,'邀请俱乐部活动'),
)
fromuser=models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name='发送者',related_name='from')
touser=models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name='接收者',related_name='to')
date=models.DateTimeField(auto_now_add=True,verbose_name='发送时间')
style=models.IntegerField(choices=CHOICES,verbose_name='请求类型')
personalsport=models.ForeignKey(PersonSports,verbose_name='邀请个人活动',blank=True,null=True)
show=models.ForeignKey(Shows,verbose_name='邀请俱乐部活动场次',blank=True,null=True)
is_read=models.BooleanField(verbose_name='是否已读',default=False)
content=models.TextField(verbose_name='内容',blank=True)
def __unicode__(self):
return self.fromuser.MOBILE
class Meta:
verbose_name = '信息'
verbose_name_plural = "信息"
class Comment(models.Model):
CHOICES=(
(1,'评价个人活动'),
(2,'评价俱乐部活动'),
)
user=models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name='评价者')
style=models.IntegerField(choices=CHOICES,verbose_name='评价类型')
personalsport=models.ForeignKey(PersonSports,verbose_name='邀请个人活动',blank=True,null=True)
show=models.ForeignKey(ClubSports,verbose_name='邀请俱乐部活动场次',blank=True,null=True)
content=models.TextField(verbose_name='内容')
def __unicode__(self):
return self.user.MOBILE
class Meta:
verbose_name = '活动评价'
verbose_name_plural = "活动评价"
class Love(models.Model):
user=models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name='用户')
sport=models.ForeignKey(Sport,verbose_name='运动')
star=models.IntegerField(verbose_name='热爱程度')
def __unicode__(self):
return self.user.MOBILE
class Meta:
verbose_name='个人爱好'
verbose_name_plural ="个人爱好"
class Version(models.Model):
version = models.CharField(max_length=16,verbose_name='版本号')
desc = models.CharField(max_length=16,verbose_name='版本描述')
download=models.CharField(max_length=100,verbose_name='下载地址')
date=models.DateTimeField(verbose_name='发布时间')
def __unicode__(self):
return self.version
def __cmp__(self, other):
if self.version.split('.') == other.version.split('.'):
return 0
if self.version.split('.') > other.version.split('.'):
return 1
return -1
class Meta:
verbose_name = u'版本'
verbose_name_plural = "版本"
class Opition(models.Model):
user=models.ForeignKey(settings.AUTH_USER_MODEL,verbose_name='用户')
content=models.TextField(verbose_name='内容')
date=models.DateTimeField(auto_now_add=True,verbose_name='发布时间')
def __unicode__(self):
return self.user.MOBILE
class Meta:
verbose_name='意见反馈'
verbose_name_plural ="意见反馈"
<file_sep>/yueqiu/admin.py
# -*- coding: utf-8 -*-
from django.contrib import admin
from yueqiu.models import Sport,Area,Site,PersonSports,ClubSports,Shows,Message,\
Comment,Love,Version,Opition
class PersonSportsAdmin(admin.ModelAdmin):
filter_horizontal = ('members',)
class ShowInline(admin.TabularInline):
model = Shows
filter_horizontal = ('members',)
class ClubAdmin(admin.ModelAdmin):
inlines = [
ShowInline,
]
class ShowsAdmin(admin.ModelAdmin):
filter_horizontal = ('members',)
admin.site.register(Sport,)
admin.site.register(Area,)
admin.site.register(Site,)
admin.site.register(PersonSports,PersonSportsAdmin)
admin.site.register(ClubSports,ClubAdmin)
admin.site.register(Shows,ShowsAdmin)
admin.site.register(Message,)
admin.site.register(Comment,)
admin.site.register(Love,)
admin.site.register(Version,)
admin.site.register(Opition,)
<file_sep>/yueqiu/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.urlpatterns import format_suffix_patterns
from yueqiu import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'yueqiu.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^user/validate_verifyCode/$', views.Reg.as_view()),
url(r'^user/data_improve/$', views.UpdateAndLogin.as_view()),
url(r'^user/verify_Code/$', views.VerCode.as_view()),
url(r'^user/login/$', views.Login.as_view()),
url(r'^user/modify_password/$', views.ModifyPW.as_view()),
url(r'^user/get_verifyCode/$', views.CreateToken.as_view()),
url(r'^user/third_login/$', views.ThirdLogin.as_view()),
url(r'^user/get_bind_stat/$', views.GetBindStat.as_view()),
url(r'^user/bind_mobile/$', views.BindMobile.as_view()),
url(r'^sport/create_personal_sport/$', views.CreatePersonalSport.as_view()),
url(r'^sport/create_club_sport/$', views.CreateClubSport.as_view()),
url(r'^sport/get_sport_Types/$', views.GetSportTypes.as_view()),
url(r'^sport/get_areas/$', views.GetAreas.as_view()),
url(r'^sport/attend_personal_sport/$', views.AttendPersonalSport.as_view()),
url(r'^sport/cancel_personal_sport/$', views.CancelPersonalSport.as_view()),
url(r'^sport/confirm_personal_sport/$', views.ConfirmPersonalSport.as_view()),
url(r'^sport/attend_club_sport/$', views.AttendClubSport.as_view()),
url(r'^sport/cancel_club_sport/$', views.CancelClubSport.as_view()),
url(r'^sport/confirm_club_sport/$', views.ConfirmClubSport.as_view()),
url(r'^sport/query_personal_sport/$', views.QueryPersonalSport.as_view()),
url(r'^sport/query_club_sport/$', views.QueryClubSport.as_view()),
url(r'^sport/query_attend_persons/$', views.QueryAttendPersonals.as_view()),
url(r'^sport/apply_for_sport/$', views.ApplyForSport.as_view()),
url(r'^lbs/mark_location/$', views.MarkLocation.as_view()),
url(r'^lbs/get_around_sites_by_name/$', views.GetSites.as_view()),
url(r'^lbs/get_around_sites/$', views.GetSites.as_view()),
url(r'^lbs/get_sportTypes_in_site/$', views.GetSportInSite.as_view()),
url(r'^sport/search_personal_sports/$', views.GetPlayInSite.as_view()),
url(r'^sport/search_club_sports/$', views.SearchClubSports.as_view()),
url(r'^manage/comment_user/$', views.CommentUser.as_view()),
url(r'^manage/comment_sport/$', views.CommentSport.as_view()),
url(r'^manage/select_my_love_sport/$', views.SelectMyLove.as_view()),
url(r'^manage/my_recomm_site/$', views.RecommSite.as_view()),
url(r'^manage/personal_center/$', views.UserCenter.as_view()),
url(r'^manage/basic_data_operate/$', views.UpdateUserData.as_view()),
url(r'^manage/query_personal_info/$', views.QueryUserCenter.as_view()),
url(r'^manage/query_enter_sports_personal/$', views.QueryEnterSportsPeronal.as_view()),
url(r'^manage/query_enter_sports_club/$', views.QueryEnterSportsClub.as_view()),
url(r'^manage/query_start_sports_personal/$', views.QueryStartSportsPeronal.as_view()),
url(r'^manage/kick_person_personal/$', views.KickPersonPersonal.as_view()),
url(r'^manage/query_over_sports_personal/$', views.QueryOverSportsPeronal.as_view()),
url(r'^manage/query_over_sports_club/$', views.QueryOverSportsClub.as_view()),
url(r'^manage/get_my_friends/$', views.GetMyF.as_view()),
url(r'^manage/delete_my_friends/$', views.RemoveMyF.as_view()),
url(r'^manage/get_sys_messages/$', views.GetMessages.as_view()),
url(r'^manage/club_center/$', views.ClubCenter.as_view()),
url(r'^manage/query_club_info/$', views.QueryClubCenter.as_view()),
url(r'^manage/query_start_sports_club/$', views.QueryStartSportsClub.as_view()),
url(r'^manage/kick_person_club/$', views.KickPersonClub.as_view()),
url(r'^manage/addfriend/$', views.AddFriend.as_view()),
url(r'^manage/apply_for_friend/$', views.ApplyFriend.as_view()),
url(r'^manage/blackers_operate/$', views.AddBlack.as_view()),
url(r'^manage/fileUpload/$', views.SetHead.as_view()),
url(r'^more/check_version/$', views.CheckVersion.as_view()),
url(r'^more/feedback/$', views.MakeOpition.as_view()),
url(r'^admin/', include(admin.site.urls)),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = format_suffix_patterns(urlpatterns)
| 427551a2c7561e82edd4e0533697c01a1eb77c3c | [
"Python"
] | 5 | Python | hungerr/yueqiu | 3cfdaf72df5f2707f32213476d10851e8104e58e | bfe3a0e73f6725d670cfa9dd60117affb66559d7 |
refs/heads/master | <file_sep>alert("This is the MDP Project G31 <NAME>");
var board;
var points1 = 0;
var points2 = 0;
var points3 = 0;
function mute(){
if(backdrop.muted == false){
backdrop.muted = true;
} else {
backdrop.muted = false;
}
}
$(document).ready(function() {
$("#choose-x").on("click", function() {
human1 = "X";
human2 = "O";
document.getElementById("opted").innerHTML="You've Chosen X";
});
$("#choose-o").on("click", function() {
human1 = "O";
human2 = "X";
document.getElementById("opted").innerHTML="You've Chosen O";
});
});
// Enemy screen buttons
$("#choose-human").on("click", function() {
cpuEnabled = false;
startGameHuman();
});
$("#choose-cpu").on("click", function() {
cpuEnabled = true;
document.getElementById("xscore").innerHTML="Your Score:";
document.getElementById("oscore").innerHTML="CPU Score:";
startGameComp();
});
function chooser(){
if (cpuEnabled===true){
startGameComp();
}
else{
startGameHuman();
}
}
var win=[
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
var currentTurn = 1;
var movesMade = 0;
var winnerContainer = $('.winner');
var reset = $('.reset');
var sqr = $('.square');
function showw(){
document.getElementById("option_choose").style.visibility="visible";
}
function showit(){
document.getElementById("play_against").style.visibility="visible";
}
function showit2(){
document.getElementById("open-button").style.visibility="visible";
}
function opengame(){
//document.getElementById("turn-tell").style.visibility="visible";
document.getElementById("gametable").style.display="block";
document.querySelector(".open-button").style.display="none";
document.querySelector(".close-button").style.display="block";
document.getElementById("scoring_data").style.visibility="visible";
document.getElementById("play_against").style.visibility="hidden";
document.getElementById("option_choose").style.visibility="hidden";
document.getElementById("playgame").style.visibility="hidden";
// document.getElementById("intro-screen").style.visibility="hidden";
}
function closegame(){
document.querySelector(".close-button").style.display="none";
document.querySelector(".open-button").style.display="block";
document.getElementById("gametable").style.display="none";
// document.getElementById("intro-screen").style.visibility="visible";
}
const cells=document.querySelectorAll('.cell');
// startGame();
function playsound() {
var a = new Audio('sound.mp3');
a.play();
}
function startGameComp(){
document.querySelector('.endgame').style.display='none';
board = Array.from(Array(9).keys());
for(var i=0;i<cells.length;i++){
cells[i].innerText='';
cells[i].style.removeProperty('background-color');
cells[i].addEventListener('click',playsound,false);
cells[i].addEventListener('click',turnClickComp,false);
}
}
function startGameHuman(){
document.querySelector('.endgame').style.display='none';
board = Array.from(Array(9).keys());
for(var i=0;i<cells.length;i++){
cells[i].innerText='';
cells[i].style.removeProperty('background-color');
cells[i].addEventListener('click',playsound,false);
cells[i].addEventListener('click',turnClickHuman,false);
}
}
function turnClickComp(square){
if (typeof board[square.target.id] == 'number') {
turn(square.target.id, human1);
if (!checkTie()) turn(bestSpot(), human2);
}
}
function turnClickHuman(square){
if (typeof board[square.target.id] == 'number') {
if (currentTurn % 2 === 1) {
turn(square.target.id, human1);
currentTurn++;
} else {
turn(square.target.id, human2);
currentTurn--;
}
if (!checkTie()) turn(turnClickHuman());
// theWinner = currentTurn == 1 ? human2 : human1;
// declareWinner(theWinner);
// }
}
}
function turn(squareId,player){
board[squareId]=player;
document.getElementById(squareId).innerText = player;
let gameWon = checkWin(board, player)
if (gameWon){
gameOver(gameWon);
}
}
function checkWin(board, player) {
let plays = board.reduce((a, e, i) =>
(e === player) ? a.concat(i) : a, []);
let gameWon = null;
for (let [index, wins] of win.entries()) {
if (wins.every(elem => plays.indexOf(elem) > -1)) {
gameWon = {index: index, player: player};
break;
}
}
return gameWon;
}
function gameOver(gameWon) {
for (let index of win[gameWon.index]) {
document.getElementById(index).style.backgroundColor =
gameWon.player == human1 ? "grey" : "grey";
}
for (var i = 0; i < cells.length; i++) {
cells[i].removeEventListener('click', turnClickComp, false);
cells[i].removeEventListener('click', turnClickHuman, false);
}
if (cpuEnabled===true){
declareWinner(gameWon.player==human1?"Player 1 Wins!":"CPU Wins!");
}
else{
declareWinner(gameWon.player==human1?"Player 1 Wins!":"Player 2 Wins!");
}
if (gameWon.player===human1){
points1++;
document.getElementById("computer_score").innerHTML = points1;
console.log(points1);
}
else if(gameWon.player===human2){
points2++;
document.getElementById("player_score").innerHTML = points2;
console.log(points2);
}
//else{
// points3++;
// document.getElementById("tie_score").innerHTML = points3;
// }
}
function declareWinner(who) {
document.querySelector(".endgame").style.display = "block";
document.querySelector(".endgame .text").innerText = who;
}
function emptySquares() {
return board.filter(s => typeof s == 'number');
}
function bestSpot() {
return minimax(board,human2).index;
}
function checkTie() {
if (emptySquares().length == 0) {
for (var i = 0; i < cells.length; i++) {
cells[i].style.backgroundColor = "grey";
cells[i].removeEventListener('click', turnClickComp, false);
cells[i].removeEventListener('click', turnClickHuman, false);
}
declareWinner("Tie Game!")
points3++;
document.getElementById("tie_score").innerHTML = points3;
return true;
}
return false;
}
function minimax(newBoard, player) {
var availSpots = emptySquares();
if (checkWin(newBoard, human1)) {
return {score: -10};
} else if (checkWin(newBoard, human2)) {
return {score: 10};
} else if (availSpots.length === 0) {
return {score: 0};
}
var moves = [];
for (var i = 0; i < availSpots.length; i++) {
var move = {};
move.index = newBoard[availSpots[i]];
newBoard[availSpots[i]] = player;
if (player == human2) {
var result = minimax(newBoard, human1);
move.score = result.score;
} else {
var result = minimax(newBoard, human2);
move.score = result.score;
}
newBoard[availSpots[i]] = move.index;
moves.push(move);
}
var bestMove;
if(player === human2) {
var bestScore = -10000;
for(var i = 0; i < moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
var bestScore = 10000;
for(var i = 0; i < moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
return moves[bestMove];
} | 5b3657fd0fe4b7a2018d9af9382fa326fbc0d43b | [
"JavaScript"
] | 1 | JavaScript | mananthakkar24/TicTacToeMDP | 1c78b89ef7c422fd6887699bb8e57b1910b099d2 | b1cb1d811a238c865483f668e7666d1446093e69 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.